locid.cpp 85 KB

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