1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 **********************************************************************
5 * Copyright (C) 1997-2016, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 **********************************************************************
8 *
9 * File locid.cpp
10 *
11 * Created by: Richard Gillam
12 *
13 * Modification History:
14 *
15 * Date Name Description
16 * 02/11/97 aliu Changed gLocPath to fgDataDirectory and added
17 * methods to get and set it.
18 * 04/02/97 aliu Made operator!= inline; fixed return value
19 * of getName().
20 * 04/15/97 aliu Cleanup for AIX/Win32.
21 * 04/24/97 aliu Numerous changes per code review.
22 * 08/18/98 stephen Changed getDisplayName()
23 * Added SIMPLIFIED_CHINESE, TRADITIONAL_CHINESE
24 * Added getISOCountries(), getISOLanguages(),
25 * getLanguagesForCountry()
26 * 03/16/99 bertrand rehaul.
27 * 07/21/99 stephen Added U_CFUNC setDefault
28 * 11/09/99 weiv Added const char * getName() const;
29 * 04/12/00 srl removing unicodestring api's and cached hash code
30 * 08/10/01 grhoten Change the static Locales to accessor functions
31 ******************************************************************************
32 */
33
34 #include <utility>
35
36 #include "unicode/bytestream.h"
37 #include "unicode/locid.h"
38 #include "unicode/localebuilder.h"
39 #include "unicode/strenum.h"
40 #include "unicode/stringpiece.h"
41 #include "unicode/uloc.h"
42 #include "unicode/ures.h"
43
44 #include "bytesinkutil.h"
45 #include "charstr.h"
46 #include "charstrmap.h"
47 #include "cmemory.h"
48 #include "cstring.h"
49 #include "mutex.h"
50 #include "putilimp.h"
51 #include "uassert.h"
52 #include "ucln_cmn.h"
53 #include "uhash.h"
54 #include "ulocimp.h"
55 #include "umutex.h"
56 #include "uniquecharstr.h"
57 #include "ustr_imp.h"
58 #include "uvector.h"
59
60 U_CDECL_BEGIN
61 static UBool U_CALLCONV locale_cleanup(void);
62 U_CDECL_END
63
64 U_NAMESPACE_BEGIN
65
66 static Locale *gLocaleCache = NULL;
67 static UInitOnce gLocaleCacheInitOnce = U_INITONCE_INITIALIZER;
68
69 // gDefaultLocaleMutex protects all access to gDefaultLocalesHashT and gDefaultLocale.
70 static UMutex gDefaultLocaleMutex;
71 static UHashtable *gDefaultLocalesHashT = NULL;
72 static Locale *gDefaultLocale = NULL;
73
74 /**
75 * \def ULOC_STRING_LIMIT
76 * strings beyond this value crash in CharString
77 */
78 #define ULOC_STRING_LIMIT 357913941
79
80 U_NAMESPACE_END
81
82 typedef enum ELocalePos {
83 eENGLISH,
84 eFRENCH,
85 eGERMAN,
86 eITALIAN,
87 eJAPANESE,
88 eKOREAN,
89 eCHINESE,
90
91 eFRANCE,
92 eGERMANY,
93 eITALY,
94 eJAPAN,
95 eKOREA,
96 eCHINA, /* Alias for PRC */
97 eTAIWAN,
98 eUK,
99 eUS,
100 eCANADA,
101 eCANADA_FRENCH,
102 eROOT,
103
104
105 //eDEFAULT,
106 eMAX_LOCALES
107 } ELocalePos;
108
109 U_CDECL_BEGIN
110 //
111 // Deleter function for Locales owned by the default Locale hash table/
112 //
113 static void U_CALLCONV
deleteLocale(void * obj)114 deleteLocale(void *obj) {
115 delete (icu::Locale *) obj;
116 }
117
locale_cleanup(void)118 static UBool U_CALLCONV locale_cleanup(void)
119 {
120 U_NAMESPACE_USE
121
122 delete [] gLocaleCache;
123 gLocaleCache = NULL;
124 gLocaleCacheInitOnce.reset();
125
126 if (gDefaultLocalesHashT) {
127 uhash_close(gDefaultLocalesHashT); // Automatically deletes all elements, using deleter func.
128 gDefaultLocalesHashT = NULL;
129 }
130 gDefaultLocale = NULL;
131 return TRUE;
132 }
133
134
locale_init(UErrorCode & status)135 static void U_CALLCONV locale_init(UErrorCode &status) {
136 U_NAMESPACE_USE
137
138 U_ASSERT(gLocaleCache == NULL);
139 gLocaleCache = new Locale[(int)eMAX_LOCALES];
140 if (gLocaleCache == NULL) {
141 status = U_MEMORY_ALLOCATION_ERROR;
142 return;
143 }
144 ucln_common_registerCleanup(UCLN_COMMON_LOCALE, locale_cleanup);
145 gLocaleCache[eROOT] = Locale("");
146 gLocaleCache[eENGLISH] = Locale("en");
147 gLocaleCache[eFRENCH] = Locale("fr");
148 gLocaleCache[eGERMAN] = Locale("de");
149 gLocaleCache[eITALIAN] = Locale("it");
150 gLocaleCache[eJAPANESE] = Locale("ja");
151 gLocaleCache[eKOREAN] = Locale("ko");
152 gLocaleCache[eCHINESE] = Locale("zh");
153 gLocaleCache[eFRANCE] = Locale("fr", "FR");
154 gLocaleCache[eGERMANY] = Locale("de", "DE");
155 gLocaleCache[eITALY] = Locale("it", "IT");
156 gLocaleCache[eJAPAN] = Locale("ja", "JP");
157 gLocaleCache[eKOREA] = Locale("ko", "KR");
158 gLocaleCache[eCHINA] = Locale("zh", "CN");
159 gLocaleCache[eTAIWAN] = Locale("zh", "TW");
160 gLocaleCache[eUK] = Locale("en", "GB");
161 gLocaleCache[eUS] = Locale("en", "US");
162 gLocaleCache[eCANADA] = Locale("en", "CA");
163 gLocaleCache[eCANADA_FRENCH] = Locale("fr", "CA");
164 }
165
166 U_CDECL_END
167
168 U_NAMESPACE_BEGIN
169
locale_set_default_internal(const char * id,UErrorCode & status)170 Locale *locale_set_default_internal(const char *id, UErrorCode& status) {
171 // Synchronize this entire function.
172 Mutex lock(&gDefaultLocaleMutex);
173
174 UBool canonicalize = FALSE;
175
176 // If given a NULL string for the locale id, grab the default
177 // name from the system.
178 // (Different from most other locale APIs, where a null name means use
179 // the current ICU default locale.)
180 if (id == NULL) {
181 id = uprv_getDefaultLocaleID(); // This function not thread safe? TODO: verify.
182 canonicalize = TRUE; // always canonicalize host ID
183 }
184
185 CharString localeNameBuf;
186 {
187 CharStringByteSink sink(&localeNameBuf);
188 if (canonicalize) {
189 ulocimp_canonicalize(id, sink, &status);
190 } else {
191 ulocimp_getName(id, sink, &status);
192 }
193 }
194
195 if (U_FAILURE(status)) {
196 return gDefaultLocale;
197 }
198
199 if (gDefaultLocalesHashT == NULL) {
200 gDefaultLocalesHashT = uhash_open(uhash_hashChars, uhash_compareChars, NULL, &status);
201 if (U_FAILURE(status)) {
202 return gDefaultLocale;
203 }
204 uhash_setValueDeleter(gDefaultLocalesHashT, deleteLocale);
205 ucln_common_registerCleanup(UCLN_COMMON_LOCALE, locale_cleanup);
206 }
207
208 Locale *newDefault = (Locale *)uhash_get(gDefaultLocalesHashT, localeNameBuf.data());
209 if (newDefault == NULL) {
210 newDefault = new Locale(Locale::eBOGUS);
211 if (newDefault == NULL) {
212 status = U_MEMORY_ALLOCATION_ERROR;
213 return gDefaultLocale;
214 }
215 newDefault->init(localeNameBuf.data(), FALSE);
216 uhash_put(gDefaultLocalesHashT, (char*) newDefault->getName(), newDefault, &status);
217 if (U_FAILURE(status)) {
218 return gDefaultLocale;
219 }
220 }
221 gDefaultLocale = newDefault;
222 return gDefaultLocale;
223 }
224
225 U_NAMESPACE_END
226
227 /* sfb 07/21/99 */
228 U_CFUNC void
locale_set_default(const char * id)229 locale_set_default(const char *id)
230 {
231 U_NAMESPACE_USE
232 UErrorCode status = U_ZERO_ERROR;
233 locale_set_default_internal(id, status);
234 }
235 /* end */
236
237 U_CFUNC const char *
locale_get_default(void)238 locale_get_default(void)
239 {
240 U_NAMESPACE_USE
241 return Locale::getDefault().getName();
242 }
243
244
245 U_NAMESPACE_BEGIN
246
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Locale)247 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Locale)
248
249 /*Character separating the posix id fields*/
250 // '_'
251 // In the platform codepage.
252 #define SEP_CHAR '_'
253 #define NULL_CHAR '\0'
254
255 Locale::~Locale()
256 {
257 if ((baseName != fullName) && (baseName != fullNameBuffer)) {
258 uprv_free(baseName);
259 }
260 baseName = NULL;
261 /*if fullName is on the heap, we free it*/
262 if (fullName != fullNameBuffer)
263 {
264 uprv_free(fullName);
265 fullName = NULL;
266 }
267 }
268
Locale()269 Locale::Locale()
270 : UObject(), fullName(fullNameBuffer), baseName(NULL)
271 {
272 init(NULL, FALSE);
273 }
274
275 /*
276 * Internal constructor to allow construction of a locale object with
277 * NO side effects. (Default constructor tries to get
278 * the default locale.)
279 */
Locale(Locale::ELocaleType)280 Locale::Locale(Locale::ELocaleType)
281 : UObject(), fullName(fullNameBuffer), baseName(NULL)
282 {
283 setToBogus();
284 }
285
286
Locale(const char * newLanguage,const char * newCountry,const char * newVariant,const char * newKeywords)287 Locale::Locale( const char * newLanguage,
288 const char * newCountry,
289 const char * newVariant,
290 const char * newKeywords)
291 : UObject(), fullName(fullNameBuffer), baseName(NULL)
292 {
293 if( (newLanguage==NULL) && (newCountry == NULL) && (newVariant == NULL) )
294 {
295 init(NULL, FALSE); /* shortcut */
296 }
297 else
298 {
299 UErrorCode status = U_ZERO_ERROR;
300 int32_t lsize = 0;
301 int32_t csize = 0;
302 int32_t vsize = 0;
303 int32_t ksize = 0;
304
305 // Check the sizes of the input strings.
306
307 // Language
308 if ( newLanguage != NULL )
309 {
310 lsize = (int32_t)uprv_strlen(newLanguage);
311 if ( lsize < 0 || lsize > ULOC_STRING_LIMIT ) { // int32 wrap
312 setToBogus();
313 return;
314 }
315 }
316
317 CharString togo(newLanguage, lsize, status); // start with newLanguage
318
319 // _Country
320 if ( newCountry != NULL )
321 {
322 csize = (int32_t)uprv_strlen(newCountry);
323 if ( csize < 0 || csize > ULOC_STRING_LIMIT ) { // int32 wrap
324 setToBogus();
325 return;
326 }
327 }
328
329 // _Variant
330 if ( newVariant != NULL )
331 {
332 // remove leading _'s
333 while(newVariant[0] == SEP_CHAR)
334 {
335 newVariant++;
336 }
337
338 // remove trailing _'s
339 vsize = (int32_t)uprv_strlen(newVariant);
340 if ( vsize < 0 || vsize > ULOC_STRING_LIMIT ) { // int32 wrap
341 setToBogus();
342 return;
343 }
344 while( (vsize>1) && (newVariant[vsize-1] == SEP_CHAR) )
345 {
346 vsize--;
347 }
348 }
349
350 if ( newKeywords != NULL)
351 {
352 ksize = (int32_t)uprv_strlen(newKeywords);
353 if ( ksize < 0 || ksize > ULOC_STRING_LIMIT ) {
354 setToBogus();
355 return;
356 }
357 }
358
359 // We've checked the input sizes, now build up the full locale string..
360
361 // newLanguage is already copied
362
363 if ( ( vsize != 0 ) || (csize != 0) ) // at least: __v
364 { // ^
365 togo.append(SEP_CHAR, status);
366 }
367
368 if ( csize != 0 )
369 {
370 togo.append(newCountry, status);
371 }
372
373 if ( vsize != 0)
374 {
375 togo.append(SEP_CHAR, status)
376 .append(newVariant, vsize, status);
377 }
378
379 if ( ksize != 0)
380 {
381 if (uprv_strchr(newKeywords, '=')) {
382 togo.append('@', status); /* keyword parsing */
383 }
384 else {
385 togo.append('_', status); /* Variant parsing with a script */
386 if ( vsize == 0) {
387 togo.append('_', status); /* No country found */
388 }
389 }
390 togo.append(newKeywords, status);
391 }
392
393 if (U_FAILURE(status)) {
394 // Something went wrong with appending, etc.
395 setToBogus();
396 return;
397 }
398 // Parse it, because for example 'language' might really be a complete
399 // string.
400 init(togo.data(), FALSE);
401 }
402 }
403
Locale(const Locale & other)404 Locale::Locale(const Locale &other)
405 : UObject(other), fullName(fullNameBuffer), baseName(NULL)
406 {
407 *this = other;
408 }
409
Locale(Locale && other)410 Locale::Locale(Locale&& other) U_NOEXCEPT
411 : UObject(other), fullName(fullNameBuffer), baseName(fullName) {
412 *this = std::move(other);
413 }
414
operator =(const Locale & other)415 Locale& Locale::operator=(const Locale& other) {
416 if (this == &other) {
417 return *this;
418 }
419
420 setToBogus();
421
422 if (other.fullName == other.fullNameBuffer) {
423 uprv_strcpy(fullNameBuffer, other.fullNameBuffer);
424 } else if (other.fullName == nullptr) {
425 fullName = nullptr;
426 } else {
427 fullName = uprv_strdup(other.fullName);
428 if (fullName == nullptr) return *this;
429 }
430
431 if (other.baseName == other.fullName) {
432 baseName = fullName;
433 } else if (other.baseName != nullptr) {
434 baseName = uprv_strdup(other.baseName);
435 if (baseName == nullptr) return *this;
436 }
437
438 uprv_strcpy(language, other.language);
439 uprv_strcpy(script, other.script);
440 uprv_strcpy(country, other.country);
441
442 variantBegin = other.variantBegin;
443 fIsBogus = other.fIsBogus;
444
445 return *this;
446 }
447
operator =(Locale && other)448 Locale& Locale::operator=(Locale&& other) U_NOEXCEPT {
449 if ((baseName != fullName) && (baseName != fullNameBuffer)) uprv_free(baseName);
450 if (fullName != fullNameBuffer) uprv_free(fullName);
451
452 if (other.fullName == other.fullNameBuffer || other.baseName == other.fullNameBuffer) {
453 uprv_strcpy(fullNameBuffer, other.fullNameBuffer);
454 }
455 if (other.fullName == other.fullNameBuffer) {
456 fullName = fullNameBuffer;
457 } else {
458 fullName = other.fullName;
459 }
460
461 if (other.baseName == other.fullNameBuffer) {
462 baseName = fullNameBuffer;
463 } else if (other.baseName == other.fullName) {
464 baseName = fullName;
465 } else {
466 baseName = other.baseName;
467 }
468
469 uprv_strcpy(language, other.language);
470 uprv_strcpy(script, other.script);
471 uprv_strcpy(country, other.country);
472
473 variantBegin = other.variantBegin;
474 fIsBogus = other.fIsBogus;
475
476 other.baseName = other.fullName = other.fullNameBuffer;
477
478 return *this;
479 }
480
481 Locale *
clone() const482 Locale::clone() const {
483 return new Locale(*this);
484 }
485
486 bool
operator ==(const Locale & other) const487 Locale::operator==( const Locale& other) const
488 {
489 return (uprv_strcmp(other.fullName, fullName) == 0);
490 }
491
492 namespace {
493
494 UInitOnce gKnownCanonicalizedInitOnce = U_INITONCE_INITIALIZER;
495 UHashtable *gKnownCanonicalized = nullptr;
496
497 static const char* const KNOWN_CANONICALIZED[] = {
498 "c",
499 // Commonly used locales known are already canonicalized
500 "af", "af_ZA", "am", "am_ET", "ar", "ar_001", "as", "as_IN", "az", "az_AZ",
501 "be", "be_BY", "bg", "bg_BG", "bn", "bn_IN", "bs", "bs_BA", "ca", "ca_ES",
502 "cs", "cs_CZ", "cy", "cy_GB", "da", "da_DK", "de", "de_DE", "el", "el_GR",
503 "en", "en_GB", "en_US", "es", "es_419", "es_ES", "et", "et_EE", "eu",
504 "eu_ES", "fa", "fa_IR", "fi", "fi_FI", "fil", "fil_PH", "fr", "fr_FR",
505 "ga", "ga_IE", "gl", "gl_ES", "gu", "gu_IN", "he", "he_IL", "hi", "hi_IN",
506 "hr", "hr_HR", "hu", "hu_HU", "hy", "hy_AM", "id", "id_ID", "is", "is_IS",
507 "it", "it_IT", "ja", "ja_JP", "jv", "jv_ID", "ka", "ka_GE", "kk", "kk_KZ",
508 "km", "km_KH", "kn", "kn_IN", "ko", "ko_KR", "ky", "ky_KG", "lo", "lo_LA",
509 "lt", "lt_LT", "lv", "lv_LV", "mk", "mk_MK", "ml", "ml_IN", "mn", "mn_MN",
510 "mr", "mr_IN", "ms", "ms_MY", "my", "my_MM", "nb", "nb_NO", "ne", "ne_NP",
511 "nl", "nl_NL", "no", "or", "or_IN", "pa", "pa_IN", "pl", "pl_PL", "ps", "ps_AF",
512 "pt", "pt_BR", "pt_PT", "ro", "ro_RO", "ru", "ru_RU", "sd", "sd_IN", "si",
513 "si_LK", "sk", "sk_SK", "sl", "sl_SI", "so", "so_SO", "sq", "sq_AL", "sr",
514 "sr_Cyrl_RS", "sr_Latn", "sr_RS", "sv", "sv_SE", "sw", "sw_TZ", "ta",
515 "ta_IN", "te", "te_IN", "th", "th_TH", "tk", "tk_TM", "tr", "tr_TR", "uk",
516 "uk_UA", "ur", "ur_PK", "uz", "uz_UZ", "vi", "vi_VN", "yue", "yue_Hant",
517 "yue_Hant_HK", "yue_HK", "zh", "zh_CN", "zh_Hans", "zh_Hans_CN", "zh_Hant",
518 "zh_Hant_TW", "zh_TW", "zu", "zu_ZA"
519 };
520
cleanupKnownCanonicalized()521 static UBool U_CALLCONV cleanupKnownCanonicalized() {
522 gKnownCanonicalizedInitOnce.reset();
523 if (gKnownCanonicalized) { uhash_close(gKnownCanonicalized); }
524 return TRUE;
525 }
526
loadKnownCanonicalized(UErrorCode & status)527 static void U_CALLCONV loadKnownCanonicalized(UErrorCode &status) {
528 ucln_common_registerCleanup(UCLN_COMMON_LOCALE_KNOWN_CANONICALIZED,
529 cleanupKnownCanonicalized);
530 LocalUHashtablePointer newKnownCanonicalizedMap(
531 uhash_open(uhash_hashChars, uhash_compareChars, nullptr, &status));
532 for (int32_t i = 0;
533 U_SUCCESS(status) && i < UPRV_LENGTHOF(KNOWN_CANONICALIZED);
534 i++) {
535 uhash_puti(newKnownCanonicalizedMap.getAlias(),
536 (void*)KNOWN_CANONICALIZED[i],
537 1, &status);
538 }
539 if (U_FAILURE(status)) {
540 return;
541 }
542
543 gKnownCanonicalized = newKnownCanonicalizedMap.orphan();
544 }
545
546 class AliasData;
547
548 /**
549 * A Builder class to build the alias data.
550 */
551 class AliasDataBuilder {
552 public:
AliasDataBuilder()553 AliasDataBuilder() {
554 }
555
556 // Build the AliasData from resource.
557 AliasData* build(UErrorCode &status);
558
559 private:
560 void readAlias(UResourceBundle* alias,
561 UniqueCharStrings* strings,
562 LocalMemory<const char*>& types,
563 LocalMemory<int32_t>& replacementIndexes,
564 int32_t &length,
565 void (*checkType)(const char* type),
566 void (*checkReplacement)(const UnicodeString& replacement),
567 UErrorCode &status);
568
569 // Read the languageAlias data from alias to
570 // strings+types+replacementIndexes
571 // The number of record will be stored into length.
572 // Allocate length items for types, to store the type field.
573 // Allocate length items for replacementIndexes,
574 // to store the index in the strings for the replacement script.
575 void readLanguageAlias(UResourceBundle* alias,
576 UniqueCharStrings* strings,
577 LocalMemory<const char*>& types,
578 LocalMemory<int32_t>& replacementIndexes,
579 int32_t &length,
580 UErrorCode &status);
581
582 // Read the scriptAlias data from alias to
583 // strings+types+replacementIndexes
584 // Allocate length items for types, to store the type field.
585 // Allocate length items for replacementIndexes,
586 // to store the index in the strings for the replacement script.
587 void readScriptAlias(UResourceBundle* alias,
588 UniqueCharStrings* strings,
589 LocalMemory<const char*>& types,
590 LocalMemory<int32_t>& replacementIndexes,
591 int32_t &length, UErrorCode &status);
592
593 // Read the territoryAlias data from alias to
594 // strings+types+replacementIndexes
595 // Allocate length items for types, to store the type field.
596 // Allocate length items for replacementIndexes,
597 // to store the index in the strings for the replacement script.
598 void readTerritoryAlias(UResourceBundle* alias,
599 UniqueCharStrings* strings,
600 LocalMemory<const char*>& types,
601 LocalMemory<int32_t>& replacementIndexes,
602 int32_t &length, UErrorCode &status);
603
604 // Read the variantAlias data from alias to
605 // strings+types+replacementIndexes
606 // Allocate length items for types, to store the type field.
607 // Allocate length items for replacementIndexes,
608 // to store the index in the strings for the replacement variant.
609 void readVariantAlias(UResourceBundle* alias,
610 UniqueCharStrings* strings,
611 LocalMemory<const char*>& types,
612 LocalMemory<int32_t>& replacementIndexes,
613 int32_t &length, UErrorCode &status);
614
615 // Read the subdivisionAlias data from alias to
616 // strings+types+replacementIndexes
617 // Allocate length items for types, to store the type field.
618 // Allocate length items for replacementIndexes,
619 // to store the index in the strings for the replacement variant.
620 void readSubdivisionAlias(UResourceBundle* alias,
621 UniqueCharStrings* strings,
622 LocalMemory<const char*>& types,
623 LocalMemory<int32_t>& replacementIndexes,
624 int32_t &length, UErrorCode &status);
625 };
626
627 /**
628 * A class to hold the Alias Data.
629 */
630 class AliasData : public UMemory {
631 public:
singleton(UErrorCode & status)632 static const AliasData* singleton(UErrorCode& status) {
633 if (U_FAILURE(status)) {
634 // Do not get into loadData if the status already has error.
635 return nullptr;
636 }
637 umtx_initOnce(AliasData::gInitOnce, &AliasData::loadData, status);
638 return gSingleton;
639 }
640
languageMap() const641 const CharStringMap& languageMap() const { return language; }
scriptMap() const642 const CharStringMap& scriptMap() const { return script; }
territoryMap() const643 const CharStringMap& territoryMap() const { return territory; }
variantMap() const644 const CharStringMap& variantMap() const { return variant; }
subdivisionMap() const645 const CharStringMap& subdivisionMap() const { return subdivision; }
646
647 static void U_CALLCONV loadData(UErrorCode &status);
648 static UBool U_CALLCONV cleanup();
649
650 static UInitOnce gInitOnce;
651
652 private:
AliasData(CharStringMap languageMap,CharStringMap scriptMap,CharStringMap territoryMap,CharStringMap variantMap,CharStringMap subdivisionMap,CharString * strings)653 AliasData(CharStringMap languageMap,
654 CharStringMap scriptMap,
655 CharStringMap territoryMap,
656 CharStringMap variantMap,
657 CharStringMap subdivisionMap,
658 CharString* strings)
659 : language(std::move(languageMap)),
660 script(std::move(scriptMap)),
661 territory(std::move(territoryMap)),
662 variant(std::move(variantMap)),
663 subdivision(std::move(subdivisionMap)),
664 strings(strings) {
665 }
666
~AliasData()667 ~AliasData() {
668 delete strings;
669 }
670
671 static const AliasData* gSingleton;
672
673 CharStringMap language;
674 CharStringMap script;
675 CharStringMap territory;
676 CharStringMap variant;
677 CharStringMap subdivision;
678 CharString* strings;
679
680 friend class AliasDataBuilder;
681 };
682
683
684 const AliasData* AliasData::gSingleton = nullptr;
685 UInitOnce AliasData::gInitOnce = U_INITONCE_INITIALIZER;
686
687 UBool U_CALLCONV
cleanup()688 AliasData::cleanup()
689 {
690 gInitOnce.reset();
691 delete gSingleton;
692 return TRUE;
693 }
694
695 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)696 AliasDataBuilder::readAlias(
697 UResourceBundle* alias,
698 UniqueCharStrings* strings,
699 LocalMemory<const char*>& types,
700 LocalMemory<int32_t>& replacementIndexes,
701 int32_t &length,
702 void (*checkType)(const char* type),
703 void (*checkReplacement)(const UnicodeString& replacement),
704 UErrorCode &status) {
705 if (U_FAILURE(status)) {
706 return;
707 }
708 length = ures_getSize(alias);
709 const char** rawTypes = types.allocateInsteadAndCopy(length);
710 if (rawTypes == nullptr) {
711 status = U_MEMORY_ALLOCATION_ERROR;
712 return;
713 }
714 int32_t* rawIndexes = replacementIndexes.allocateInsteadAndCopy(length);
715 if (rawIndexes == nullptr) {
716 status = U_MEMORY_ALLOCATION_ERROR;
717 return;
718 }
719 int i = 0;
720 while (ures_hasNext(alias)) {
721 LocalUResourceBundlePointer res(
722 ures_getNextResource(alias, nullptr, &status));
723 const char* aliasFrom = ures_getKey(res.getAlias());
724 UnicodeString aliasTo =
725 ures_getUnicodeStringByKey(res.getAlias(), "replacement", &status);
726
727 checkType(aliasFrom);
728 checkReplacement(aliasTo);
729
730 rawTypes[i] = aliasFrom;
731 rawIndexes[i] = strings->add(aliasTo, status);
732 i++;
733 }
734 }
735
736 /**
737 * Read the languageAlias data from alias to strings+types+replacementIndexes.
738 * Allocate length items for types, to store the type field. Allocate length
739 * items for replacementIndexes, to store the index in the strings for the
740 * replacement language.
741 */
742 void
readLanguageAlias(UResourceBundle * alias,UniqueCharStrings * strings,LocalMemory<const char * > & types,LocalMemory<int32_t> & replacementIndexes,int32_t & length,UErrorCode & status)743 AliasDataBuilder::readLanguageAlias(
744 UResourceBundle* alias,
745 UniqueCharStrings* strings,
746 LocalMemory<const char*>& types,
747 LocalMemory<int32_t>& replacementIndexes,
748 int32_t &length,
749 UErrorCode &status)
750 {
751 return readAlias(
752 alias, strings, types, replacementIndexes, length,
753 #if U_DEBUG
754 [](const char* type) {
755 // Assert the aliasFrom only contains the following possibilities
756 // language_REGION_variant
757 // language_REGION
758 // language_variant
759 // language
760 // und_variant
761 Locale test(type);
762 // Assert no script in aliasFrom
763 U_ASSERT(test.getScript()[0] == '\0');
764 // Assert when language is und, no REGION in aliasFrom.
765 U_ASSERT(test.getLanguage()[0] != '\0' || test.getCountry()[0] == '\0');
766 },
767 #else
768 [](const char*) {},
769 #endif
770 [](const UnicodeString&) {}, status);
771 }
772
773 /**
774 * Read the scriptAlias data from alias to strings+types+replacementIndexes.
775 * Allocate length items for types, to store the type field. Allocate length
776 * items for replacementIndexes, to store the index in the strings for the
777 * replacement script.
778 */
779 void
readScriptAlias(UResourceBundle * alias,UniqueCharStrings * strings,LocalMemory<const char * > & types,LocalMemory<int32_t> & replacementIndexes,int32_t & length,UErrorCode & status)780 AliasDataBuilder::readScriptAlias(
781 UResourceBundle* alias,
782 UniqueCharStrings* strings,
783 LocalMemory<const char*>& types,
784 LocalMemory<int32_t>& replacementIndexes,
785 int32_t &length,
786 UErrorCode &status)
787 {
788 return readAlias(
789 alias, strings, types, replacementIndexes, length,
790 #if U_DEBUG
791 [](const char* type) {
792 U_ASSERT(uprv_strlen(type) == 4);
793 },
794 [](const UnicodeString& replacement) {
795 U_ASSERT(replacement.length() == 4);
796 },
797 #else
798 [](const char*) {},
799 [](const UnicodeString&) { },
800 #endif
801 status);
802 }
803
804 /**
805 * Read the territoryAlias data from alias to strings+types+replacementIndexes.
806 * Allocate length items for types, to store the type field. Allocate length
807 * items for replacementIndexes, to store the index in the strings for the
808 * replacement regions.
809 */
810 void
readTerritoryAlias(UResourceBundle * alias,UniqueCharStrings * strings,LocalMemory<const char * > & types,LocalMemory<int32_t> & replacementIndexes,int32_t & length,UErrorCode & status)811 AliasDataBuilder::readTerritoryAlias(
812 UResourceBundle* alias,
813 UniqueCharStrings* strings,
814 LocalMemory<const char*>& types,
815 LocalMemory<int32_t>& replacementIndexes,
816 int32_t &length,
817 UErrorCode &status)
818 {
819 return readAlias(
820 alias, strings, types, replacementIndexes, length,
821 #if U_DEBUG
822 [](const char* type) {
823 U_ASSERT(uprv_strlen(type) == 2 || uprv_strlen(type) == 3);
824 },
825 #else
826 [](const char*) {},
827 #endif
828 [](const UnicodeString&) { },
829 status);
830 }
831
832 /**
833 * Read the variantAlias data from alias to strings+types+replacementIndexes.
834 * Allocate length items for types, to store the type field. Allocate length
835 * items for replacementIndexes, to store the index in the strings for the
836 * replacement variant.
837 */
838 void
readVariantAlias(UResourceBundle * alias,UniqueCharStrings * strings,LocalMemory<const char * > & types,LocalMemory<int32_t> & replacementIndexes,int32_t & length,UErrorCode & status)839 AliasDataBuilder::readVariantAlias(
840 UResourceBundle* alias,
841 UniqueCharStrings* strings,
842 LocalMemory<const char*>& types,
843 LocalMemory<int32_t>& replacementIndexes,
844 int32_t &length,
845 UErrorCode &status)
846 {
847 return readAlias(
848 alias, strings, types, replacementIndexes, length,
849 #if U_DEBUG
850 [](const char* type) {
851 U_ASSERT(uprv_strlen(type) >= 4 && uprv_strlen(type) <= 8);
852 U_ASSERT(uprv_strlen(type) != 4 ||
853 (type[0] >= '0' && type[0] <= '9'));
854 },
855 [](const UnicodeString& replacement) {
856 U_ASSERT(replacement.length() >= 4 && replacement.length() <= 8);
857 U_ASSERT(replacement.length() != 4 ||
858 (replacement.charAt(0) >= u'0' &&
859 replacement.charAt(0) <= u'9'));
860 },
861 #else
862 [](const char*) {},
863 [](const UnicodeString&) { },
864 #endif
865 status);
866 }
867
868 /**
869 * Read the subdivisionAlias data from alias to strings+types+replacementIndexes.
870 * Allocate length items for types, to store the type field. Allocate length
871 * items for replacementIndexes, to store the index in the strings for the
872 * replacement regions.
873 */
874 void
readSubdivisionAlias(UResourceBundle * alias,UniqueCharStrings * strings,LocalMemory<const char * > & types,LocalMemory<int32_t> & replacementIndexes,int32_t & length,UErrorCode & status)875 AliasDataBuilder::readSubdivisionAlias(
876 UResourceBundle* alias,
877 UniqueCharStrings* strings,
878 LocalMemory<const char*>& types,
879 LocalMemory<int32_t>& replacementIndexes,
880 int32_t &length,
881 UErrorCode &status)
882 {
883 return readAlias(
884 alias, strings, types, replacementIndexes, length,
885 #if U_DEBUG
886 [](const char* type) {
887 U_ASSERT(uprv_strlen(type) >= 3 && uprv_strlen(type) <= 8);
888 },
889 #else
890 [](const char*) {},
891 #endif
892 [](const UnicodeString&) { },
893 status);
894 }
895
896 /**
897 * Initializes the alias data from the ICU resource bundles. The alias data
898 * contains alias of language, country, script and variants.
899 *
900 * If the alias data has already loaded, then this method simply returns without
901 * doing anything meaningful.
902 */
903 void U_CALLCONV
loadData(UErrorCode & status)904 AliasData::loadData(UErrorCode &status)
905 {
906 #ifdef LOCALE_CANONICALIZATION_DEBUG
907 UDate start = uprv_getRawUTCtime();
908 #endif // LOCALE_CANONICALIZATION_DEBUG
909 ucln_common_registerCleanup(UCLN_COMMON_LOCALE_ALIAS, cleanup);
910 AliasDataBuilder builder;
911 gSingleton = builder.build(status);
912 #ifdef LOCALE_CANONICALIZATION_DEBUG
913 UDate end = uprv_getRawUTCtime();
914 printf("AliasData::loadData took total %f ms\n", end - start);
915 #endif // LOCALE_CANONICALIZATION_DEBUG
916 }
917
918 /**
919 * Build the alias data from resources.
920 */
921 AliasData*
build(UErrorCode & status)922 AliasDataBuilder::build(UErrorCode &status) {
923 LocalUResourceBundlePointer metadata(
924 ures_openDirect(nullptr, "metadata", &status));
925 LocalUResourceBundlePointer metadataAlias(
926 ures_getByKey(metadata.getAlias(), "alias", nullptr, &status));
927 LocalUResourceBundlePointer languageAlias(
928 ures_getByKey(metadataAlias.getAlias(), "language", nullptr, &status));
929 LocalUResourceBundlePointer scriptAlias(
930 ures_getByKey(metadataAlias.getAlias(), "script", nullptr, &status));
931 LocalUResourceBundlePointer territoryAlias(
932 ures_getByKey(metadataAlias.getAlias(), "territory", nullptr, &status));
933 LocalUResourceBundlePointer variantAlias(
934 ures_getByKey(metadataAlias.getAlias(), "variant", nullptr, &status));
935 LocalUResourceBundlePointer subdivisionAlias(
936 ures_getByKey(metadataAlias.getAlias(), "subdivision", nullptr, &status));
937
938 if (U_FAILURE(status)) {
939 return nullptr;
940 }
941 int32_t languagesLength = 0, scriptLength = 0, territoryLength = 0,
942 variantLength = 0, subdivisionLength = 0;
943
944 // Read the languageAlias into languageTypes, languageReplacementIndexes
945 // and strings
946 UniqueCharStrings strings(status);
947 LocalMemory<const char*> languageTypes;
948 LocalMemory<int32_t> languageReplacementIndexes;
949 readLanguageAlias(languageAlias.getAlias(),
950 &strings,
951 languageTypes,
952 languageReplacementIndexes,
953 languagesLength,
954 status);
955
956 // Read the scriptAlias into scriptTypes, scriptReplacementIndexes
957 // and strings
958 LocalMemory<const char*> scriptTypes;
959 LocalMemory<int32_t> scriptReplacementIndexes;
960 readScriptAlias(scriptAlias.getAlias(),
961 &strings,
962 scriptTypes,
963 scriptReplacementIndexes,
964 scriptLength,
965 status);
966
967 // Read the territoryAlias into territoryTypes, territoryReplacementIndexes
968 // and strings
969 LocalMemory<const char*> territoryTypes;
970 LocalMemory<int32_t> territoryReplacementIndexes;
971 readTerritoryAlias(territoryAlias.getAlias(),
972 &strings,
973 territoryTypes,
974 territoryReplacementIndexes,
975 territoryLength, status);
976
977 // Read the variantAlias into variantTypes, variantReplacementIndexes
978 // and strings
979 LocalMemory<const char*> variantTypes;
980 LocalMemory<int32_t> variantReplacementIndexes;
981 readVariantAlias(variantAlias.getAlias(),
982 &strings,
983 variantTypes,
984 variantReplacementIndexes,
985 variantLength, status);
986
987 // Read the subdivisionAlias into subdivisionTypes, subdivisionReplacementIndexes
988 // and strings
989 LocalMemory<const char*> subdivisionTypes;
990 LocalMemory<int32_t> subdivisionReplacementIndexes;
991 readSubdivisionAlias(subdivisionAlias.getAlias(),
992 &strings,
993 subdivisionTypes,
994 subdivisionReplacementIndexes,
995 subdivisionLength, status);
996
997 if (U_FAILURE(status)) {
998 return nullptr;
999 }
1000
1001 // We can only use strings after freeze it.
1002 strings.freeze();
1003
1004 // Build the languageMap from languageTypes & languageReplacementIndexes
1005 CharStringMap languageMap(490, status);
1006 for (int32_t i = 0; U_SUCCESS(status) && i < languagesLength; i++) {
1007 languageMap.put(languageTypes[i],
1008 strings.get(languageReplacementIndexes[i]),
1009 status);
1010 }
1011
1012 // Build the scriptMap from scriptTypes & scriptReplacementIndexes
1013 CharStringMap scriptMap(1, status);
1014 for (int32_t i = 0; U_SUCCESS(status) && i < scriptLength; i++) {
1015 scriptMap.put(scriptTypes[i],
1016 strings.get(scriptReplacementIndexes[i]),
1017 status);
1018 }
1019
1020 // Build the territoryMap from territoryTypes & territoryReplacementIndexes
1021 CharStringMap territoryMap(650, status);
1022 for (int32_t i = 0; U_SUCCESS(status) && i < territoryLength; i++) {
1023 territoryMap.put(territoryTypes[i],
1024 strings.get(territoryReplacementIndexes[i]),
1025 status);
1026 }
1027
1028 // Build the variantMap from variantTypes & variantReplacementIndexes.
1029 CharStringMap variantMap(2, status);
1030 for (int32_t i = 0; U_SUCCESS(status) && i < variantLength; i++) {
1031 variantMap.put(variantTypes[i],
1032 strings.get(variantReplacementIndexes[i]),
1033 status);
1034 }
1035
1036 // Build the subdivisionMap from subdivisionTypes & subdivisionReplacementIndexes.
1037 CharStringMap subdivisionMap(2, status);
1038 for (int32_t i = 0; U_SUCCESS(status) && i < subdivisionLength; i++) {
1039 subdivisionMap.put(subdivisionTypes[i],
1040 strings.get(subdivisionReplacementIndexes[i]),
1041 status);
1042 }
1043
1044 if (U_FAILURE(status)) {
1045 return nullptr;
1046 }
1047
1048 // copy hashtables
1049 auto *data = new AliasData(
1050 std::move(languageMap),
1051 std::move(scriptMap),
1052 std::move(territoryMap),
1053 std::move(variantMap),
1054 std::move(subdivisionMap),
1055 strings.orphanCharStrings());
1056
1057 if (data == nullptr) {
1058 status = U_MEMORY_ALLOCATION_ERROR;
1059 }
1060 return data;
1061 }
1062
1063 /**
1064 * A class that find the replacement values of locale fields by using AliasData.
1065 */
1066 class AliasReplacer {
1067 public:
AliasReplacer(UErrorCode status)1068 AliasReplacer(UErrorCode status) :
1069 language(nullptr), script(nullptr), region(nullptr),
1070 extensions(nullptr), variants(status),
1071 data(nullptr) {
1072 }
~AliasReplacer()1073 ~AliasReplacer() {
1074 }
1075
1076 // Check the fields inside locale, if need to replace fields,
1077 // place the the replaced locale ID in out and return true.
1078 // Otherwise return false for no replacement or error.
1079 bool replace(
1080 const Locale& locale, CharString& out, UErrorCode& status);
1081
1082 private:
1083 const char* language;
1084 const char* script;
1085 const char* region;
1086 const char* extensions;
1087 UVector variants;
1088
1089 const AliasData* data;
1090
notEmpty(const char * str)1091 inline bool notEmpty(const char* str) {
1092 return str && str[0] != NULL_CHAR;
1093 }
1094
1095 /**
1096 * If replacement is neither null nor empty and input is either null or empty,
1097 * return replacement.
1098 * If replacement is neither null nor empty but input is not empty, return input.
1099 * If replacement is either null or empty and type is either null or empty,
1100 * return input.
1101 * Otherwise return null.
1102 * replacement input type return
1103 * AAA nullptr * AAA
1104 * AAA BBB * BBB
1105 * nullptr || "" CCC nullptr CCC
1106 * nullptr || "" * DDD nullptr
1107 */
deleteOrReplace(const char * input,const char * type,const char * replacement)1108 inline const char* deleteOrReplace(
1109 const char* input, const char* type, const char* replacement) {
1110 return notEmpty(replacement) ?
1111 ((input == nullptr) ? replacement : input) :
1112 ((type == nullptr) ? input : nullptr);
1113 }
1114
same(const char * a,const char * b)1115 inline bool same(const char* a, const char* b) {
1116 if (a == nullptr && b == nullptr) {
1117 return true;
1118 }
1119 if ((a == nullptr && b != nullptr) ||
1120 (a != nullptr && b == nullptr)) {
1121 return false;
1122 }
1123 return uprv_strcmp(a, b) == 0;
1124 }
1125
1126 // Gather fields and generate locale ID into out.
1127 CharString& outputToString(CharString& out, UErrorCode status);
1128
1129 // Generate the lookup key.
1130 CharString& generateKey(const char* language, const char* region,
1131 const char* variant, CharString& out,
1132 UErrorCode status);
1133
1134 void parseLanguageReplacement(const char* replacement,
1135 const char*& replaceLanguage,
1136 const char*& replaceScript,
1137 const char*& replaceRegion,
1138 const char*& replaceVariant,
1139 const char*& replaceExtensions,
1140 UVector& toBeFreed,
1141 UErrorCode& status);
1142
1143 // Replace by using languageAlias.
1144 bool replaceLanguage(bool checkLanguage, bool checkRegion,
1145 bool checkVariants, UVector& toBeFreed,
1146 UErrorCode& status);
1147
1148 // Replace by using territoryAlias.
1149 bool replaceTerritory(UVector& toBeFreed, UErrorCode& status);
1150
1151 // Replace by using scriptAlias.
1152 bool replaceScript(UErrorCode& status);
1153
1154 // Replace by using variantAlias.
1155 bool replaceVariant(UErrorCode& status);
1156
1157 // Replace by using subdivisionAlias.
1158 bool replaceSubdivision(StringPiece subdivision,
1159 CharString& output, UErrorCode& status);
1160
1161 // Replace transformed extensions.
1162 bool replaceTransformedExtensions(
1163 CharString& transformedExtensions, CharString& output, UErrorCode& status);
1164 };
1165
1166 CharString&
generateKey(const char * language,const char * region,const char * variant,CharString & out,UErrorCode status)1167 AliasReplacer::generateKey(
1168 const char* language, const char* region, const char* variant,
1169 CharString& out, UErrorCode status)
1170 {
1171 out.append(language, status);
1172 if (notEmpty(region)) {
1173 out.append(SEP_CHAR, status)
1174 .append(region, status);
1175 }
1176 if (notEmpty(variant)) {
1177 out.append(SEP_CHAR, status)
1178 .append(variant, status);
1179 }
1180 return out;
1181 }
1182
1183 void
parseLanguageReplacement(const char * replacement,const char * & replacedLanguage,const char * & replacedScript,const char * & replacedRegion,const char * & replacedVariant,const char * & replacedExtensions,UVector & toBeFreed,UErrorCode & status)1184 AliasReplacer::parseLanguageReplacement(
1185 const char* replacement,
1186 const char*& replacedLanguage,
1187 const char*& replacedScript,
1188 const char*& replacedRegion,
1189 const char*& replacedVariant,
1190 const char*& replacedExtensions,
1191 UVector& toBeFreed,
1192 UErrorCode& status)
1193 {
1194 if (U_FAILURE(status)) {
1195 return;
1196 }
1197 replacedScript = replacedRegion = replacedVariant
1198 = replacedExtensions = nullptr;
1199 if (uprv_strchr(replacement, '_') == nullptr) {
1200 replacedLanguage = replacement;
1201 // reach the end, just return it.
1202 return;
1203 }
1204 // We have multiple field so we have to allocate and parse
1205 CharString* str = new CharString(
1206 replacement, (int32_t)uprv_strlen(replacement), status);
1207 if (U_FAILURE(status)) {
1208 return;
1209 }
1210 if (str == nullptr) {
1211 status = U_MEMORY_ALLOCATION_ERROR;
1212 return;
1213 }
1214 toBeFreed.addElementX(str, status);
1215 char* data = str->data();
1216 replacedLanguage = (const char*) data;
1217 char* endOfField = uprv_strchr(data, '_');
1218 *endOfField = '\0'; // null terminiate it.
1219 endOfField++;
1220 const char* start = endOfField;
1221 endOfField = (char*) uprv_strchr(start, '_');
1222 size_t len = 0;
1223 if (endOfField == nullptr) {
1224 len = uprv_strlen(start);
1225 } else {
1226 len = endOfField - start;
1227 *endOfField = '\0'; // null terminiate it.
1228 }
1229 if (len == 4 && uprv_isASCIILetter(*start)) {
1230 // Got a script
1231 replacedScript = start;
1232 if (endOfField == nullptr) {
1233 return;
1234 }
1235 start = endOfField++;
1236 endOfField = (char*)uprv_strchr(start, '_');
1237 if (endOfField == nullptr) {
1238 len = uprv_strlen(start);
1239 } else {
1240 len = endOfField - start;
1241 *endOfField = '\0'; // null terminiate it.
1242 }
1243 }
1244 if (len >= 2 && len <= 3) {
1245 // Got a region
1246 replacedRegion = start;
1247 if (endOfField == nullptr) {
1248 return;
1249 }
1250 start = endOfField++;
1251 endOfField = (char*)uprv_strchr(start, '_');
1252 if (endOfField == nullptr) {
1253 len = uprv_strlen(start);
1254 } else {
1255 len = endOfField - start;
1256 *endOfField = '\0'; // null terminiate it.
1257 }
1258 }
1259 if (len >= 4) {
1260 // Got a variant
1261 replacedVariant = start;
1262 if (endOfField == nullptr) {
1263 return;
1264 }
1265 start = endOfField++;
1266 }
1267 replacedExtensions = start;
1268 }
1269
1270 bool
replaceLanguage(bool checkLanguage,bool checkRegion,bool checkVariants,UVector & toBeFreed,UErrorCode & status)1271 AliasReplacer::replaceLanguage(
1272 bool checkLanguage, bool checkRegion,
1273 bool checkVariants, UVector& toBeFreed, UErrorCode& status)
1274 {
1275 if (U_FAILURE(status)) {
1276 return false;
1277 }
1278 if ( (checkRegion && region == nullptr) ||
1279 (checkVariants && variants.size() == 0)) {
1280 // Nothing to search.
1281 return false;
1282 }
1283 int32_t variant_size = checkVariants ? variants.size() : 1;
1284 // Since we may have more than one variant, we need to loop through them.
1285 const char* searchLanguage = checkLanguage ? language : "und";
1286 const char* searchRegion = checkRegion ? region : nullptr;
1287 const char* searchVariant = nullptr;
1288 for (int32_t variant_index = 0;
1289 variant_index < variant_size;
1290 variant_index++) {
1291 if (checkVariants) {
1292 U_ASSERT(variant_index < variant_size);
1293 searchVariant = (const char*)(variants.elementAt(variant_index));
1294 }
1295
1296 if (searchVariant != nullptr && uprv_strlen(searchVariant) < 4) {
1297 // Do not consider ill-formed variant subtag.
1298 searchVariant = nullptr;
1299 }
1300 CharString typeKey;
1301 generateKey(searchLanguage, searchRegion, searchVariant, typeKey,
1302 status);
1303 if (U_FAILURE(status)) {
1304 return false;
1305 }
1306 const char *replacement = data->languageMap().get(typeKey.data());
1307 if (replacement == nullptr) {
1308 // Found no replacement data.
1309 continue;
1310 }
1311
1312 const char* replacedLanguage = nullptr;
1313 const char* replacedScript = nullptr;
1314 const char* replacedRegion = nullptr;
1315 const char* replacedVariant = nullptr;
1316 const char* replacedExtensions = nullptr;
1317 parseLanguageReplacement(replacement,
1318 replacedLanguage,
1319 replacedScript,
1320 replacedRegion,
1321 replacedVariant,
1322 replacedExtensions,
1323 toBeFreed,
1324 status);
1325 replacedLanguage =
1326 (replacedLanguage != nullptr && uprv_strcmp(replacedLanguage, "und") == 0) ?
1327 language : replacedLanguage;
1328 replacedScript = deleteOrReplace(script, nullptr, replacedScript);
1329 replacedRegion = deleteOrReplace(region, searchRegion, replacedRegion);
1330 replacedVariant = deleteOrReplace(
1331 searchVariant, searchVariant, replacedVariant);
1332
1333 if ( same(language, replacedLanguage) &&
1334 same(script, replacedScript) &&
1335 same(region, replacedRegion) &&
1336 same(searchVariant, replacedVariant) &&
1337 replacedExtensions == nullptr) {
1338 // Replacement produce no changes.
1339 continue;
1340 }
1341
1342 language = replacedLanguage;
1343 region = replacedRegion;
1344 script = replacedScript;
1345 if (searchVariant != nullptr) {
1346 if (notEmpty(replacedVariant)) {
1347 variants.setElementAt((void*)replacedVariant, variant_index);
1348 } else {
1349 variants.removeElementAt(variant_index);
1350 }
1351 }
1352 if (replacedExtensions != nullptr) {
1353 // DO NOTHING
1354 // UTS35 does not specify what should we do if we have extensions in the
1355 // replacement. Currently we know only the following 4 "BCP47 LegacyRules" have
1356 // extensions in them languageAlias:
1357 // i_default => en_x_i_default
1358 // i_enochian => und_x_i_enochian
1359 // i_mingo => see_x_i_mingo
1360 // zh_min => nan_x_zh_min
1361 // But all of them are already changed by code inside ultag_parse() before
1362 // hitting this code.
1363 }
1364
1365 // Something changed by language alias data.
1366 return true;
1367 }
1368 // Nothing changed by language alias data.
1369 return false;
1370 }
1371
1372 bool
replaceTerritory(UVector & toBeFreed,UErrorCode & status)1373 AliasReplacer::replaceTerritory(UVector& toBeFreed, UErrorCode& status)
1374 {
1375 if (U_FAILURE(status)) {
1376 return false;
1377 }
1378 if (region == nullptr) {
1379 // No region to search.
1380 return false;
1381 }
1382 const char *replacement = data->territoryMap().get(region);
1383 if (replacement == nullptr) {
1384 // Found no replacement data for this region.
1385 return false;
1386 }
1387 const char* replacedRegion = replacement;
1388 const char* firstSpace = uprv_strchr(replacement, ' ');
1389 if (firstSpace != nullptr) {
1390 // If there are are more than one region in the replacement.
1391 // We need to check which one match based on the language.
1392 // Cannot use nullptr for language because that will construct
1393 // the default locale, in that case, use "und" to get the correct
1394 // locale.
1395 Locale l = LocaleBuilder()
1396 .setLanguage(language == nullptr ? "und" : language)
1397 .setScript(script)
1398 .build(status);
1399 l.addLikelySubtags(status);
1400 const char* likelyRegion = l.getCountry();
1401 LocalPointer<CharString> item;
1402 if (likelyRegion != nullptr && uprv_strlen(likelyRegion) > 0) {
1403 size_t len = uprv_strlen(likelyRegion);
1404 const char* foundInReplacement = uprv_strstr(replacement,
1405 likelyRegion);
1406 if (foundInReplacement != nullptr) {
1407 // Assuming the case there are no three letter region code in
1408 // the replacement of territoryAlias
1409 U_ASSERT(foundInReplacement == replacement ||
1410 *(foundInReplacement-1) == ' ');
1411 U_ASSERT(foundInReplacement[len] == ' ' ||
1412 foundInReplacement[len] == '\0');
1413 item.adoptInsteadAndCheckErrorCode(
1414 new CharString(foundInReplacement, (int32_t)len, status), status);
1415 }
1416 }
1417 if (item.isNull() && U_SUCCESS(status)) {
1418 item.adoptInsteadAndCheckErrorCode(
1419 new CharString(replacement,
1420 (int32_t)(firstSpace - replacement), status), status);
1421 }
1422 if (U_FAILURE(status)) { return false; }
1423 if (item.isNull()) {
1424 status = U_MEMORY_ALLOCATION_ERROR;
1425 return false;
1426 }
1427 replacedRegion = item->data();
1428 toBeFreed.addElementX(item.orphan(), status);
1429 }
1430 U_ASSERT(!same(region, replacedRegion));
1431 region = replacedRegion;
1432 // The region is changed by data in territory alias.
1433 return true;
1434 }
1435
1436 bool
replaceScript(UErrorCode & status)1437 AliasReplacer::replaceScript(UErrorCode& status)
1438 {
1439 if (U_FAILURE(status)) {
1440 return false;
1441 }
1442 if (script == nullptr) {
1443 // No script to search.
1444 return false;
1445 }
1446 const char *replacement = data->scriptMap().get(script);
1447 if (replacement == nullptr) {
1448 // Found no replacement data for this script.
1449 return false;
1450 }
1451 U_ASSERT(!same(script, replacement));
1452 script = replacement;
1453 // The script is changed by data in script alias.
1454 return true;
1455 }
1456
1457 bool
replaceVariant(UErrorCode & status)1458 AliasReplacer::replaceVariant(UErrorCode& status)
1459 {
1460 if (U_FAILURE(status)) {
1461 return false;
1462 }
1463 // Since we may have more than one variant, we need to loop through them.
1464 for (int32_t i = 0; i < variants.size(); i++) {
1465 const char *variant = (const char*)(variants.elementAt(i));
1466 const char *replacement = data->variantMap().get(variant);
1467 if (replacement == nullptr) {
1468 // Found no replacement data for this variant.
1469 continue;
1470 }
1471 U_ASSERT((uprv_strlen(replacement) >= 5 &&
1472 uprv_strlen(replacement) <= 8) ||
1473 (uprv_strlen(replacement) == 4 &&
1474 replacement[0] >= '0' &&
1475 replacement[0] <= '9'));
1476 if (!same(variant, replacement)) {
1477 variants.setElementAt((void*)replacement, i);
1478 // Special hack to handle hepburn-heploc => alalc97
1479 if (uprv_strcmp(variant, "heploc") == 0) {
1480 for (int32_t j = 0; j < variants.size(); j++) {
1481 if (uprv_strcmp((const char*)(variants.elementAt(j)),
1482 "hepburn") == 0) {
1483 variants.removeElementAt(j);
1484 }
1485 }
1486 }
1487 return true;
1488 }
1489 }
1490 return false;
1491 }
1492
1493 bool
replaceSubdivision(StringPiece subdivision,CharString & output,UErrorCode & status)1494 AliasReplacer::replaceSubdivision(
1495 StringPiece subdivision, CharString& output, UErrorCode& status)
1496 {
1497 if (U_FAILURE(status)) {
1498 return false;
1499 }
1500 const char *replacement = data->subdivisionMap().get(subdivision.data());
1501 if (replacement != nullptr) {
1502 const char* firstSpace = uprv_strchr(replacement, ' ');
1503 // Found replacement data for this subdivision.
1504 size_t len = (firstSpace != nullptr) ?
1505 (firstSpace - replacement) : uprv_strlen(replacement);
1506 if (2 <= len && len <= 8) {
1507 output.append(replacement, (int32_t)len, status);
1508 if (2 == len) {
1509 // Add 'zzzz' based on changes to UTS #35 for CLDR-14312.
1510 output.append("zzzz", 4, status);
1511 }
1512 }
1513 return true;
1514 }
1515 return false;
1516 }
1517
1518 bool
replaceTransformedExtensions(CharString & transformedExtensions,CharString & output,UErrorCode & status)1519 AliasReplacer::replaceTransformedExtensions(
1520 CharString& transformedExtensions, CharString& output, UErrorCode& status)
1521 {
1522 // The content of the transformedExtensions will be modified in this
1523 // function to NULL-terminating (tkey-tvalue) pairs.
1524 if (U_FAILURE(status)) {
1525 return false;
1526 }
1527 int32_t len = transformedExtensions.length();
1528 const char* str = transformedExtensions.data();
1529 const char* tkey = ultag_getTKeyStart(str);
1530 int32_t tlangLen = (tkey == str) ? 0 :
1531 ((tkey == nullptr) ? len : static_cast<int32_t>((tkey - str - 1)));
1532 CharStringByteSink sink(&output);
1533 if (tlangLen > 0) {
1534 Locale tlang = LocaleBuilder()
1535 .setLanguageTag(StringPiece(str, tlangLen))
1536 .build(status);
1537 tlang.canonicalize(status);
1538 tlang.toLanguageTag(sink, status);
1539 if (U_FAILURE(status)) {
1540 return false;
1541 }
1542 T_CString_toLowerCase(output.data());
1543 }
1544 if (tkey != nullptr) {
1545 // We need to sort the tfields by tkey
1546 UVector tfields(status);
1547 if (U_FAILURE(status)) {
1548 return false;
1549 }
1550 do {
1551 const char* tvalue = uprv_strchr(tkey, '-');
1552 if (tvalue == nullptr) {
1553 status = U_ILLEGAL_ARGUMENT_ERROR;
1554 return false;
1555 }
1556 const char* nextTKey = ultag_getTKeyStart(tvalue);
1557 if (nextTKey != nullptr) {
1558 *((char*)(nextTKey-1)) = '\0'; // NULL terminate tvalue
1559 }
1560 tfields.insertElementAt((void*)tkey, tfields.size(), status);
1561 if (U_FAILURE(status)) {
1562 return false;
1563 }
1564 tkey = nextTKey;
1565 } while (tkey != nullptr);
1566 tfields.sort([](UElement e1, UElement e2) -> int32_t {
1567 return uprv_strcmp((const char*)e1.pointer, (const char*)e2.pointer);
1568 }, status);
1569 for (int32_t i = 0; i < tfields.size(); i++) {
1570 if (output.length() > 0) {
1571 output.append('-', status);
1572 }
1573 const char* tfield = (const char*) tfields.elementAt(i);
1574 const char* tvalue = uprv_strchr(tfield, '-');
1575 if (tvalue == nullptr) {
1576 status = U_ILLEGAL_ARGUMENT_ERROR;
1577 return false;
1578 }
1579 // Split the "tkey-tvalue" pair string so that we can canonicalize the tvalue.
1580 *((char*)tvalue++) = '\0'; // NULL terminate tkey
1581 output.append(tfield, status).append('-', status);
1582 const char* bcpTValue = ulocimp_toBcpType(tfield, tvalue, nullptr, nullptr);
1583 output.append((bcpTValue == nullptr) ? tvalue : bcpTValue, status);
1584 }
1585 }
1586 if (U_FAILURE(status)) {
1587 return false;
1588 }
1589 return true;
1590 }
1591
1592 CharString&
outputToString(CharString & out,UErrorCode status)1593 AliasReplacer::outputToString(
1594 CharString& out, UErrorCode status)
1595 {
1596 out.append(language, status);
1597 if (notEmpty(script)) {
1598 out.append(SEP_CHAR, status)
1599 .append(script, status);
1600 }
1601 if (notEmpty(region)) {
1602 out.append(SEP_CHAR, status)
1603 .append(region, status);
1604 }
1605 if (variants.size() > 0) {
1606 if (!notEmpty(script) && !notEmpty(region)) {
1607 out.append(SEP_CHAR, status);
1608 }
1609 variants.sort([](UElement e1, UElement e2) -> int32_t {
1610 return uprv_strcmp((const char*)e1.pointer, (const char*)e2.pointer);
1611 }, status);
1612 int32_t variantsStart = out.length();
1613 for (int32_t i = 0; i < variants.size(); i++) {
1614 out.append(SEP_CHAR, status)
1615 .append((const char*)(variants.elementAt(i)),
1616 status);
1617 }
1618 T_CString_toUpperCase(out.data() + variantsStart);
1619 }
1620 if (notEmpty(extensions)) {
1621 CharString tmp("und_", status);
1622 tmp.append(extensions, status);
1623 Locale tmpLocale(tmp.data());
1624 // only support x extension inside CLDR for now.
1625 U_ASSERT(extensions[0] == 'x');
1626 out.append(tmpLocale.getName() + 1, status);
1627 }
1628 return out;
1629 }
1630
1631 bool
replace(const Locale & locale,CharString & out,UErrorCode & status)1632 AliasReplacer::replace(const Locale& locale, CharString& out, UErrorCode& status)
1633 {
1634 data = AliasData::singleton(status);
1635 if (U_FAILURE(status)) {
1636 return false;
1637 }
1638 U_ASSERT(data != nullptr);
1639 out.clear();
1640 language = locale.getLanguage();
1641 if (!notEmpty(language)) {
1642 language = nullptr;
1643 }
1644 script = locale.getScript();
1645 if (!notEmpty(script)) {
1646 script = nullptr;
1647 }
1648 region = locale.getCountry();
1649 if (!notEmpty(region)) {
1650 region = nullptr;
1651 }
1652 const char* variantsStr = locale.getVariant();
1653 CharString variantsBuff(variantsStr, -1, status);
1654 if (!variantsBuff.isEmpty()) {
1655 if (U_FAILURE(status)) { return false; }
1656 char* start = variantsBuff.data();
1657 T_CString_toLowerCase(start);
1658 char* end;
1659 while ((end = uprv_strchr(start, SEP_CHAR)) != nullptr &&
1660 U_SUCCESS(status)) {
1661 *end = NULL_CHAR; // null terminate inside variantsBuff
1662 variants.addElementX(start, status);
1663 start = end + 1;
1664 }
1665 variants.addElementX(start, status);
1666 }
1667 if (U_FAILURE(status)) { return false; }
1668
1669 // Sort the variants
1670 variants.sort([](UElement e1, UElement e2) -> int32_t {
1671 return uprv_strcmp((const char*)e1.pointer, (const char*)e2.pointer);
1672 }, status);
1673
1674 // A changed count to assert when loop too many times.
1675 int changed = 0;
1676 // A UVector to to hold CharString allocated by the replace* method
1677 // and freed when out of scope from his function.
1678 UVector stringsToBeFreed([](void *obj){ delete ((CharString*) obj); },
1679 nullptr, 10, status);
1680 while (U_SUCCESS(status)) {
1681 // Something wrong with the data cause looping here more than 10 times
1682 // already.
1683 U_ASSERT(changed < 5);
1684 // From observation of key in data/misc/metadata.txt
1685 // we know currently we only need to search in the following combination
1686 // of fields for type in languageAlias:
1687 // * lang_region_variant
1688 // * lang_region
1689 // * lang_variant
1690 // * lang
1691 // * und_variant
1692 // This assumption is ensured by the U_ASSERT in readLanguageAlias
1693 //
1694 // lang REGION variant
1695 if ( replaceLanguage(true, true, true, stringsToBeFreed, status) ||
1696 replaceLanguage(true, true, false, stringsToBeFreed, status) ||
1697 replaceLanguage(true, false, true, stringsToBeFreed, status) ||
1698 replaceLanguage(true, false, false, stringsToBeFreed, status) ||
1699 replaceLanguage(false,false, true, stringsToBeFreed, status) ||
1700 replaceTerritory(stringsToBeFreed, status) ||
1701 replaceScript(status) ||
1702 replaceVariant(status)) {
1703 // Some values in data is changed, try to match from the beginning
1704 // again.
1705 changed++;
1706 continue;
1707 }
1708 // Nothing changed. Break out.
1709 break;
1710 } // while(1)
1711
1712 if (U_FAILURE(status)) { return false; }
1713 // Nothing changed and we know the order of the variants are not change
1714 // because we have no variant or only one.
1715 const char* extensionsStr = locale_getKeywordsStart(locale.getName());
1716 if (changed == 0 && variants.size() <= 1 && extensionsStr == nullptr) {
1717 return false;
1718 }
1719 outputToString(out, status);
1720 if (U_FAILURE(status)) {
1721 return false;
1722 }
1723 if (extensionsStr != nullptr) {
1724 changed = 0;
1725 Locale temp(locale);
1726 LocalPointer<icu::StringEnumeration> iter(locale.createKeywords(status));
1727 if (U_SUCCESS(status) && !iter.isNull()) {
1728 const char* key;
1729 while ((key = iter->next(nullptr, status)) != nullptr) {
1730 if (uprv_strcmp("sd", key) == 0 || uprv_strcmp("rg", key) == 0 ||
1731 uprv_strcmp("t", key) == 0) {
1732 CharString value;
1733 CharStringByteSink valueSink(&value);
1734 locale.getKeywordValue(key, valueSink, status);
1735 if (U_FAILURE(status)) {
1736 status = U_ZERO_ERROR;
1737 continue;
1738 }
1739 CharString replacement;
1740 if (uprv_strlen(key) == 2) {
1741 if (replaceSubdivision(value.toStringPiece(), replacement, status)) {
1742 changed++;
1743 temp.setKeywordValue(key, replacement.data(), status);
1744 }
1745 } else {
1746 U_ASSERT(uprv_strcmp(key, "t") == 0);
1747 if (replaceTransformedExtensions(value, replacement, status)) {
1748 changed++;
1749 temp.setKeywordValue(key, replacement.data(), status);
1750 }
1751 }
1752 if (U_FAILURE(status)) {
1753 return false;
1754 }
1755 }
1756 }
1757 }
1758 if (changed != 0) {
1759 extensionsStr = locale_getKeywordsStart(temp.getName());
1760 }
1761 out.append(extensionsStr, status);
1762 }
1763 if (U_FAILURE(status)) {
1764 return false;
1765 }
1766 // If the tag is not changed, return.
1767 if (uprv_strcmp(out.data(), locale.getName()) == 0) {
1768 out.clear();
1769 return false;
1770 }
1771 return true;
1772 }
1773
1774 // Return true if the locale is changed during canonicalization.
1775 // The replaced value then will be put into out.
1776 bool
canonicalizeLocale(const Locale & locale,CharString & out,UErrorCode & status)1777 canonicalizeLocale(const Locale& locale, CharString& out, UErrorCode& status)
1778 {
1779 AliasReplacer replacer(status);
1780 return replacer.replace(locale, out, status);
1781 }
1782
1783 // Function to optimize for known cases without so we can skip the loading
1784 // of resources in the startup time until we really need it.
1785 bool
isKnownCanonicalizedLocale(const char * locale,UErrorCode & status)1786 isKnownCanonicalizedLocale(const char* locale, UErrorCode& status)
1787 {
1788 if ( uprv_strcmp(locale, "c") == 0 ||
1789 uprv_strcmp(locale, "en") == 0 ||
1790 uprv_strcmp(locale, "en_US") == 0) {
1791 return true;
1792 }
1793
1794 // common well-known Canonicalized.
1795 umtx_initOnce(gKnownCanonicalizedInitOnce,
1796 &loadKnownCanonicalized, status);
1797 if (U_FAILURE(status)) {
1798 return false;
1799 }
1800 U_ASSERT(gKnownCanonicalized != nullptr);
1801 return uhash_geti(gKnownCanonicalized, locale) != 0;
1802 }
1803
1804 } // namespace
1805
1806 // Function for testing.
1807 U_CAPI const char* const*
ulocimp_getKnownCanonicalizedLocaleForTest(int32_t * length)1808 ulocimp_getKnownCanonicalizedLocaleForTest(int32_t* length)
1809 {
1810 *length = UPRV_LENGTHOF(KNOWN_CANONICALIZED);
1811 return KNOWN_CANONICALIZED;
1812 }
1813
1814 // Function for testing.
1815 U_CAPI bool
ulocimp_isCanonicalizedLocaleForTest(const char * localeName)1816 ulocimp_isCanonicalizedLocaleForTest(const char* localeName)
1817 {
1818 Locale l(localeName);
1819 UErrorCode status = U_ZERO_ERROR;
1820 CharString temp;
1821 return !canonicalizeLocale(l, temp, status) && U_SUCCESS(status);
1822 }
1823
1824 /*This function initializes a Locale from a C locale ID*/
init(const char * localeID,UBool canonicalize)1825 Locale& Locale::init(const char* localeID, UBool canonicalize)
1826 {
1827 fIsBogus = FALSE;
1828 /* Free our current storage */
1829 if ((baseName != fullName) && (baseName != fullNameBuffer)) {
1830 uprv_free(baseName);
1831 }
1832 baseName = NULL;
1833 if(fullName != fullNameBuffer) {
1834 uprv_free(fullName);
1835 fullName = fullNameBuffer;
1836 }
1837
1838 // not a loop:
1839 // just an easy way to have a common error-exit
1840 // without goto and without another function
1841 do {
1842 char *separator;
1843 char *field[5] = {0};
1844 int32_t fieldLen[5] = {0};
1845 int32_t fieldIdx;
1846 int32_t variantField;
1847 int32_t length;
1848 UErrorCode err;
1849
1850 if(localeID == NULL) {
1851 // not an error, just set the default locale
1852 return *this = getDefault();
1853 }
1854
1855 /* preset all fields to empty */
1856 language[0] = script[0] = country[0] = 0;
1857
1858 // "canonicalize" the locale ID to ICU/Java format
1859 err = U_ZERO_ERROR;
1860 length = canonicalize ?
1861 uloc_canonicalize(localeID, fullName, sizeof(fullNameBuffer), &err) :
1862 uloc_getName(localeID, fullName, sizeof(fullNameBuffer), &err);
1863
1864 if(err == U_BUFFER_OVERFLOW_ERROR || length >= (int32_t)sizeof(fullNameBuffer)) {
1865 U_ASSERT(baseName == nullptr);
1866 /*Go to heap for the fullName if necessary*/
1867 fullName = (char *)uprv_malloc(sizeof(char)*(length + 1));
1868 if(fullName == 0) {
1869 fullName = fullNameBuffer;
1870 break; // error: out of memory
1871 }
1872 err = U_ZERO_ERROR;
1873 length = canonicalize ?
1874 uloc_canonicalize(localeID, fullName, length+1, &err) :
1875 uloc_getName(localeID, fullName, length+1, &err);
1876 }
1877 if(U_FAILURE(err) || err == U_STRING_NOT_TERMINATED_WARNING) {
1878 /* should never occur */
1879 break;
1880 }
1881
1882 variantBegin = length;
1883
1884 /* after uloc_getName/canonicalize() we know that only '_' are separators */
1885 /* But _ could also appeared in timezone such as "en@timezone=America/Los_Angeles" */
1886 separator = field[0] = fullName;
1887 fieldIdx = 1;
1888 char* at = uprv_strchr(fullName, '@');
1889 while ((separator = uprv_strchr(field[fieldIdx-1], SEP_CHAR)) != 0 &&
1890 fieldIdx < UPRV_LENGTHOF(field)-1 &&
1891 (at == nullptr || separator < at)) {
1892 field[fieldIdx] = separator + 1;
1893 fieldLen[fieldIdx-1] = (int32_t)(separator - field[fieldIdx-1]);
1894 fieldIdx++;
1895 }
1896 // variant may contain @foo or .foo POSIX cruft; remove it
1897 separator = uprv_strchr(field[fieldIdx-1], '@');
1898 char* sep2 = uprv_strchr(field[fieldIdx-1], '.');
1899 if (separator!=NULL || sep2!=NULL) {
1900 if (separator==NULL || (sep2!=NULL && separator > sep2)) {
1901 separator = sep2;
1902 }
1903 fieldLen[fieldIdx-1] = (int32_t)(separator - field[fieldIdx-1]);
1904 } else {
1905 fieldLen[fieldIdx-1] = length - (int32_t)(field[fieldIdx-1] - fullName);
1906 }
1907
1908 if (fieldLen[0] >= (int32_t)(sizeof(language)))
1909 {
1910 break; // error: the language field is too long
1911 }
1912
1913 variantField = 1; /* Usually the 2nd one, except when a script or country is also used. */
1914 if (fieldLen[0] > 0) {
1915 /* We have a language */
1916 uprv_memcpy(language, fullName, fieldLen[0]);
1917 language[fieldLen[0]] = 0;
1918 }
1919 if (fieldLen[1] == 4 && uprv_isASCIILetter(field[1][0]) &&
1920 uprv_isASCIILetter(field[1][1]) && uprv_isASCIILetter(field[1][2]) &&
1921 uprv_isASCIILetter(field[1][3])) {
1922 /* We have at least a script */
1923 uprv_memcpy(script, field[1], fieldLen[1]);
1924 script[fieldLen[1]] = 0;
1925 variantField++;
1926 }
1927
1928 if (fieldLen[variantField] == 2 || fieldLen[variantField] == 3) {
1929 /* We have a country */
1930 uprv_memcpy(country, field[variantField], fieldLen[variantField]);
1931 country[fieldLen[variantField]] = 0;
1932 variantField++;
1933 } else if (fieldLen[variantField] == 0) {
1934 variantField++; /* script or country empty but variant in next field (i.e. en__POSIX) */
1935 }
1936
1937 if (fieldLen[variantField] > 0) {
1938 /* We have a variant */
1939 variantBegin = (int32_t)(field[variantField] - fullName);
1940 }
1941
1942 err = U_ZERO_ERROR;
1943 initBaseName(err);
1944 if (U_FAILURE(err)) {
1945 break;
1946 }
1947
1948 if (canonicalize) {
1949 if (!isKnownCanonicalizedLocale(fullName, err)) {
1950 CharString replaced;
1951 // Not sure it is already canonicalized
1952 if (canonicalizeLocale(*this, replaced, err)) {
1953 U_ASSERT(U_SUCCESS(err));
1954 // If need replacement, call init again.
1955 init(replaced.data(), false);
1956 }
1957 if (U_FAILURE(err)) {
1958 break;
1959 }
1960 }
1961 } // if (canonicalize) {
1962
1963 // successful end of init()
1964 return *this;
1965 } while(0); /*loop doesn't iterate*/
1966
1967 // when an error occurs, then set this object to "bogus" (there is no UErrorCode here)
1968 setToBogus();
1969
1970 return *this;
1971 }
1972
1973 /*
1974 * Set up the base name.
1975 * If there are no key words, it's exactly the full name.
1976 * If key words exist, it's the full name truncated at the '@' character.
1977 * Need to set up both at init() and after setting a keyword.
1978 */
1979 void
initBaseName(UErrorCode & status)1980 Locale::initBaseName(UErrorCode &status) {
1981 if (U_FAILURE(status)) {
1982 return;
1983 }
1984 U_ASSERT(baseName==NULL || baseName==fullName);
1985 const char *atPtr = uprv_strchr(fullName, '@');
1986 const char *eqPtr = uprv_strchr(fullName, '=');
1987 if (atPtr && eqPtr && atPtr < eqPtr) {
1988 // Key words exist.
1989 int32_t baseNameLength = (int32_t)(atPtr - fullName);
1990 baseName = (char *)uprv_malloc(baseNameLength + 1);
1991 if (baseName == NULL) {
1992 status = U_MEMORY_ALLOCATION_ERROR;
1993 return;
1994 }
1995 uprv_strncpy(baseName, fullName, baseNameLength);
1996 baseName[baseNameLength] = 0;
1997
1998 // The original computation of variantBegin leaves it equal to the length
1999 // of fullName if there is no variant. It should instead be
2000 // the length of the baseName.
2001 if (variantBegin > baseNameLength) {
2002 variantBegin = baseNameLength;
2003 }
2004 } else {
2005 baseName = fullName;
2006 }
2007 }
2008
2009
2010 int32_t
hashCode() const2011 Locale::hashCode() const
2012 {
2013 return ustr_hashCharsN(fullName, static_cast<int32_t>(uprv_strlen(fullName)));
2014 }
2015
2016 void
setToBogus()2017 Locale::setToBogus() {
2018 /* Free our current storage */
2019 if((baseName != fullName) && (baseName != fullNameBuffer)) {
2020 uprv_free(baseName);
2021 }
2022 baseName = NULL;
2023 if(fullName != fullNameBuffer) {
2024 uprv_free(fullName);
2025 fullName = fullNameBuffer;
2026 }
2027 *fullNameBuffer = 0;
2028 *language = 0;
2029 *script = 0;
2030 *country = 0;
2031 fIsBogus = TRUE;
2032 variantBegin = 0;
2033 }
2034
2035 const Locale& U_EXPORT2
getDefault()2036 Locale::getDefault()
2037 {
2038 {
2039 Mutex lock(&gDefaultLocaleMutex);
2040 if (gDefaultLocale != NULL) {
2041 return *gDefaultLocale;
2042 }
2043 }
2044 UErrorCode status = U_ZERO_ERROR;
2045 return *locale_set_default_internal(NULL, status);
2046 }
2047
2048
2049
2050 void U_EXPORT2
setDefault(const Locale & newLocale,UErrorCode & status)2051 Locale::setDefault( const Locale& newLocale,
2052 UErrorCode& status)
2053 {
2054 if (U_FAILURE(status)) {
2055 return;
2056 }
2057
2058 /* Set the default from the full name string of the supplied locale.
2059 * This is a convenient way to access the default locale caching mechanisms.
2060 */
2061 const char *localeID = newLocale.getName();
2062 locale_set_default_internal(localeID, status);
2063 }
2064
2065 void
addLikelySubtags(UErrorCode & status)2066 Locale::addLikelySubtags(UErrorCode& status) {
2067 if (U_FAILURE(status)) {
2068 return;
2069 }
2070
2071 CharString maximizedLocaleID;
2072 {
2073 CharStringByteSink sink(&maximizedLocaleID);
2074 ulocimp_addLikelySubtags(fullName, sink, &status);
2075 }
2076
2077 if (U_FAILURE(status)) {
2078 return;
2079 }
2080
2081 init(maximizedLocaleID.data(), /*canonicalize=*/FALSE);
2082 if (isBogus()) {
2083 status = U_ILLEGAL_ARGUMENT_ERROR;
2084 }
2085 }
2086
2087 void
minimizeSubtags(UErrorCode & status)2088 Locale::minimizeSubtags(UErrorCode& status) {
2089 if (U_FAILURE(status)) {
2090 return;
2091 }
2092
2093 CharString minimizedLocaleID;
2094 {
2095 CharStringByteSink sink(&minimizedLocaleID);
2096 ulocimp_minimizeSubtags(fullName, sink, &status);
2097 }
2098
2099 if (U_FAILURE(status)) {
2100 return;
2101 }
2102
2103 init(minimizedLocaleID.data(), /*canonicalize=*/FALSE);
2104 if (isBogus()) {
2105 status = U_ILLEGAL_ARGUMENT_ERROR;
2106 }
2107 }
2108
2109 void
canonicalize(UErrorCode & status)2110 Locale::canonicalize(UErrorCode& status) {
2111 if (U_FAILURE(status)) {
2112 return;
2113 }
2114 if (isBogus()) {
2115 status = U_ILLEGAL_ARGUMENT_ERROR;
2116 return;
2117 }
2118 CharString uncanonicalized(fullName, status);
2119 if (U_FAILURE(status)) {
2120 return;
2121 }
2122 init(uncanonicalized.data(), /*canonicalize=*/TRUE);
2123 if (isBogus()) {
2124 status = U_ILLEGAL_ARGUMENT_ERROR;
2125 }
2126 }
2127
2128 Locale U_EXPORT2
forLanguageTag(StringPiece tag,UErrorCode & status)2129 Locale::forLanguageTag(StringPiece tag, UErrorCode& status)
2130 {
2131 Locale result(Locale::eBOGUS);
2132
2133 if (U_FAILURE(status)) {
2134 return result;
2135 }
2136
2137 // If a BCP 47 language tag is passed as the language parameter to the
2138 // normal Locale constructor, it will actually fall back to invoking
2139 // uloc_forLanguageTag() to parse it if it somehow is able to detect that
2140 // the string actually is BCP 47. This works well for things like strings
2141 // using BCP 47 extensions, but it does not at all work for things like
2142 // legacy language tags (marked as “Type: grandfathered” in BCP 47,
2143 // e.g., "en-GB-oed") which are possible to also
2144 // interpret as ICU locale IDs and because of that won't trigger the BCP 47
2145 // parsing. Therefore the code here explicitly calls uloc_forLanguageTag()
2146 // and then Locale::init(), instead of just calling the normal constructor.
2147
2148 CharString localeID;
2149 int32_t parsedLength;
2150 {
2151 CharStringByteSink sink(&localeID);
2152 ulocimp_forLanguageTag(
2153 tag.data(),
2154 tag.length(),
2155 sink,
2156 &parsedLength,
2157 &status);
2158 }
2159
2160 if (U_FAILURE(status)) {
2161 return result;
2162 }
2163
2164 if (parsedLength != tag.size()) {
2165 status = U_ILLEGAL_ARGUMENT_ERROR;
2166 return result;
2167 }
2168
2169 result.init(localeID.data(), /*canonicalize=*/FALSE);
2170 if (result.isBogus()) {
2171 status = U_ILLEGAL_ARGUMENT_ERROR;
2172 }
2173 return result;
2174 }
2175
2176 void
toLanguageTag(ByteSink & sink,UErrorCode & status) const2177 Locale::toLanguageTag(ByteSink& sink, UErrorCode& status) const
2178 {
2179 if (U_FAILURE(status)) {
2180 return;
2181 }
2182
2183 if (fIsBogus) {
2184 status = U_ILLEGAL_ARGUMENT_ERROR;
2185 return;
2186 }
2187
2188 ulocimp_toLanguageTag(fullName, sink, /*strict=*/FALSE, &status);
2189 }
2190
2191 Locale U_EXPORT2
createFromName(const char * name)2192 Locale::createFromName (const char *name)
2193 {
2194 if (name) {
2195 Locale l("");
2196 l.init(name, FALSE);
2197 return l;
2198 }
2199 else {
2200 return getDefault();
2201 }
2202 }
2203
2204 Locale U_EXPORT2
createCanonical(const char * name)2205 Locale::createCanonical(const char* name) {
2206 Locale loc("");
2207 loc.init(name, TRUE);
2208 return loc;
2209 }
2210
2211 const char *
getISO3Language() const2212 Locale::getISO3Language() const
2213 {
2214 return uloc_getISO3Language(fullName);
2215 }
2216
2217
2218 const char *
getISO3Country() const2219 Locale::getISO3Country() const
2220 {
2221 return uloc_getISO3Country(fullName);
2222 }
2223
2224 /**
2225 * Return the LCID value as specified in the "LocaleID" resource for this
2226 * locale. The LocaleID must be expressed as a hexadecimal number, from
2227 * one to four digits. If the LocaleID resource is not present, or is
2228 * in an incorrect format, 0 is returned. The LocaleID is for use in
2229 * Windows (it is an LCID), but is available on all platforms.
2230 */
2231 uint32_t
getLCID() const2232 Locale::getLCID() const
2233 {
2234 return uloc_getLCID(fullName);
2235 }
2236
getISOCountries()2237 const char* const* U_EXPORT2 Locale::getISOCountries()
2238 {
2239 return uloc_getISOCountries();
2240 }
2241
getISOLanguages()2242 const char* const* U_EXPORT2 Locale::getISOLanguages()
2243 {
2244 return uloc_getISOLanguages();
2245 }
2246
2247 // Set the locale's data based on a posix id.
setFromPOSIXID(const char * posixID)2248 void Locale::setFromPOSIXID(const char *posixID)
2249 {
2250 init(posixID, TRUE);
2251 }
2252
2253 const Locale & U_EXPORT2
getRoot(void)2254 Locale::getRoot(void)
2255 {
2256 return getLocale(eROOT);
2257 }
2258
2259 const Locale & U_EXPORT2
getEnglish(void)2260 Locale::getEnglish(void)
2261 {
2262 return getLocale(eENGLISH);
2263 }
2264
2265 const Locale & U_EXPORT2
getFrench(void)2266 Locale::getFrench(void)
2267 {
2268 return getLocale(eFRENCH);
2269 }
2270
2271 const Locale & U_EXPORT2
getGerman(void)2272 Locale::getGerman(void)
2273 {
2274 return getLocale(eGERMAN);
2275 }
2276
2277 const Locale & U_EXPORT2
getItalian(void)2278 Locale::getItalian(void)
2279 {
2280 return getLocale(eITALIAN);
2281 }
2282
2283 const Locale & U_EXPORT2
getJapanese(void)2284 Locale::getJapanese(void)
2285 {
2286 return getLocale(eJAPANESE);
2287 }
2288
2289 const Locale & U_EXPORT2
getKorean(void)2290 Locale::getKorean(void)
2291 {
2292 return getLocale(eKOREAN);
2293 }
2294
2295 const Locale & U_EXPORT2
getChinese(void)2296 Locale::getChinese(void)
2297 {
2298 return getLocale(eCHINESE);
2299 }
2300
2301 const Locale & U_EXPORT2
getSimplifiedChinese(void)2302 Locale::getSimplifiedChinese(void)
2303 {
2304 return getLocale(eCHINA);
2305 }
2306
2307 const Locale & U_EXPORT2
getTraditionalChinese(void)2308 Locale::getTraditionalChinese(void)
2309 {
2310 return getLocale(eTAIWAN);
2311 }
2312
2313
2314 const Locale & U_EXPORT2
getFrance(void)2315 Locale::getFrance(void)
2316 {
2317 return getLocale(eFRANCE);
2318 }
2319
2320 const Locale & U_EXPORT2
getGermany(void)2321 Locale::getGermany(void)
2322 {
2323 return getLocale(eGERMANY);
2324 }
2325
2326 const Locale & U_EXPORT2
getItaly(void)2327 Locale::getItaly(void)
2328 {
2329 return getLocale(eITALY);
2330 }
2331
2332 const Locale & U_EXPORT2
getJapan(void)2333 Locale::getJapan(void)
2334 {
2335 return getLocale(eJAPAN);
2336 }
2337
2338 const Locale & U_EXPORT2
getKorea(void)2339 Locale::getKorea(void)
2340 {
2341 return getLocale(eKOREA);
2342 }
2343
2344 const Locale & U_EXPORT2
getChina(void)2345 Locale::getChina(void)
2346 {
2347 return getLocale(eCHINA);
2348 }
2349
2350 const Locale & U_EXPORT2
getPRC(void)2351 Locale::getPRC(void)
2352 {
2353 return getLocale(eCHINA);
2354 }
2355
2356 const Locale & U_EXPORT2
getTaiwan(void)2357 Locale::getTaiwan(void)
2358 {
2359 return getLocale(eTAIWAN);
2360 }
2361
2362 const Locale & U_EXPORT2
getUK(void)2363 Locale::getUK(void)
2364 {
2365 return getLocale(eUK);
2366 }
2367
2368 const Locale & U_EXPORT2
getUS(void)2369 Locale::getUS(void)
2370 {
2371 return getLocale(eUS);
2372 }
2373
2374 const Locale & U_EXPORT2
getCanada(void)2375 Locale::getCanada(void)
2376 {
2377 return getLocale(eCANADA);
2378 }
2379
2380 const Locale & U_EXPORT2
getCanadaFrench(void)2381 Locale::getCanadaFrench(void)
2382 {
2383 return getLocale(eCANADA_FRENCH);
2384 }
2385
2386 const Locale &
getLocale(int locid)2387 Locale::getLocale(int locid)
2388 {
2389 Locale *localeCache = getLocaleCache();
2390 U_ASSERT((locid < eMAX_LOCALES)&&(locid>=0));
2391 if (localeCache == NULL) {
2392 // Failure allocating the locale cache.
2393 // The best we can do is return a NULL reference.
2394 locid = 0;
2395 }
2396 return localeCache[locid]; /*operating on NULL*/
2397 }
2398
2399 /*
2400 This function is defined this way in order to get around static
2401 initialization and static destruction.
2402 */
2403 Locale *
getLocaleCache(void)2404 Locale::getLocaleCache(void)
2405 {
2406 UErrorCode status = U_ZERO_ERROR;
2407 umtx_initOnce(gLocaleCacheInitOnce, locale_init, status);
2408 return gLocaleCache;
2409 }
2410
2411 class KeywordEnumeration : public StringEnumeration {
2412 private:
2413 char *keywords;
2414 char *current;
2415 int32_t length;
2416 UnicodeString currUSKey;
2417 static const char fgClassID;/* Warning this is used beyond the typical RTTI usage. */
2418
2419 public:
getStaticClassID(void)2420 static UClassID U_EXPORT2 getStaticClassID(void) { return (UClassID)&fgClassID; }
getDynamicClassID(void) const2421 virtual UClassID getDynamicClassID(void) const override { return getStaticClassID(); }
2422 public:
KeywordEnumeration(const char * keys,int32_t keywordLen,int32_t currentIndex,UErrorCode & status)2423 KeywordEnumeration(const char *keys, int32_t keywordLen, int32_t currentIndex, UErrorCode &status)
2424 : keywords((char *)&fgClassID), current((char *)&fgClassID), length(0) {
2425 if(U_SUCCESS(status) && keywordLen != 0) {
2426 if(keys == NULL || keywordLen < 0) {
2427 status = U_ILLEGAL_ARGUMENT_ERROR;
2428 } else {
2429 keywords = (char *)uprv_malloc(keywordLen+1);
2430 if (keywords == NULL) {
2431 status = U_MEMORY_ALLOCATION_ERROR;
2432 }
2433 else {
2434 uprv_memcpy(keywords, keys, keywordLen);
2435 keywords[keywordLen] = 0;
2436 current = keywords + currentIndex;
2437 length = keywordLen;
2438 }
2439 }
2440 }
2441 }
2442
2443 virtual ~KeywordEnumeration();
2444
clone() const2445 virtual StringEnumeration * clone() const override
2446 {
2447 UErrorCode status = U_ZERO_ERROR;
2448 return new KeywordEnumeration(keywords, length, (int32_t)(current - keywords), status);
2449 }
2450
count(UErrorCode &) const2451 virtual int32_t count(UErrorCode &/*status*/) const override {
2452 char *kw = keywords;
2453 int32_t result = 0;
2454 while(*kw) {
2455 result++;
2456 kw += uprv_strlen(kw)+1;
2457 }
2458 return result;
2459 }
2460
next(int32_t * resultLength,UErrorCode & status)2461 virtual const char* next(int32_t* resultLength, UErrorCode& status) override {
2462 const char* result;
2463 int32_t len;
2464 if(U_SUCCESS(status) && *current != 0) {
2465 result = current;
2466 len = (int32_t)uprv_strlen(current);
2467 current += len+1;
2468 if(resultLength != NULL) {
2469 *resultLength = len;
2470 }
2471 } else {
2472 if(resultLength != NULL) {
2473 *resultLength = 0;
2474 }
2475 result = NULL;
2476 }
2477 return result;
2478 }
2479
snext(UErrorCode & status)2480 virtual const UnicodeString* snext(UErrorCode& status) override {
2481 int32_t resultLength = 0;
2482 const char *s = next(&resultLength, status);
2483 return setChars(s, resultLength, status);
2484 }
2485
reset(UErrorCode &)2486 virtual void reset(UErrorCode& /*status*/) override {
2487 current = keywords;
2488 }
2489 };
2490
2491 const char KeywordEnumeration::fgClassID = '\0';
2492
~KeywordEnumeration()2493 KeywordEnumeration::~KeywordEnumeration() {
2494 uprv_free(keywords);
2495 }
2496
2497 // A wrapper around KeywordEnumeration that calls uloc_toUnicodeLocaleKey() in
2498 // the next() method for each keyword before returning it.
2499 class UnicodeKeywordEnumeration : public KeywordEnumeration {
2500 public:
2501 using KeywordEnumeration::KeywordEnumeration;
2502 virtual ~UnicodeKeywordEnumeration();
2503
next(int32_t * resultLength,UErrorCode & status)2504 virtual const char* next(int32_t* resultLength, UErrorCode& status) override {
2505 const char* legacy_key = KeywordEnumeration::next(nullptr, status);
2506 while (U_SUCCESS(status) && legacy_key != nullptr) {
2507 const char* key = uloc_toUnicodeLocaleKey(legacy_key);
2508 if (key != nullptr) {
2509 if (resultLength != nullptr) {
2510 *resultLength = static_cast<int32_t>(uprv_strlen(key));
2511 }
2512 return key;
2513 }
2514 // Not a Unicode keyword, could be a t, x or other, continue to look at the next one.
2515 legacy_key = KeywordEnumeration::next(nullptr, status);
2516 }
2517 if (resultLength != nullptr) *resultLength = 0;
2518 return nullptr;
2519 }
2520 };
2521
2522 // Out-of-line virtual destructor to serve as the "key function".
2523 UnicodeKeywordEnumeration::~UnicodeKeywordEnumeration() = default;
2524
2525 StringEnumeration *
createKeywords(UErrorCode & status) const2526 Locale::createKeywords(UErrorCode &status) const
2527 {
2528 StringEnumeration *result = NULL;
2529
2530 if (U_FAILURE(status)) {
2531 return result;
2532 }
2533
2534 const char* variantStart = uprv_strchr(fullName, '@');
2535 const char* assignment = uprv_strchr(fullName, '=');
2536 if(variantStart) {
2537 if(assignment > variantStart) {
2538 CharString keywords;
2539 CharStringByteSink sink(&keywords);
2540 ulocimp_getKeywords(variantStart+1, '@', sink, FALSE, &status);
2541 if (U_SUCCESS(status) && !keywords.isEmpty()) {
2542 result = new KeywordEnumeration(keywords.data(), keywords.length(), 0, status);
2543 if (!result) {
2544 status = U_MEMORY_ALLOCATION_ERROR;
2545 }
2546 }
2547 } else {
2548 status = U_INVALID_FORMAT_ERROR;
2549 }
2550 }
2551 return result;
2552 }
2553
2554 StringEnumeration *
createUnicodeKeywords(UErrorCode & status) const2555 Locale::createUnicodeKeywords(UErrorCode &status) const
2556 {
2557 StringEnumeration *result = NULL;
2558
2559 if (U_FAILURE(status)) {
2560 return result;
2561 }
2562
2563 const char* variantStart = uprv_strchr(fullName, '@');
2564 const char* assignment = uprv_strchr(fullName, '=');
2565 if(variantStart) {
2566 if(assignment > variantStart) {
2567 CharString keywords;
2568 CharStringByteSink sink(&keywords);
2569 ulocimp_getKeywords(variantStart+1, '@', sink, FALSE, &status);
2570 if (U_SUCCESS(status) && !keywords.isEmpty()) {
2571 result = new UnicodeKeywordEnumeration(keywords.data(), keywords.length(), 0, status);
2572 if (!result) {
2573 status = U_MEMORY_ALLOCATION_ERROR;
2574 }
2575 }
2576 } else {
2577 status = U_INVALID_FORMAT_ERROR;
2578 }
2579 }
2580 return result;
2581 }
2582
2583 int32_t
getKeywordValue(const char * keywordName,char * buffer,int32_t bufLen,UErrorCode & status) const2584 Locale::getKeywordValue(const char* keywordName, char *buffer, int32_t bufLen, UErrorCode &status) const
2585 {
2586 return uloc_getKeywordValue(fullName, keywordName, buffer, bufLen, &status);
2587 }
2588
2589 void
getKeywordValue(StringPiece keywordName,ByteSink & sink,UErrorCode & status) const2590 Locale::getKeywordValue(StringPiece keywordName, ByteSink& sink, UErrorCode& status) const {
2591 if (U_FAILURE(status)) {
2592 return;
2593 }
2594
2595 if (fIsBogus) {
2596 status = U_ILLEGAL_ARGUMENT_ERROR;
2597 return;
2598 }
2599
2600 // TODO: Remove the need for a const char* to a NUL terminated buffer.
2601 const CharString keywordName_nul(keywordName, status);
2602 if (U_FAILURE(status)) {
2603 return;
2604 }
2605
2606 ulocimp_getKeywordValue(fullName, keywordName_nul.data(), sink, &status);
2607 }
2608
2609 void
getUnicodeKeywordValue(StringPiece keywordName,ByteSink & sink,UErrorCode & status) const2610 Locale::getUnicodeKeywordValue(StringPiece keywordName,
2611 ByteSink& sink,
2612 UErrorCode& status) const {
2613 // TODO: Remove the need for a const char* to a NUL terminated buffer.
2614 const CharString keywordName_nul(keywordName, status);
2615 if (U_FAILURE(status)) {
2616 return;
2617 }
2618
2619 const char* legacy_key = uloc_toLegacyKey(keywordName_nul.data());
2620
2621 if (legacy_key == nullptr) {
2622 status = U_ILLEGAL_ARGUMENT_ERROR;
2623 return;
2624 }
2625
2626 CharString legacy_value;
2627 {
2628 CharStringByteSink sink(&legacy_value);
2629 getKeywordValue(legacy_key, sink, status);
2630 }
2631
2632 if (U_FAILURE(status)) {
2633 return;
2634 }
2635
2636 const char* unicode_value = uloc_toUnicodeLocaleType(
2637 keywordName_nul.data(), legacy_value.data());
2638
2639 if (unicode_value == nullptr) {
2640 status = U_ILLEGAL_ARGUMENT_ERROR;
2641 return;
2642 }
2643
2644 sink.Append(unicode_value, static_cast<int32_t>(uprv_strlen(unicode_value)));
2645 }
2646
2647 void
setKeywordValue(const char * keywordName,const char * keywordValue,UErrorCode & status)2648 Locale::setKeywordValue(const char* keywordName, const char* keywordValue, UErrorCode &status)
2649 {
2650 if (U_FAILURE(status)) {
2651 return;
2652 }
2653 if (status == U_STRING_NOT_TERMINATED_WARNING) {
2654 status = U_ZERO_ERROR;
2655 }
2656 int32_t bufferLength = uprv_max((int32_t)(uprv_strlen(fullName) + 1), ULOC_FULLNAME_CAPACITY);
2657 int32_t newLength = uloc_setKeywordValue(keywordName, keywordValue, fullName,
2658 bufferLength, &status) + 1;
2659 U_ASSERT(status != U_STRING_NOT_TERMINATED_WARNING);
2660 /* Handle the case the current buffer is not enough to hold the new id */
2661 if (status == U_BUFFER_OVERFLOW_ERROR) {
2662 U_ASSERT(newLength > bufferLength);
2663 char* newFullName = (char *)uprv_malloc(newLength);
2664 if (newFullName == nullptr) {
2665 status = U_MEMORY_ALLOCATION_ERROR;
2666 return;
2667 }
2668 uprv_strcpy(newFullName, fullName);
2669 if (fullName != fullNameBuffer) {
2670 // if full Name is already on the heap, need to free it.
2671 uprv_free(fullName);
2672 if (baseName == fullName) {
2673 baseName = newFullName; // baseName should not point to freed memory.
2674 }
2675 }
2676 fullName = newFullName;
2677 status = U_ZERO_ERROR;
2678 uloc_setKeywordValue(keywordName, keywordValue, fullName, newLength, &status);
2679 U_ASSERT(status != U_STRING_NOT_TERMINATED_WARNING);
2680 } else {
2681 U_ASSERT(newLength <= bufferLength);
2682 }
2683 if (U_SUCCESS(status) && baseName == fullName) {
2684 // May have added the first keyword, meaning that the fullName is no longer also the baseName.
2685 initBaseName(status);
2686 }
2687 }
2688
2689 void
setKeywordValue(StringPiece keywordName,StringPiece keywordValue,UErrorCode & status)2690 Locale::setKeywordValue(StringPiece keywordName,
2691 StringPiece keywordValue,
2692 UErrorCode& status) {
2693 // TODO: Remove the need for a const char* to a NUL terminated buffer.
2694 const CharString keywordName_nul(keywordName, status);
2695 const CharString keywordValue_nul(keywordValue, status);
2696 setKeywordValue(keywordName_nul.data(), keywordValue_nul.data(), status);
2697 }
2698
2699 void
setUnicodeKeywordValue(StringPiece keywordName,StringPiece keywordValue,UErrorCode & status)2700 Locale::setUnicodeKeywordValue(StringPiece keywordName,
2701 StringPiece keywordValue,
2702 UErrorCode& status) {
2703 // TODO: Remove the need for a const char* to a NUL terminated buffer.
2704 const CharString keywordName_nul(keywordName, status);
2705 const CharString keywordValue_nul(keywordValue, status);
2706
2707 if (U_FAILURE(status)) {
2708 return;
2709 }
2710
2711 const char* legacy_key = uloc_toLegacyKey(keywordName_nul.data());
2712
2713 if (legacy_key == nullptr) {
2714 status = U_ILLEGAL_ARGUMENT_ERROR;
2715 return;
2716 }
2717
2718 const char* legacy_value = nullptr;
2719
2720 if (!keywordValue_nul.isEmpty()) {
2721 legacy_value =
2722 uloc_toLegacyType(keywordName_nul.data(), keywordValue_nul.data());
2723
2724 if (legacy_value == nullptr) {
2725 status = U_ILLEGAL_ARGUMENT_ERROR;
2726 return;
2727 }
2728 }
2729
2730 setKeywordValue(legacy_key, legacy_value, status);
2731 }
2732
2733 const char *
getBaseName() const2734 Locale::getBaseName() const {
2735 return baseName;
2736 }
2737
2738 Locale::Iterator::~Iterator() = default;
2739
2740 //eof
2741 U_NAMESPACE_END
2742