locid.cpp 85 KB

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