/
locid.cpp
2547 lines (2262 loc) Β· 76.3 KB
/
locid.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Β© 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (C) 1997-2016, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*
* File locid.cpp
*
* Created by: Richard Gillam
*
* Modification History:
*
* Date Name Description
* 02/11/97 aliu Changed gLocPath to fgDataDirectory and added
* methods to get and set it.
* 04/02/97 aliu Made operator!= inline; fixed return value
* of getName().
* 04/15/97 aliu Cleanup for AIX/Win32.
* 04/24/97 aliu Numerous changes per code review.
* 08/18/98 stephen Changed getDisplayName()
* Added SIMPLIFIED_CHINESE, TRADITIONAL_CHINESE
* Added getISOCountries(), getISOLanguages(),
* getLanguagesForCountry()
* 03/16/99 bertrand rehaul.
* 07/21/99 stephen Added U_CFUNC setDefault
* 11/09/99 weiv Added const char * getName() const;
* 04/12/00 srl removing unicodestring api's and cached hash code
* 08/10/01 grhoten Change the static Locales to accessor functions
******************************************************************************
*/
#include <utility>
#include "unicode/bytestream.h"
#include "unicode/locid.h"
#include "unicode/localebuilder.h"
#include "unicode/strenum.h"
#include "unicode/stringpiece.h"
#include "unicode/uloc.h"
#include "unicode/ures.h"
#include "bytesinkutil.h"
#include "charstr.h"
#include "charstrmap.h"
#include "cmemory.h"
#include "cstring.h"
#include "mutex.h"
#include "putilimp.h"
#include "uassert.h"
#include "ucln_cmn.h"
#include "uhash.h"
#include "ulocimp.h"
#include "umutex.h"
#include "uniquecharstr.h"
#include "ustr_imp.h"
#include "uvector.h"
U_CDECL_BEGIN
static UBool U_CALLCONV locale_cleanup(void);
U_CDECL_END
U_NAMESPACE_BEGIN
static Locale *gLocaleCache = NULL;
static UInitOnce gLocaleCacheInitOnce = U_INITONCE_INITIALIZER;
// gDefaultLocaleMutex protects all access to gDefaultLocalesHashT and gDefaultLocale.
static UMutex gDefaultLocaleMutex;
static UHashtable *gDefaultLocalesHashT = NULL;
static Locale *gDefaultLocale = NULL;
/**
* \def ULOC_STRING_LIMIT
* strings beyond this value crash in CharString
*/
#define ULOC_STRING_LIMIT 357913941
U_NAMESPACE_END
typedef enum ELocalePos {
eENGLISH,
eFRENCH,
eGERMAN,
eITALIAN,
eJAPANESE,
eKOREAN,
eCHINESE,
eFRANCE,
eGERMANY,
eITALY,
eJAPAN,
eKOREA,
eCHINA, /* Alias for PRC */
eTAIWAN,
eUK,
eUS,
eCANADA,
eCANADA_FRENCH,
eROOT,
//eDEFAULT,
eMAX_LOCALES
} ELocalePos;
U_CDECL_BEGIN
//
// Deleter function for Locales owned by the default Locale hash table/
//
static void U_CALLCONV
deleteLocale(void *obj) {
delete (icu::Locale *) obj;
}
static UBool U_CALLCONV locale_cleanup(void)
{
U_NAMESPACE_USE
delete [] gLocaleCache;
gLocaleCache = NULL;
gLocaleCacheInitOnce.reset();
if (gDefaultLocalesHashT) {
uhash_close(gDefaultLocalesHashT); // Automatically deletes all elements, using deleter func.
gDefaultLocalesHashT = NULL;
}
gDefaultLocale = NULL;
return TRUE;
}
static void U_CALLCONV locale_init(UErrorCode &status) {
U_NAMESPACE_USE
U_ASSERT(gLocaleCache == NULL);
gLocaleCache = new Locale[(int)eMAX_LOCALES];
if (gLocaleCache == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
ucln_common_registerCleanup(UCLN_COMMON_LOCALE, locale_cleanup);
gLocaleCache[eROOT] = Locale("");
gLocaleCache[eENGLISH] = Locale("en");
gLocaleCache[eFRENCH] = Locale("fr");
gLocaleCache[eGERMAN] = Locale("de");
gLocaleCache[eITALIAN] = Locale("it");
gLocaleCache[eJAPANESE] = Locale("ja");
gLocaleCache[eKOREAN] = Locale("ko");
gLocaleCache[eCHINESE] = Locale("zh");
gLocaleCache[eFRANCE] = Locale("fr", "FR");
gLocaleCache[eGERMANY] = Locale("de", "DE");
gLocaleCache[eITALY] = Locale("it", "IT");
gLocaleCache[eJAPAN] = Locale("ja", "JP");
gLocaleCache[eKOREA] = Locale("ko", "KR");
gLocaleCache[eCHINA] = Locale("zh", "CN");
gLocaleCache[eTAIWAN] = Locale("zh", "TW");
gLocaleCache[eUK] = Locale("en", "GB");
gLocaleCache[eUS] = Locale("en", "US");
gLocaleCache[eCANADA] = Locale("en", "CA");
gLocaleCache[eCANADA_FRENCH] = Locale("fr", "CA");
}
U_CDECL_END
U_NAMESPACE_BEGIN
Locale *locale_set_default_internal(const char *id, UErrorCode& status) {
// Synchronize this entire function.
Mutex lock(&gDefaultLocaleMutex);
UBool canonicalize = FALSE;
// If given a NULL string for the locale id, grab the default
// name from the system.
// (Different from most other locale APIs, where a null name means use
// the current ICU default locale.)
if (id == NULL) {
id = uprv_getDefaultLocaleID(); // This function not thread safe? TODO: verify.
canonicalize = TRUE; // always canonicalize host ID
}
CharString localeNameBuf;
{
CharStringByteSink sink(&localeNameBuf);
if (canonicalize) {
ulocimp_canonicalize(id, sink, &status);
} else {
ulocimp_getName(id, sink, &status);
}
}
if (U_FAILURE(status)) {
return gDefaultLocale;
}
if (gDefaultLocalesHashT == NULL) {
gDefaultLocalesHashT = uhash_open(uhash_hashChars, uhash_compareChars, NULL, &status);
if (U_FAILURE(status)) {
return gDefaultLocale;
}
uhash_setValueDeleter(gDefaultLocalesHashT, deleteLocale);
ucln_common_registerCleanup(UCLN_COMMON_LOCALE, locale_cleanup);
}
Locale *newDefault = (Locale *)uhash_get(gDefaultLocalesHashT, localeNameBuf.data());
if (newDefault == NULL) {
newDefault = new Locale(Locale::eBOGUS);
if (newDefault == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return gDefaultLocale;
}
newDefault->init(localeNameBuf.data(), FALSE);
uhash_put(gDefaultLocalesHashT, (char*) newDefault->getName(), newDefault, &status);
if (U_FAILURE(status)) {
return gDefaultLocale;
}
}
gDefaultLocale = newDefault;
return gDefaultLocale;
}
U_NAMESPACE_END
/* sfb 07/21/99 */
U_CFUNC void
locale_set_default(const char *id)
{
U_NAMESPACE_USE
UErrorCode status = U_ZERO_ERROR;
locale_set_default_internal(id, status);
}
/* end */
U_CFUNC const char *
locale_get_default(void)
{
U_NAMESPACE_USE
return Locale::getDefault().getName();
}
U_NAMESPACE_BEGIN
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Locale)
/*Character separating the posix id fields*/
// '_'
// In the platform codepage.
#define SEP_CHAR '_'
#define NULL_CHAR '\0'
Locale::~Locale()
{
if (baseName != fullName) {
uprv_free(baseName);
}
baseName = NULL;
/*if fullName is on the heap, we free it*/
if (fullName != fullNameBuffer)
{
uprv_free(fullName);
fullName = NULL;
}
}
Locale::Locale()
: UObject(), fullName(fullNameBuffer), baseName(NULL)
{
init(NULL, FALSE);
}
/*
* Internal constructor to allow construction of a locale object with
* NO side effects. (Default constructor tries to get
* the default locale.)
*/
Locale::Locale(Locale::ELocaleType)
: UObject(), fullName(fullNameBuffer), baseName(NULL)
{
setToBogus();
}
Locale::Locale( const char * newLanguage,
const char * newCountry,
const char * newVariant,
const char * newKeywords)
: UObject(), fullName(fullNameBuffer), baseName(NULL)
{
if( (newLanguage==NULL) && (newCountry == NULL) && (newVariant == NULL) )
{
init(NULL, FALSE); /* shortcut */
}
else
{
UErrorCode status = U_ZERO_ERROR;
int32_t size = 0;
int32_t lsize = 0;
int32_t csize = 0;
int32_t vsize = 0;
int32_t ksize = 0;
// Calculate the size of the resulting string.
// Language
if ( newLanguage != NULL )
{
lsize = (int32_t)uprv_strlen(newLanguage);
if ( lsize < 0 || lsize > ULOC_STRING_LIMIT ) { // int32 wrap
setToBogus();
return;
}
size = lsize;
}
CharString togo(newLanguage, lsize, status); // start with newLanguage
// _Country
if ( newCountry != NULL )
{
csize = (int32_t)uprv_strlen(newCountry);
if ( csize < 0 || csize > ULOC_STRING_LIMIT ) { // int32 wrap
setToBogus();
return;
}
size += csize;
}
// _Variant
if ( newVariant != NULL )
{
// remove leading _'s
while(newVariant[0] == SEP_CHAR)
{
newVariant++;
}
// remove trailing _'s
vsize = (int32_t)uprv_strlen(newVariant);
if ( vsize < 0 || vsize > ULOC_STRING_LIMIT ) { // int32 wrap
setToBogus();
return;
}
while( (vsize>1) && (newVariant[vsize-1] == SEP_CHAR) )
{
vsize--;
}
}
if( vsize > 0 )
{
size += vsize;
}
// Separator rules:
if ( vsize > 0 )
{
size += 2; // at least: __v
}
else if ( csize > 0 )
{
size += 1; // at least: _v
}
if ( newKeywords != NULL)
{
ksize = (int32_t)uprv_strlen(newKeywords);
if ( ksize < 0 || ksize > ULOC_STRING_LIMIT ) {
setToBogus();
return;
}
size += ksize + 1;
}
// NOW we have the full locale string..
// Now, copy it back.
// newLanguage is already copied
if ( ( vsize != 0 ) || (csize != 0) ) // at least: __v
{ // ^
togo.append(SEP_CHAR, status);
}
if ( csize != 0 )
{
togo.append(newCountry, status);
}
if ( vsize != 0)
{
togo.append(SEP_CHAR, status)
.append(newVariant, vsize, status);
}
if ( ksize != 0)
{
if (uprv_strchr(newKeywords, '=')) {
togo.append('@', status); /* keyword parsing */
}
else {
togo.append('_', status); /* Variant parsing with a script */
if ( vsize == 0) {
togo.append('_', status); /* No country found */
}
}
togo.append(newKeywords, status);
}
if (U_FAILURE(status)) {
// Something went wrong with appending, etc.
setToBogus();
return;
}
// Parse it, because for example 'language' might really be a complete
// string.
init(togo.data(), FALSE);
}
}
Locale::Locale(const Locale &other)
: UObject(other), fullName(fullNameBuffer), baseName(NULL)
{
*this = other;
}
Locale::Locale(Locale&& other) U_NOEXCEPT
: UObject(other), fullName(fullNameBuffer), baseName(fullName) {
*this = std::move(other);
}
Locale& Locale::operator=(const Locale& other) {
if (this == &other) {
return *this;
}
setToBogus();
if (other.fullName == other.fullNameBuffer) {
uprv_strcpy(fullNameBuffer, other.fullNameBuffer);
} else if (other.fullName == nullptr) {
fullName = nullptr;
} else {
fullName = uprv_strdup(other.fullName);
if (fullName == nullptr) return *this;
}
if (other.baseName == other.fullName) {
baseName = fullName;
} else if (other.baseName != nullptr) {
baseName = uprv_strdup(other.baseName);
if (baseName == nullptr) return *this;
}
uprv_strcpy(language, other.language);
uprv_strcpy(script, other.script);
uprv_strcpy(country, other.country);
variantBegin = other.variantBegin;
fIsBogus = other.fIsBogus;
return *this;
}
Locale& Locale::operator=(Locale&& other) U_NOEXCEPT {
if (baseName != fullName) uprv_free(baseName);
if (fullName != fullNameBuffer) uprv_free(fullName);
if (other.fullName == other.fullNameBuffer) {
uprv_strcpy(fullNameBuffer, other.fullNameBuffer);
fullName = fullNameBuffer;
} else {
fullName = other.fullName;
}
if (other.baseName == other.fullName) {
baseName = fullName;
} else {
baseName = other.baseName;
}
uprv_strcpy(language, other.language);
uprv_strcpy(script, other.script);
uprv_strcpy(country, other.country);
variantBegin = other.variantBegin;
fIsBogus = other.fIsBogus;
other.baseName = other.fullName = other.fullNameBuffer;
return *this;
}
Locale *
Locale::clone() const {
return new Locale(*this);
}
UBool
Locale::operator==( const Locale& other) const
{
return (uprv_strcmp(other.fullName, fullName) == 0);
}
namespace {
UInitOnce gKnownCanonicalizedInitOnce = U_INITONCE_INITIALIZER;
UHashtable *gKnownCanonicalized = nullptr;
static const char* const KNOWN_CANONICALIZED[] = {
"c",
// Commonly used locales known are already canonicalized
"af", "af_ZA", "am", "am_ET", "ar", "ar_001", "as", "as_IN", "az", "az_AZ",
"be", "be_BY", "bg", "bg_BG", "bn", "bn_IN", "bs", "bs_BA", "ca", "ca_ES",
"cs", "cs_CZ", "cy", "cy_GB", "da", "da_DK", "de", "de_DE", "el", "el_GR",
"en", "en_GB", "en_US", "es", "es_419", "es_ES", "et", "et_EE", "eu",
"eu_ES", "fa", "fa_IR", "fi", "fi_FI", "fil", "fil_PH", "fr", "fr_FR",
"ga", "ga_IE", "gl", "gl_ES", "gu", "gu_IN", "he", "he_IL", "hi", "hi_IN",
"hr", "hr_HR", "hu", "hu_HU", "hy", "hy_AM", "id", "id_ID", "is", "is_IS",
"it", "it_IT", "ja", "ja_JP", "jv", "jv_ID", "ka", "ka_GE", "kk", "kk_KZ",
"km", "km_KH", "kn", "kn_IN", "ko", "ko_KR", "ky", "ky_KG", "lo", "lo_LA",
"lt", "lt_LT", "lv", "lv_LV", "mk", "mk_MK", "ml", "ml_IN", "mn", "mn_MN",
"mr", "mr_IN", "ms", "ms_MY", "my", "my_MM", "nb", "nb_NO", "ne", "ne_NP",
"nl", "nl_NL", "or", "or_IN", "pa", "pa_IN", "pl", "pl_PL", "ps", "ps_AF",
"pt", "pt_BR", "pt_PT", "ro", "ro_RO", "ru", "ru_RU", "sd", "sd_IN", "si",
"si_LK", "sk", "sk_SK", "sl", "sl_SI", "so", "so_SO", "sq", "sq_AL", "sr",
"sr_Cyrl_RS", "sr_Latn", "sr_RS", "sv", "sv_SE", "sw", "sw_TZ", "ta",
"ta_IN", "te", "te_IN", "th", "th_TH", "tk", "tk_TM", "tr", "tr_TR", "uk",
"uk_UA", "ur", "ur_PK", "uz", "uz_UZ", "vi", "vi_VN", "yue", "yue_Hant",
"yue_Hant_HK", "yue_HK", "zh", "zh_CN", "zh_Hans", "zh_Hans_CN", "zh_Hant",
"zh_Hant_TW", "zh_TW", "zu", "zu_ZA"
};
static UBool U_CALLCONV cleanupKnownCanonicalized() {
gKnownCanonicalizedInitOnce.reset();
if (gKnownCanonicalized) { uhash_close(gKnownCanonicalized); }
return TRUE;
}
static void U_CALLCONV loadKnownCanonicalized(UErrorCode &status) {
ucln_common_registerCleanup(UCLN_COMMON_LOCALE_KNOWN_CANONICALIZED,
cleanupKnownCanonicalized);
LocalUHashtablePointer newKnownCanonicalizedMap(
uhash_open(uhash_hashChars, uhash_compareChars, nullptr, &status));
for (int32_t i = 0;
U_SUCCESS(status) && i < UPRV_LENGTHOF(KNOWN_CANONICALIZED);
i++) {
uhash_puti(newKnownCanonicalizedMap.getAlias(),
(void*)KNOWN_CANONICALIZED[i],
1, &status);
}
if (U_FAILURE(status)) {
return;
}
gKnownCanonicalized = newKnownCanonicalizedMap.orphan();
}
class AliasData;
/**
* A Builder class to build the alias data.
*/
class AliasDataBuilder {
public:
AliasDataBuilder() {
}
// Build the AliasData from resource.
AliasData* build(UErrorCode &status);
private:
void readAlias(UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length,
void (*checkType)(const char* type),
void (*checkReplacement)(const UnicodeString& replacement),
UErrorCode &status);
// Read the languageAlias data from alias to
// strings+types+replacementIndexes
// The number of record will be stored into length.
// Allocate length items for types, to store the type field.
// Allocate length items for replacementIndexes,
// to store the index in the strings for the replacement script.
void readLanguageAlias(UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length,
UErrorCode &status);
// Read the scriptAlias data from alias to
// strings+types+replacementIndexes
// Allocate length items for types, to store the type field.
// Allocate length items for replacementIndexes,
// to store the index in the strings for the replacement script.
void readScriptAlias(UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length, UErrorCode &status);
// Read the territoryAlias data from alias to
// strings+types+replacementIndexes
// Allocate length items for types, to store the type field.
// Allocate length items for replacementIndexes,
// to store the index in the strings for the replacement script.
void readTerritoryAlias(UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length, UErrorCode &status);
// Read the variantAlias data from alias to
// strings+types+replacementIndexes
// Allocate length items for types, to store the type field.
// Allocate length items for replacementIndexes,
// to store the index in the strings for the replacement variant.
void readVariantAlias(UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length, UErrorCode &status);
};
/**
* A class to hold the Alias Data.
*/
class AliasData : public UMemory {
public:
static const AliasData* singleton(UErrorCode& status) {
if (U_FAILURE(status)) {
// Do not get into loadData if the status already has error.
return nullptr;
}
umtx_initOnce(AliasData::gInitOnce, &AliasData::loadData, status);
return gSingleton;
}
const CharStringMap& languageMap() const { return language; }
const CharStringMap& scriptMap() const { return script; }
const CharStringMap& territoryMap() const { return territory; }
const CharStringMap& variantMap() const { return variant; }
static void U_CALLCONV loadData(UErrorCode &status);
static UBool U_CALLCONV cleanup();
static UInitOnce gInitOnce;
private:
AliasData(CharStringMap languageMap,
CharStringMap scriptMap,
CharStringMap territoryMap,
CharStringMap variantMap,
CharString* strings)
: language(std::move(languageMap)),
script(std::move(scriptMap)),
territory(std::move(territoryMap)),
variant(std::move(variantMap)),
strings(strings) {
}
~AliasData() {
delete strings;
}
static const AliasData* gSingleton;
CharStringMap language;
CharStringMap script;
CharStringMap territory;
CharStringMap variant;
CharString* strings;
friend class AliasDataBuilder;
};
const AliasData* AliasData::gSingleton = nullptr;
UInitOnce AliasData::gInitOnce = U_INITONCE_INITIALIZER;
UBool U_CALLCONV
AliasData::cleanup()
{
gInitOnce.reset();
delete gSingleton;
return TRUE;
}
void
AliasDataBuilder::readAlias(
UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length,
void (*checkType)(const char* type),
void (*checkReplacement)(const UnicodeString& replacement),
UErrorCode &status) {
if (U_FAILURE(status)) {
return;
}
length = ures_getSize(alias);
const char** rawTypes = types.allocateInsteadAndCopy(length);
if (rawTypes == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
int32_t* rawIndexes = replacementIndexes.allocateInsteadAndCopy(length);
if (rawIndexes == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
int i = 0;
while (ures_hasNext(alias)) {
LocalUResourceBundlePointer res(
ures_getNextResource(alias, nullptr, &status));
const char* aliasFrom = ures_getKey(res.getAlias());
UnicodeString aliasTo =
ures_getUnicodeStringByKey(res.getAlias(), "replacement", &status);
checkType(aliasFrom);
checkReplacement(aliasTo);
rawTypes[i] = aliasFrom;
rawIndexes[i] = strings->add(aliasTo, status);
i++;
}
}
/**
* Read the languageAlias data from alias to strings+types+replacementIndexes.
* Allocate length items for types, to store the type field. Allocate length
* items for replacementIndexes, to store the index in the strings for the
* replacement language.
*/
void
AliasDataBuilder::readLanguageAlias(
UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length,
UErrorCode &status)
{
return readAlias(
alias, strings, types, replacementIndexes, length,
#if U_DEBUG
[](const char* type) {
// Assert the aliasFrom only contains the following possibilties
// language_REGION_variant
// language_REGION
// language_variant
// language
// und_variant
Locale test(type);
// Assert no script in aliasFrom
U_ASSERT(test.getScript()[0] == '\0');
// Assert when language is und, no REGION in aliasFrom.
U_ASSERT(test.getLanguage()[0] != '\0' || test.getCountry()[0] == '\0');
},
#else
[](const char*) {},
#endif
[](const UnicodeString&) {}, status);
}
/**
* Read the scriptAlias data from alias to strings+types+replacementIndexes.
* Allocate length items for types, to store the type field. Allocate length
* items for replacementIndexes, to store the index in the strings for the
* replacement script.
*/
void
AliasDataBuilder::readScriptAlias(
UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length,
UErrorCode &status)
{
return readAlias(
alias, strings, types, replacementIndexes, length,
#if U_DEBUG
[](const char* type) {
U_ASSERT(uprv_strlen(type) == 4);
},
[](const UnicodeString& replacement) {
U_ASSERT(replacement.length() == 4);
},
#else
[](const char*) {},
[](const UnicodeString&) { },
#endif
status);
}
/**
* Read the territoryAlias data from alias to strings+types+replacementIndexes.
* Allocate length items for types, to store the type field. Allocate length
* items for replacementIndexes, to store the index in the strings for the
* replacement regions.
*/
void
AliasDataBuilder::readTerritoryAlias(
UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length,
UErrorCode &status)
{
return readAlias(
alias, strings, types, replacementIndexes, length,
#if U_DEBUG
[](const char* type) {
U_ASSERT(uprv_strlen(type) == 2 || uprv_strlen(type) == 3);
},
#else
[](const char*) {},
#endif
[](const UnicodeString&) { },
status);
}
/**
* Read the variantAlias data from alias to strings+types+replacementIndexes.
* Allocate length items for types, to store the type field. Allocate length
* items for replacementIndexes, to store the index in the strings for the
* replacement variant.
*/
void
AliasDataBuilder::readVariantAlias(
UResourceBundle* alias,
UniqueCharStrings* strings,
LocalMemory<const char*>& types,
LocalMemory<int32_t>& replacementIndexes,
int32_t &length,
UErrorCode &status)
{
return readAlias(
alias, strings, types, replacementIndexes, length,
#if U_DEBUG
[](const char* type) {
U_ASSERT(uprv_strlen(type) >= 4 && uprv_strlen(type) <= 8);
U_ASSERT(uprv_strlen(type) != 4 ||
(type[0] >= '0' && type[0] <= '9'));
},
[](const UnicodeString& replacement) {
U_ASSERT(replacement.length() >= 4 && replacement.length() <= 8);
U_ASSERT(replacement.length() != 4 ||
(replacement.charAt(0) >= u'0' &&
replacement.charAt(0) <= u'9'));
},
#else
[](const char*) {},
[](const UnicodeString&) { },
#endif
status);
}
/**
* Initializes the alias data from the ICU resource bundles. The alias data
* contains alias of language, country, script and variants.
*
* If the alias data has already loaded, then this method simply returns without
* doing anything meaningful.
*/
void U_CALLCONV
AliasData::loadData(UErrorCode &status)
{
#ifdef LOCALE_CANONICALIZATION_DEBUG
UDate start = uprv_getRawUTCtime();
#endif // LOCALE_CANONICALIZATION_DEBUG
ucln_common_registerCleanup(UCLN_COMMON_LOCALE_ALIAS, cleanup);
AliasDataBuilder builder;
gSingleton = builder.build(status);
#ifdef LOCALE_CANONICALIZATION_DEBUG
UDate end = uprv_getRawUTCtime();
printf("AliasData::loadData took total %f ms\n", end - start);
#endif // LOCALE_CANONICALIZATION_DEBUG
}
/**
* Build the alias data from resources.
*/
AliasData*
AliasDataBuilder::build(UErrorCode &status) {
LocalUResourceBundlePointer metadata(
ures_openDirect(nullptr, "metadata", &status));
LocalUResourceBundlePointer metadataAlias(
ures_getByKey(metadata.getAlias(), "alias", nullptr, &status));
LocalUResourceBundlePointer languageAlias(
ures_getByKey(metadataAlias.getAlias(), "language", nullptr, &status));
LocalUResourceBundlePointer scriptAlias(
ures_getByKey(metadataAlias.getAlias(), "script", nullptr, &status));
LocalUResourceBundlePointer territoryAlias(
ures_getByKey(metadataAlias.getAlias(), "territory", nullptr, &status));
LocalUResourceBundlePointer variantAlias(
ures_getByKey(metadataAlias.getAlias(), "variant", nullptr, &status));
if (U_FAILURE(status)) {
return nullptr;
}
int32_t languagesLength = 0, scriptLength = 0, territoryLength = 0,
variantLength = 0;
// Read the languageAlias into languageTypes, languageReplacementIndexes
// and strings
UniqueCharStrings strings(status);
LocalMemory<const char*> languageTypes;
LocalMemory<int32_t> languageReplacementIndexes;
readLanguageAlias(languageAlias.getAlias(),
&strings,
languageTypes,
languageReplacementIndexes,
languagesLength,
status);
// Read the scriptAlias into scriptTypes, scriptReplacementIndexes
// and strings
LocalMemory<const char*> scriptTypes;
LocalMemory<int32_t> scriptReplacementIndexes;
readScriptAlias(scriptAlias.getAlias(),
&strings,
scriptTypes,
scriptReplacementIndexes,
scriptLength,
status);
// Read the territoryAlias into territoryTypes, territoryReplacementIndexes
// and strings
LocalMemory<const char*> territoryTypes;
LocalMemory<int32_t> territoryReplacementIndexes;
readTerritoryAlias(territoryAlias.getAlias(),
&strings,
territoryTypes,
territoryReplacementIndexes,
territoryLength, status);
// Read the variantAlias into variantTypes, variantReplacementIndexes
// and strings
LocalMemory<const char*> variantTypes;
LocalMemory<int32_t> variantReplacementIndexes;
readVariantAlias(variantAlias.getAlias(),
&strings,
variantTypes,
variantReplacementIndexes,
variantLength, status);
if (U_FAILURE(status)) {
return nullptr;
}
// We can only use strings after freeze it.
strings.freeze();
// Build the languageMap from languageTypes & languageReplacementIndexes
CharStringMap languageMap(490, status);
for (int32_t i = 0; U_SUCCESS(status) && i < languagesLength; i++) {
languageMap.put(languageTypes[i],
strings.get(languageReplacementIndexes[i]),
status);
}
// Build the scriptMap from scriptTypes & scriptReplacementIndexes
CharStringMap scriptMap(1, status);
for (int32_t i = 0; U_SUCCESS(status) && i < scriptLength; i++) {
scriptMap.put(scriptTypes[i],
strings.get(scriptReplacementIndexes[i]),
status);
}
// Build the territoryMap from territoryTypes & territoryReplacementIndexes
CharStringMap territoryMap(650, status);
for (int32_t i = 0; U_SUCCESS(status) && i < territoryLength; i++) {
territoryMap.put(territoryTypes[i],
strings.get(territoryReplacementIndexes[i]),
status);
}
// Build the variantMap from variantTypes & variantReplacementIndexes.
CharStringMap variantMap(2, status);
for (int32_t i = 0; U_SUCCESS(status) && i < variantLength; i++) {
variantMap.put(variantTypes[i],
strings.get(variantReplacementIndexes[i]),
status);
}
if (U_FAILURE(status)) {
return nullptr;
}