uloc.cpp 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421
  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 ULOC.CPP
  10. *
  11. * Modification History:
  12. *
  13. * Date Name Description
  14. * 04/01/97 aliu Creation.
  15. * 08/21/98 stephen JDK 1.2 sync
  16. * 12/08/98 rtg New Locale implementation and C API
  17. * 03/15/99 damiba overhaul.
  18. * 04/06/99 stephen changed setDefault() to realloc and copy
  19. * 06/14/99 stephen Changed calls to ures_open for new params
  20. * 07/21/99 stephen Modified setDefault() to propagate to C++
  21. * 05/14/04 alan 7 years later: refactored, cleaned up, fixed bugs,
  22. * brought canonicalization code into line with spec
  23. *****************************************************************************/
  24. /*
  25. POSIX's locale format, from putil.c: [no spaces]
  26. ll [ _CC ] [ . MM ] [ @ VV]
  27. l = lang, C = ctry, M = charmap, V = variant
  28. */
  29. #include <algorithm>
  30. #include <optional>
  31. #include <string_view>
  32. #include "unicode/bytestream.h"
  33. #include "unicode/errorcode.h"
  34. #include "unicode/stringpiece.h"
  35. #include "unicode/utypes.h"
  36. #include "unicode/ustring.h"
  37. #include "unicode/uloc.h"
  38. #include "bytesinkutil.h"
  39. #include "putilimp.h"
  40. #include "ustr_imp.h"
  41. #include "ulocimp.h"
  42. #include "umutex.h"
  43. #include "cstring.h"
  44. #include "cmemory.h"
  45. #include "locmap.h"
  46. #include "uarrsort.h"
  47. #include "uenumimp.h"
  48. #include "uassert.h"
  49. #include "charstr.h"
  50. U_NAMESPACE_USE
  51. /* ### Declarations **************************************************/
  52. /* Locale stuff from locid.cpp */
  53. U_CFUNC void locale_set_default(const char *id);
  54. U_CFUNC const char *locale_get_default();
  55. namespace {
  56. /* ### Data tables **************************************************/
  57. /**
  58. * Table of language codes, both 2- and 3-letter, with preference
  59. * given to 2-letter codes where possible. Includes 3-letter codes
  60. * that lack a 2-letter equivalent.
  61. *
  62. * This list must be in sorted order. This list is returned directly
  63. * to the user by some API.
  64. *
  65. * This list must be kept in sync with LANGUAGES_3, with corresponding
  66. * entries matched.
  67. *
  68. * This table should be terminated with a nullptr entry, followed by a
  69. * second list, and another nullptr entry. The first list is visible to
  70. * user code when this array is returned by API. The second list
  71. * contains codes we support, but do not expose through user API.
  72. *
  73. * Notes
  74. *
  75. * Tables updated per http://lcweb.loc.gov/standards/iso639-2/ to
  76. * include the revisions up to 2001/7/27 *CWB*
  77. *
  78. * The 3 character codes are the terminology codes like RFC 3066. This
  79. * is compatible with prior ICU codes
  80. *
  81. * "in" "iw" "ji" "jw" & "sh" have been withdrawn but are still in the
  82. * table but now at the end of the table because 3 character codes are
  83. * duplicates. This avoids bad searches going from 3 to 2 character
  84. * codes.
  85. *
  86. * The range qaa-qtz is reserved for local use
  87. */
  88. /* Generated using org.unicode.cldr.icu.GenerateISO639LanguageTables */
  89. /* ISO639 table version is 20150505 */
  90. /* Subsequent hand addition of selected languages */
  91. constexpr const char* LANGUAGES[] = {
  92. "aa", "ab", "ace", "ach", "ada", "ady", "ae", "aeb",
  93. "af", "afh", "agq", "ain", "ak", "akk", "akz", "ale",
  94. "aln", "alt", "am", "an", "ang", "anp", "ar", "arc",
  95. "arn", "aro", "arp", "arq", "ars", "arw", "ary", "arz", "as",
  96. "asa", "ase", "ast", "av", "avk", "awa", "ay", "az",
  97. "ba", "bal", "ban", "bar", "bas", "bax", "bbc", "bbj",
  98. "be", "bej", "bem", "bew", "bez", "bfd", "bfq", "bg",
  99. "bgc", "bgn", "bho", "bi", "bik", "bin", "bjn", "bkm", "bla",
  100. "blo", "bm", "bn", "bo", "bpy", "bqi", "br", "bra", "brh",
  101. "brx", "bs", "bss", "bua", "bug", "bum", "byn", "byv",
  102. "ca", "cad", "car", "cay", "cch", "ccp", "ce", "ceb", "cgg",
  103. "ch", "chb", "chg", "chk", "chm", "chn", "cho", "chp",
  104. "chr", "chy", "ckb", "co", "cop", "cps", "cr", "crh",
  105. "cs", "csb", "csw", "cu", "cv", "cy",
  106. "da", "dak", "dar", "dav", "de", "del", "den", "dgr",
  107. "din", "dje", "doi", "dsb", "dtp", "dua", "dum", "dv",
  108. "dyo", "dyu", "dz", "dzg",
  109. "ebu", "ee", "efi", "egl", "egy", "eka", "el", "elx",
  110. "en", "enm", "eo", "es", "esu", "et", "eu", "ewo",
  111. "ext",
  112. "fa", "fan", "fat", "ff", "fi", "fil", "fit", "fj",
  113. "fo", "fon", "fr", "frc", "frm", "fro", "frp", "frr",
  114. "frs", "fur", "fy",
  115. "ga", "gaa", "gag", "gan", "gay", "gba", "gbz", "gd",
  116. "gez", "gil", "gl", "glk", "gmh", "gn", "goh", "gom",
  117. "gon", "gor", "got", "grb", "grc", "gsw", "gu", "guc",
  118. "gur", "guz", "gv", "gwi",
  119. "ha", "hai", "hak", "haw", "he", "hi", "hif", "hil",
  120. "hit", "hmn", "ho", "hr", "hsb", "hsn", "ht", "hu",
  121. "hup", "hy", "hz",
  122. "ia", "iba", "ibb", "id", "ie", "ig", "ii", "ik",
  123. "ilo", "inh", "io", "is", "it", "iu", "izh",
  124. "ja", "jam", "jbo", "jgo", "jmc", "jpr", "jrb", "jut",
  125. "jv",
  126. "ka", "kaa", "kab", "kac", "kaj", "kam", "kaw", "kbd",
  127. "kbl", "kcg", "kde", "kea", "ken", "kfo", "kg", "kgp",
  128. "kha", "kho", "khq", "khw", "ki", "kiu", "kj", "kk",
  129. "kkj", "kl", "kln", "km", "kmb", "kn", "ko", "koi",
  130. "kok", "kos", "kpe", "kr", "krc", "kri", "krj", "krl",
  131. "kru", "ks", "ksb", "ksf", "ksh", "ku", "kum", "kut",
  132. "kv", "kw", "kxv", "ky",
  133. "la", "lad", "lag", "lah", "lam", "lb", "lez", "lfn",
  134. "lg", "li", "lij", "liv", "lkt", "lmo", "ln", "lo",
  135. "lol", "loz", "lrc", "lt", "ltg", "lu", "lua", "lui",
  136. "lun", "luo", "lus", "luy", "lv", "lzh", "lzz",
  137. "mad", "maf", "mag", "mai", "mak", "man", "mas", "mde",
  138. "mdf", "mdh", "mdr", "men", "mer", "mfe", "mg", "mga",
  139. "mgh", "mgo", "mh", "mi", "mic", "min", "mis", "mk",
  140. "ml", "mn", "mnc", "mni",
  141. "moh", "mos", "mr", "mrj",
  142. "ms", "mt", "mua", "mul", "mus", "mwl", "mwr", "mwv",
  143. "my", "mye", "myv", "mzn",
  144. "na", "nan", "nap", "naq", "nb", "nd", "nds", "ne",
  145. "new", "ng", "nia", "niu", "njo", "nl", "nmg", "nn",
  146. "nnh", "no", "nog", "non", "nov", "nqo", "nr", "nso",
  147. "nus", "nv", "nwc", "ny", "nym", "nyn", "nyo", "nzi",
  148. "oc", "oj", "om", "or", "os", "osa", "ota",
  149. "pa", "pag", "pal", "pam", "pap", "pau", "pcd", "pcm", "pdc",
  150. "pdt", "peo", "pfl", "phn", "pi", "pl", "pms", "pnt",
  151. "pon", "prg", "pro", "ps", "pt",
  152. "qu", "quc", "qug",
  153. "raj", "rap", "rar", "rgn", "rif", "rm", "rn", "ro",
  154. "rof", "rom", "rtm", "ru", "rue", "rug", "rup",
  155. "rw", "rwk",
  156. "sa", "sad", "sah", "sam", "saq", "sas", "sat", "saz",
  157. "sba", "sbp", "sc", "scn", "sco", "sd", "sdc", "sdh",
  158. "se", "see", "seh", "sei", "sel", "ses", "sg", "sga",
  159. "sgs", "shi", "shn", "shu", "si", "sid", "sk",
  160. "sl", "sli", "sly", "sm", "sma", "smj", "smn", "sms",
  161. "sn", "snk", "so", "sog", "sq", "sr", "srn", "srr",
  162. "ss", "ssy", "st", "stq", "su", "suk", "sus", "sux",
  163. "sv", "sw", "swb", "syc", "syr", "szl",
  164. "ta", "tcy", "te", "tem", "teo", "ter", "tet", "tg",
  165. "th", "ti", "tig", "tiv", "tk", "tkl", "tkr",
  166. "tlh", "tli", "tly", "tmh", "tn", "to", "tog", "tok", "tpi",
  167. "tr", "tru", "trv", "ts", "tsd", "tsi", "tt", "ttt",
  168. "tum", "tvl", "tw", "twq", "ty", "tyv", "tzm",
  169. "udm", "ug", "uga", "uk", "umb", "und", "ur", "uz",
  170. "vai", "ve", "vec", "vep", "vi", "vls", "vmf", "vmw",
  171. "vo", "vot", "vro", "vun",
  172. "wa", "wae", "wal", "war", "was", "wbp", "wo", "wuu",
  173. "xal", "xh", "xmf", "xnr", "xog",
  174. "yao", "yap", "yav", "ybb", "yi", "yo", "yrl", "yue",
  175. "za", "zap", "zbl", "zea", "zen", "zgh", "zh", "zu",
  176. "zun", "zxx", "zza",
  177. nullptr,
  178. "in", "iw", "ji", "jw", "mo", "sh", "swc", "tl", /* obsolete language codes */
  179. nullptr
  180. };
  181. constexpr const char* DEPRECATED_LANGUAGES[]={
  182. "in", "iw", "ji", "jw", "mo", nullptr, nullptr
  183. };
  184. constexpr const char* REPLACEMENT_LANGUAGES[]={
  185. "id", "he", "yi", "jv", "ro", nullptr, nullptr
  186. };
  187. /**
  188. * Table of 3-letter language codes.
  189. *
  190. * This is a lookup table used to convert 3-letter language codes to
  191. * their 2-letter equivalent, where possible. It must be kept in sync
  192. * with LANGUAGES. For all valid i, LANGUAGES[i] must refer to the
  193. * same language as LANGUAGES_3[i]. The commented-out lines are
  194. * copied from LANGUAGES to make eyeballing this baby easier.
  195. *
  196. * Where a 3-letter language code has no 2-letter equivalent, the
  197. * 3-letter code occupies both LANGUAGES[i] and LANGUAGES_3[i].
  198. *
  199. * This table should be terminated with a nullptr entry, followed by a
  200. * second list, and another nullptr entry. The two lists correspond to
  201. * the two lists in LANGUAGES.
  202. */
  203. /* Generated using org.unicode.cldr.icu.GenerateISO639LanguageTables */
  204. /* ISO639 table version is 20150505 */
  205. /* Subsequent hand addition of selected languages */
  206. constexpr const char* LANGUAGES_3[] = {
  207. "aar", "abk", "ace", "ach", "ada", "ady", "ave", "aeb",
  208. "afr", "afh", "agq", "ain", "aka", "akk", "akz", "ale",
  209. "aln", "alt", "amh", "arg", "ang", "anp", "ara", "arc",
  210. "arn", "aro", "arp", "arq", "ars", "arw", "ary", "arz", "asm",
  211. "asa", "ase", "ast", "ava", "avk", "awa", "aym", "aze",
  212. "bak", "bal", "ban", "bar", "bas", "bax", "bbc", "bbj",
  213. "bel", "bej", "bem", "bew", "bez", "bfd", "bfq", "bul",
  214. "bgc", "bgn", "bho", "bis", "bik", "bin", "bjn", "bkm", "bla",
  215. "blo", "bam", "ben", "bod", "bpy", "bqi", "bre", "bra", "brh",
  216. "brx", "bos", "bss", "bua", "bug", "bum", "byn", "byv",
  217. "cat", "cad", "car", "cay", "cch", "ccp", "che", "ceb", "cgg",
  218. "cha", "chb", "chg", "chk", "chm", "chn", "cho", "chp",
  219. "chr", "chy", "ckb", "cos", "cop", "cps", "cre", "crh",
  220. "ces", "csb", "csw", "chu", "chv", "cym",
  221. "dan", "dak", "dar", "dav", "deu", "del", "den", "dgr",
  222. "din", "dje", "doi", "dsb", "dtp", "dua", "dum", "div",
  223. "dyo", "dyu", "dzo", "dzg",
  224. "ebu", "ewe", "efi", "egl", "egy", "eka", "ell", "elx",
  225. "eng", "enm", "epo", "spa", "esu", "est", "eus", "ewo",
  226. "ext",
  227. "fas", "fan", "fat", "ful", "fin", "fil", "fit", "fij",
  228. "fao", "fon", "fra", "frc", "frm", "fro", "frp", "frr",
  229. "frs", "fur", "fry",
  230. "gle", "gaa", "gag", "gan", "gay", "gba", "gbz", "gla",
  231. "gez", "gil", "glg", "glk", "gmh", "grn", "goh", "gom",
  232. "gon", "gor", "got", "grb", "grc", "gsw", "guj", "guc",
  233. "gur", "guz", "glv", "gwi",
  234. "hau", "hai", "hak", "haw", "heb", "hin", "hif", "hil",
  235. "hit", "hmn", "hmo", "hrv", "hsb", "hsn", "hat", "hun",
  236. "hup", "hye", "her",
  237. "ina", "iba", "ibb", "ind", "ile", "ibo", "iii", "ipk",
  238. "ilo", "inh", "ido", "isl", "ita", "iku", "izh",
  239. "jpn", "jam", "jbo", "jgo", "jmc", "jpr", "jrb", "jut",
  240. "jav",
  241. "kat", "kaa", "kab", "kac", "kaj", "kam", "kaw", "kbd",
  242. "kbl", "kcg", "kde", "kea", "ken", "kfo", "kon", "kgp",
  243. "kha", "kho", "khq", "khw", "kik", "kiu", "kua", "kaz",
  244. "kkj", "kal", "kln", "khm", "kmb", "kan", "kor", "koi",
  245. "kok", "kos", "kpe", "kau", "krc", "kri", "krj", "krl",
  246. "kru", "kas", "ksb", "ksf", "ksh", "kur", "kum", "kut",
  247. "kom", "cor", "kxv", "kir",
  248. "lat", "lad", "lag", "lah", "lam", "ltz", "lez", "lfn",
  249. "lug", "lim", "lij", "liv", "lkt", "lmo", "lin", "lao",
  250. "lol", "loz", "lrc", "lit", "ltg", "lub", "lua", "lui",
  251. "lun", "luo", "lus", "luy", "lav", "lzh", "lzz",
  252. "mad", "maf", "mag", "mai", "mak", "man", "mas", "mde",
  253. "mdf", "mdh", "mdr", "men", "mer", "mfe", "mlg", "mga",
  254. "mgh", "mgo", "mah", "mri", "mic", "min", "mis", "mkd",
  255. "mal", "mon", "mnc", "mni",
  256. "moh", "mos", "mar", "mrj",
  257. "msa", "mlt", "mua", "mul", "mus", "mwl", "mwr", "mwv",
  258. "mya", "mye", "myv", "mzn",
  259. "nau", "nan", "nap", "naq", "nob", "nde", "nds", "nep",
  260. "new", "ndo", "nia", "niu", "njo", "nld", "nmg", "nno",
  261. "nnh", "nor", "nog", "non", "nov", "nqo", "nbl", "nso",
  262. "nus", "nav", "nwc", "nya", "nym", "nyn", "nyo", "nzi",
  263. "oci", "oji", "orm", "ori", "oss", "osa", "ota",
  264. "pan", "pag", "pal", "pam", "pap", "pau", "pcd", "pcm", "pdc",
  265. "pdt", "peo", "pfl", "phn", "pli", "pol", "pms", "pnt",
  266. "pon", "prg", "pro", "pus", "por",
  267. "que", "quc", "qug",
  268. "raj", "rap", "rar", "rgn", "rif", "roh", "run", "ron",
  269. "rof", "rom", "rtm", "rus", "rue", "rug", "rup",
  270. "kin", "rwk",
  271. "san", "sad", "sah", "sam", "saq", "sas", "sat", "saz",
  272. "sba", "sbp", "srd", "scn", "sco", "snd", "sdc", "sdh",
  273. "sme", "see", "seh", "sei", "sel", "ses", "sag", "sga",
  274. "sgs", "shi", "shn", "shu", "sin", "sid", "slk",
  275. "slv", "sli", "sly", "smo", "sma", "smj", "smn", "sms",
  276. "sna", "snk", "som", "sog", "sqi", "srp", "srn", "srr",
  277. "ssw", "ssy", "sot", "stq", "sun", "suk", "sus", "sux",
  278. "swe", "swa", "swb", "syc", "syr", "szl",
  279. "tam", "tcy", "tel", "tem", "teo", "ter", "tet", "tgk",
  280. "tha", "tir", "tig", "tiv", "tuk", "tkl", "tkr",
  281. "tlh", "tli", "tly", "tmh", "tsn", "ton", "tog", "tok", "tpi",
  282. "tur", "tru", "trv", "tso", "tsd", "tsi", "tat", "ttt",
  283. "tum", "tvl", "twi", "twq", "tah", "tyv", "tzm",
  284. "udm", "uig", "uga", "ukr", "umb", "und", "urd", "uzb",
  285. "vai", "ven", "vec", "vep", "vie", "vls", "vmf", "vmw",
  286. "vol", "vot", "vro", "vun",
  287. "wln", "wae", "wal", "war", "was", "wbp", "wol", "wuu",
  288. "xal", "xho", "xmf", "xnr", "xog",
  289. "yao", "yap", "yav", "ybb", "yid", "yor", "yrl", "yue",
  290. "zha", "zap", "zbl", "zea", "zen", "zgh", "zho", "zul",
  291. "zun", "zxx", "zza",
  292. nullptr,
  293. /* "in", "iw", "ji", "jw", "mo", "sh", "swc", "tl", */
  294. "ind", "heb", "yid", "jaw", "mol", "srp", "swc", "tgl",
  295. nullptr
  296. };
  297. /**
  298. * Table of 2-letter country codes.
  299. *
  300. * This list must be in sorted order. This list is returned directly
  301. * to the user by some API.
  302. *
  303. * This list must be kept in sync with COUNTRIES_3, with corresponding
  304. * entries matched.
  305. *
  306. * This table should be terminated with a nullptr entry, followed by a
  307. * second list, and another nullptr entry. The first list is visible to
  308. * user code when this array is returned by API. The second list
  309. * contains codes we support, but do not expose through user API.
  310. *
  311. * Notes:
  312. *
  313. * ZR(ZAR) is now CD(COD) and FX(FXX) is PS(PSE) as per
  314. * http://www.evertype.com/standards/iso3166/iso3166-1-en.html added
  315. * new codes keeping the old ones for compatibility updated to include
  316. * 1999/12/03 revisions *CWB*
  317. *
  318. * RO(ROM) is now RO(ROU) according to
  319. * http://www.iso.org/iso/en/prods-services/iso3166ma/03updates-on-iso-3166/nlv3e-rou.html
  320. */
  321. constexpr const char* COUNTRIES[] = {
  322. "AD", "AE", "AF", "AG", "AI", "AL", "AM",
  323. "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ",
  324. "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI",
  325. "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV",
  326. "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG",
  327. "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CQ", "CR",
  328. "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DG", "DJ", "DK",
  329. "DM", "DO", "DZ", "EA", "EC", "EE", "EG", "EH", "ER",
  330. "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR",
  331. "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL",
  332. "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU",
  333. "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU",
  334. "IC", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS",
  335. "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI",
  336. "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA",
  337. "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU",
  338. "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK",
  339. "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS",
  340. "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA",
  341. "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP",
  342. "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG",
  343. "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT",
  344. "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA",
  345. "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ",
  346. "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV",
  347. "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ",
  348. "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV",
  349. "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ",
  350. "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF",
  351. "WS", "XK", "YE", "YT", "ZA", "ZM", "ZW",
  352. nullptr,
  353. "AN", "BU", "CS", "FX", "RO", "SU", "TP", "YD", "YU", "ZR", /* obsolete country codes */
  354. nullptr
  355. };
  356. constexpr const char* DEPRECATED_COUNTRIES[] = {
  357. "AN", "BU", "CS", "DD", "DY", "FX", "HV", "NH", "RH", "SU", "TP", "UK", "VD", "YD", "YU", "ZR", nullptr, nullptr /* deprecated country list */
  358. };
  359. constexpr const char* REPLACEMENT_COUNTRIES[] = {
  360. /* "AN", "BU", "CS", "DD", "DY", "FX", "HV", "NH", "RH", "SU", "TP", "UK", "VD", "YD", "YU", "ZR" */
  361. "CW", "MM", "RS", "DE", "BJ", "FR", "BF", "VU", "ZW", "RU", "TL", "GB", "VN", "YE", "RS", "CD", nullptr, nullptr /* replacement country codes */
  362. };
  363. /**
  364. * Table of 3-letter country codes.
  365. *
  366. * This is a lookup table used to convert 3-letter country codes to
  367. * their 2-letter equivalent. It must be kept in sync with COUNTRIES.
  368. * For all valid i, COUNTRIES[i] must refer to the same country as
  369. * COUNTRIES_3[i]. The commented-out lines are copied from COUNTRIES
  370. * to make eyeballing this baby easier.
  371. *
  372. * This table should be terminated with a nullptr entry, followed by a
  373. * second list, and another nullptr entry. The two lists correspond to
  374. * the two lists in COUNTRIES.
  375. */
  376. constexpr const char* COUNTRIES_3[] = {
  377. /* "AD", "AE", "AF", "AG", "AI", "AL", "AM", */
  378. "AND", "ARE", "AFG", "ATG", "AIA", "ALB", "ARM",
  379. /* "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", */
  380. "AGO", "ATA", "ARG", "ASM", "AUT", "AUS", "ABW", "ALA", "AZE",
  381. /* "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", */
  382. "BIH", "BRB", "BGD", "BEL", "BFA", "BGR", "BHR", "BDI",
  383. /* "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", */
  384. "BEN", "BLM", "BMU", "BRN", "BOL", "BES", "BRA", "BHS", "BTN", "BVT",
  385. /* "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", */
  386. "BWA", "BLR", "BLZ", "CAN", "CCK", "COD", "CAF", "COG",
  387. /* "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CQ", "CR", */
  388. "CHE", "CIV", "COK", "CHL", "CMR", "CHN", "COL", "CRQ", "CRI",
  389. /* "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DG", "DJ", "DK", */
  390. "CUB", "CPV", "CUW", "CXR", "CYP", "CZE", "DEU", "DGA", "DJI", "DNK",
  391. /* "DM", "DO", "DZ", "EA", "EC", "EE", "EG", "EH", "ER", */
  392. "DMA", "DOM", "DZA", "XEA", "ECU", "EST", "EGY", "ESH", "ERI",
  393. /* "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", */
  394. "ESP", "ETH", "FIN", "FJI", "FLK", "FSM", "FRO", "FRA",
  395. /* "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", */
  396. "GAB", "GBR", "GRD", "GEO", "GUF", "GGY", "GHA", "GIB", "GRL",
  397. /* "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", */
  398. "GMB", "GIN", "GLP", "GNQ", "GRC", "SGS", "GTM", "GUM",
  399. /* "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", */
  400. "GNB", "GUY", "HKG", "HMD", "HND", "HRV", "HTI", "HUN",
  401. /* "IC", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS" */
  402. "XIC", "IDN", "IRL", "ISR", "IMN", "IND", "IOT", "IRQ", "IRN", "ISL",
  403. /* "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", */
  404. "ITA", "JEY", "JAM", "JOR", "JPN", "KEN", "KGZ", "KHM", "KIR",
  405. /* "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", */
  406. "COM", "KNA", "PRK", "KOR", "KWT", "CYM", "KAZ", "LAO",
  407. /* "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", */
  408. "LBN", "LCA", "LIE", "LKA", "LBR", "LSO", "LTU", "LUX",
  409. /* "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", */
  410. "LVA", "LBY", "MAR", "MCO", "MDA", "MNE", "MAF", "MDG", "MHL", "MKD",
  411. /* "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", */
  412. "MLI", "MMR", "MNG", "MAC", "MNP", "MTQ", "MRT", "MSR",
  413. /* "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", */
  414. "MLT", "MUS", "MDV", "MWI", "MEX", "MYS", "MOZ", "NAM",
  415. /* "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", */
  416. "NCL", "NER", "NFK", "NGA", "NIC", "NLD", "NOR", "NPL",
  417. /* "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", */
  418. "NRU", "NIU", "NZL", "OMN", "PAN", "PER", "PYF", "PNG",
  419. /* "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", */
  420. "PHL", "PAK", "POL", "SPM", "PCN", "PRI", "PSE", "PRT",
  421. /* "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", */
  422. "PLW", "PRY", "QAT", "REU", "ROU", "SRB", "RUS", "RWA", "SAU",
  423. /* "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", */
  424. "SLB", "SYC", "SDN", "SWE", "SGP", "SHN", "SVN", "SJM",
  425. /* "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", */
  426. "SVK", "SLE", "SMR", "SEN", "SOM", "SUR", "SSD", "STP", "SLV",
  427. /* "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", */
  428. "SXM", "SYR", "SWZ", "TCA", "TCD", "ATF", "TGO", "THA", "TJK",
  429. /* "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", */
  430. "TKL", "TLS", "TKM", "TUN", "TON", "TUR", "TTO", "TUV",
  431. /* "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", */
  432. "TWN", "TZA", "UKR", "UGA", "UMI", "USA", "URY", "UZB",
  433. /* "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", */
  434. "VAT", "VCT", "VEN", "VGB", "VIR", "VNM", "VUT", "WLF",
  435. /* "WS", "XK", "YE", "YT", "ZA", "ZM", "ZW", */
  436. "WSM", "XKK", "YEM", "MYT", "ZAF", "ZMB", "ZWE",
  437. nullptr,
  438. /* "AN", "BU", "CS", "FX", "RO", "SU", "TP", "YD", "YU", "ZR" */
  439. "ANT", "BUR", "SCG", "FXX", "ROM", "SUN", "TMP", "YMD", "YUG", "ZAR",
  440. nullptr
  441. };
  442. typedef struct CanonicalizationMap {
  443. const char *id; /* input ID */
  444. const char *canonicalID; /* canonicalized output ID */
  445. } CanonicalizationMap;
  446. /**
  447. * A map to canonicalize locale IDs. This handles a variety of
  448. * different semantic kinds of transformations.
  449. */
  450. constexpr CanonicalizationMap CANONICALIZE_MAP[] = {
  451. { "art__LOJBAN", "jbo" }, /* registered name */
  452. { "hy__AREVELA", "hy" }, /* Registered IANA variant */
  453. { "hy__AREVMDA", "hyw" }, /* Registered IANA variant */
  454. { "zh__GUOYU", "zh" }, /* registered name */
  455. { "zh__HAKKA", "hak" }, /* registered name */
  456. { "zh__XIANG", "hsn" }, /* registered name */
  457. // subtags with 3 chars won't be treated as variants.
  458. { "zh_GAN", "gan" }, /* registered name */
  459. { "zh_MIN_NAN", "nan" }, /* registered name */
  460. { "zh_WUU", "wuu" }, /* registered name */
  461. { "zh_YUE", "yue" }, /* registered name */
  462. };
  463. /* ### BCP47 Conversion *******************************************/
  464. /* Gets the size of the shortest subtag in the given localeID. */
  465. int32_t getShortestSubtagLength(const char *localeID) {
  466. int32_t localeIDLength = static_cast<int32_t>(uprv_strlen(localeID));
  467. int32_t length = localeIDLength;
  468. int32_t tmpLength = 0;
  469. int32_t i;
  470. bool reset = true;
  471. for (i = 0; i < localeIDLength; i++) {
  472. if (localeID[i] != '_' && localeID[i] != '-') {
  473. if (reset) {
  474. tmpLength = 0;
  475. reset = false;
  476. }
  477. tmpLength++;
  478. } else {
  479. if (tmpLength != 0 && tmpLength < length) {
  480. length = tmpLength;
  481. }
  482. reset = true;
  483. }
  484. }
  485. return length;
  486. }
  487. /* Test if the locale id has BCP47 u extension and does not have '@' */
  488. inline bool _hasBCP47Extension(const char *id) {
  489. return id != nullptr && uprv_strstr(id, "@") == nullptr && getShortestSubtagLength(id) == 1;
  490. }
  491. /* ### Keywords **************************************************/
  492. inline bool UPRV_ISDIGIT(char c) { return c >= '0' && c <= '9'; }
  493. inline bool UPRV_ISALPHANUM(char c) { return uprv_isASCIILetter(c) || UPRV_ISDIGIT(c); }
  494. /* Punctuation/symbols allowed in legacy key values */
  495. inline bool UPRV_OK_VALUE_PUNCTUATION(char c) { return c == '_' || c == '-' || c == '+' || c == '/'; }
  496. } // namespace
  497. #define ULOC_KEYWORD_BUFFER_LEN 25
  498. #define ULOC_MAX_NO_KEYWORDS 25
  499. U_CAPI const char * U_EXPORT2
  500. locale_getKeywordsStart(const char *localeID) {
  501. const char *result = nullptr;
  502. if((result = uprv_strchr(localeID, '@')) != nullptr) {
  503. return result;
  504. }
  505. #if (U_CHARSET_FAMILY == U_EBCDIC_FAMILY)
  506. else {
  507. /* We do this because the @ sign is variant, and the @ sign used on one
  508. EBCDIC machine won't be compiled the same way on other EBCDIC based
  509. machines. */
  510. static const uint8_t ebcdicSigns[] = { 0x7C, 0x44, 0x66, 0x80, 0xAC, 0xAE, 0xAF, 0xB5, 0xEC, 0xEF, 0x00 };
  511. const uint8_t *charToFind = ebcdicSigns;
  512. while(*charToFind) {
  513. if((result = uprv_strchr(localeID, *charToFind)) != nullptr) {
  514. return result;
  515. }
  516. charToFind++;
  517. }
  518. }
  519. #endif
  520. return nullptr;
  521. }
  522. namespace {
  523. /**
  524. * @param keywordName incoming name to be canonicalized
  525. * @param status return status (keyword too long)
  526. * @return the keyword name
  527. */
  528. CharString locale_canonKeywordName(std::string_view keywordName, UErrorCode& status)
  529. {
  530. if (U_FAILURE(status)) { return {}; }
  531. CharString result;
  532. for (char c : keywordName) {
  533. if (!UPRV_ISALPHANUM(c)) {
  534. status = U_ILLEGAL_ARGUMENT_ERROR; /* malformed keyword name */
  535. return {};
  536. }
  537. result.append(uprv_tolower(c), status);
  538. }
  539. if (result.isEmpty()) {
  540. status = U_ILLEGAL_ARGUMENT_ERROR; /* empty keyword name */
  541. return {};
  542. }
  543. return result;
  544. }
  545. typedef struct {
  546. char keyword[ULOC_KEYWORD_BUFFER_LEN];
  547. int32_t keywordLen;
  548. const char *valueStart;
  549. int32_t valueLen;
  550. } KeywordStruct;
  551. int32_t U_CALLCONV
  552. compareKeywordStructs(const void * /*context*/, const void *left, const void *right) {
  553. const char* leftString = static_cast<const KeywordStruct*>(left)->keyword;
  554. const char* rightString = static_cast<const KeywordStruct*>(right)->keyword;
  555. return uprv_strcmp(leftString, rightString);
  556. }
  557. } // namespace
  558. U_EXPORT CharString
  559. ulocimp_getKeywords(const char* localeID,
  560. char prev,
  561. bool valuesToo,
  562. UErrorCode& status)
  563. {
  564. return ByteSinkUtil::viaByteSinkToCharString(
  565. [&](ByteSink& sink, UErrorCode& status) {
  566. ulocimp_getKeywords(localeID,
  567. prev,
  568. sink,
  569. valuesToo,
  570. status);
  571. },
  572. status);
  573. }
  574. U_EXPORT void
  575. ulocimp_getKeywords(const char* localeID,
  576. char prev,
  577. ByteSink& sink,
  578. bool valuesToo,
  579. UErrorCode& status)
  580. {
  581. if (U_FAILURE(status)) { return; }
  582. KeywordStruct keywordList[ULOC_MAX_NO_KEYWORDS];
  583. int32_t maxKeywords = ULOC_MAX_NO_KEYWORDS;
  584. int32_t numKeywords = 0;
  585. const char* pos = localeID;
  586. const char* equalSign = nullptr;
  587. const char* semicolon = nullptr;
  588. int32_t i = 0, j, n;
  589. if(prev == '@') { /* start of keyword definition */
  590. /* we will grab pairs, trim spaces, lowercase keywords, sort and return */
  591. do {
  592. bool duplicate = false;
  593. /* skip leading spaces */
  594. while(*pos == ' ') {
  595. pos++;
  596. }
  597. if (!*pos) { /* handle trailing "; " */
  598. break;
  599. }
  600. if(numKeywords == maxKeywords) {
  601. status = U_INTERNAL_PROGRAM_ERROR;
  602. return;
  603. }
  604. equalSign = uprv_strchr(pos, '=');
  605. semicolon = uprv_strchr(pos, ';');
  606. /* lack of '=' [foo@currency] is illegal */
  607. /* ';' before '=' [foo@currency;collation=pinyin] is illegal */
  608. if(!equalSign || (semicolon && semicolon<equalSign)) {
  609. status = U_INVALID_FORMAT_ERROR;
  610. return;
  611. }
  612. /* need to normalize both keyword and keyword name */
  613. if(equalSign - pos >= ULOC_KEYWORD_BUFFER_LEN) {
  614. /* keyword name too long for internal buffer */
  615. status = U_INTERNAL_PROGRAM_ERROR;
  616. return;
  617. }
  618. for(i = 0, n = 0; i < equalSign - pos; ++i) {
  619. if (pos[i] != ' ') {
  620. keywordList[numKeywords].keyword[n++] = uprv_tolower(pos[i]);
  621. }
  622. }
  623. /* zero-length keyword is an error. */
  624. if (n == 0) {
  625. status = U_INVALID_FORMAT_ERROR;
  626. return;
  627. }
  628. keywordList[numKeywords].keyword[n] = 0;
  629. keywordList[numKeywords].keywordLen = n;
  630. /* now grab the value part. First we skip the '=' */
  631. equalSign++;
  632. /* then we leading spaces */
  633. while(*equalSign == ' ') {
  634. equalSign++;
  635. }
  636. /* Premature end or zero-length value */
  637. if (!*equalSign || equalSign == semicolon) {
  638. status = U_INVALID_FORMAT_ERROR;
  639. return;
  640. }
  641. keywordList[numKeywords].valueStart = equalSign;
  642. pos = semicolon;
  643. i = 0;
  644. if(pos) {
  645. while(*(pos - i - 1) == ' ') {
  646. i++;
  647. }
  648. keywordList[numKeywords].valueLen = static_cast<int32_t>(pos - equalSign - i);
  649. pos++;
  650. } else {
  651. i = static_cast<int32_t>(uprv_strlen(equalSign));
  652. while(i && equalSign[i-1] == ' ') {
  653. i--;
  654. }
  655. keywordList[numKeywords].valueLen = i;
  656. }
  657. /* If this is a duplicate keyword, then ignore it */
  658. for (j=0; j<numKeywords; ++j) {
  659. if (uprv_strcmp(keywordList[j].keyword, keywordList[numKeywords].keyword) == 0) {
  660. duplicate = true;
  661. break;
  662. }
  663. }
  664. if (!duplicate) {
  665. ++numKeywords;
  666. }
  667. } while(pos);
  668. /* now we have a list of keywords */
  669. /* we need to sort it */
  670. uprv_sortArray(keywordList, numKeywords, sizeof(KeywordStruct), compareKeywordStructs, nullptr, false, &status);
  671. /* Now construct the keyword part */
  672. for(i = 0; i < numKeywords; i++) {
  673. sink.Append(keywordList[i].keyword, keywordList[i].keywordLen);
  674. if(valuesToo) {
  675. sink.Append("=", 1);
  676. sink.Append(keywordList[i].valueStart, keywordList[i].valueLen);
  677. if(i < numKeywords - 1) {
  678. sink.Append(";", 1);
  679. }
  680. } else {
  681. sink.Append("\0", 1);
  682. }
  683. }
  684. }
  685. }
  686. U_CAPI int32_t U_EXPORT2
  687. uloc_getKeywordValue(const char* localeID,
  688. const char* keywordName,
  689. char* buffer, int32_t bufferCapacity,
  690. UErrorCode* status)
  691. {
  692. if (U_FAILURE(*status)) { return 0; }
  693. if (keywordName == nullptr || *keywordName == '\0') {
  694. *status = U_ILLEGAL_ARGUMENT_ERROR;
  695. return 0;
  696. }
  697. return ByteSinkUtil::viaByteSinkToTerminatedChars(
  698. buffer, bufferCapacity,
  699. [&](ByteSink& sink, UErrorCode& status) {
  700. ulocimp_getKeywordValue(localeID, keywordName, sink, status);
  701. },
  702. *status);
  703. }
  704. U_EXPORT CharString
  705. ulocimp_getKeywordValue(const char* localeID,
  706. std::string_view keywordName,
  707. UErrorCode& status)
  708. {
  709. return ByteSinkUtil::viaByteSinkToCharString(
  710. [&](ByteSink& sink, UErrorCode& status) {
  711. ulocimp_getKeywordValue(localeID, keywordName, sink, status);
  712. },
  713. status);
  714. }
  715. U_EXPORT void
  716. ulocimp_getKeywordValue(const char* localeID,
  717. std::string_view keywordName,
  718. icu::ByteSink& sink,
  719. UErrorCode& status)
  720. {
  721. if (U_FAILURE(status)) { return; }
  722. if (localeID == nullptr || keywordName.empty()) {
  723. status = U_ILLEGAL_ARGUMENT_ERROR;
  724. return;
  725. }
  726. const char* startSearchHere = nullptr;
  727. const char* nextSeparator = nullptr;
  728. CharString tempBuffer;
  729. const char* tmpLocaleID;
  730. CharString canonKeywordName = locale_canonKeywordName(keywordName, status);
  731. if (U_FAILURE(status)) {
  732. return;
  733. }
  734. if (_hasBCP47Extension(localeID)) {
  735. tempBuffer = ulocimp_forLanguageTag(localeID, -1, nullptr, status);
  736. tmpLocaleID = U_SUCCESS(status) && !tempBuffer.isEmpty() ? tempBuffer.data() : localeID;
  737. } else {
  738. tmpLocaleID=localeID;
  739. }
  740. startSearchHere = locale_getKeywordsStart(tmpLocaleID);
  741. if(startSearchHere == nullptr) {
  742. /* no keywords, return at once */
  743. return;
  744. }
  745. /* find the first keyword */
  746. while(startSearchHere) {
  747. const char* keyValueTail;
  748. startSearchHere++; /* skip @ or ; */
  749. nextSeparator = uprv_strchr(startSearchHere, '=');
  750. if(!nextSeparator) {
  751. status = U_ILLEGAL_ARGUMENT_ERROR; /* key must have =value */
  752. return;
  753. }
  754. /* strip leading & trailing spaces (TC decided to tolerate these) */
  755. while(*startSearchHere == ' ') {
  756. startSearchHere++;
  757. }
  758. keyValueTail = nextSeparator;
  759. while (keyValueTail > startSearchHere && *(keyValueTail-1) == ' ') {
  760. keyValueTail--;
  761. }
  762. /* now keyValueTail points to first char after the keyName */
  763. /* copy & normalize keyName from locale */
  764. if (startSearchHere == keyValueTail) {
  765. status = U_ILLEGAL_ARGUMENT_ERROR; /* empty keyword name in passed-in locale */
  766. return;
  767. }
  768. CharString localeKeywordName;
  769. while (startSearchHere < keyValueTail) {
  770. if (!UPRV_ISALPHANUM(*startSearchHere)) {
  771. status = U_ILLEGAL_ARGUMENT_ERROR; /* malformed keyword name */
  772. return;
  773. }
  774. localeKeywordName.append(uprv_tolower(*startSearchHere++), status);
  775. }
  776. if (U_FAILURE(status)) {
  777. return;
  778. }
  779. startSearchHere = uprv_strchr(nextSeparator, ';');
  780. if (canonKeywordName == localeKeywordName) {
  781. /* current entry matches the keyword. */
  782. nextSeparator++; /* skip '=' */
  783. /* First strip leading & trailing spaces (TC decided to tolerate these) */
  784. while(*nextSeparator == ' ') {
  785. nextSeparator++;
  786. }
  787. keyValueTail = (startSearchHere)? startSearchHere: nextSeparator + uprv_strlen(nextSeparator);
  788. while(keyValueTail > nextSeparator && *(keyValueTail-1) == ' ') {
  789. keyValueTail--;
  790. }
  791. /* Now copy the value, but check well-formedness */
  792. if (nextSeparator == keyValueTail) {
  793. status = U_ILLEGAL_ARGUMENT_ERROR; /* empty key value name in passed-in locale */
  794. return;
  795. }
  796. while (nextSeparator < keyValueTail) {
  797. if (!UPRV_ISALPHANUM(*nextSeparator) && !UPRV_OK_VALUE_PUNCTUATION(*nextSeparator)) {
  798. status = U_ILLEGAL_ARGUMENT_ERROR; /* malformed key value */
  799. return;
  800. }
  801. /* Should we lowercase value to return here? Tests expect as-is. */
  802. sink.Append(nextSeparator++, 1);
  803. }
  804. return;
  805. }
  806. }
  807. }
  808. U_CAPI int32_t U_EXPORT2
  809. uloc_setKeywordValue(const char* keywordName,
  810. const char* keywordValue,
  811. char* buffer, int32_t bufferCapacity,
  812. UErrorCode* status)
  813. {
  814. if (U_FAILURE(*status)) { return 0; }
  815. if (keywordName == nullptr || *keywordName == 0) {
  816. *status = U_ILLEGAL_ARGUMENT_ERROR;
  817. return 0;
  818. }
  819. if (bufferCapacity <= 1) {
  820. *status = U_ILLEGAL_ARGUMENT_ERROR;
  821. return 0;
  822. }
  823. int32_t bufLen = (int32_t)uprv_strlen(buffer);
  824. if(bufferCapacity<bufLen) {
  825. /* The capacity is less than the length?! Is this NUL terminated? */
  826. *status = U_ILLEGAL_ARGUMENT_ERROR;
  827. return 0;
  828. }
  829. char* keywords = const_cast<char*>(locale_getKeywordsStart(buffer));
  830. int32_t baseLen = keywords == nullptr ? bufLen : keywords - buffer;
  831. // Remove -1 from the capacity so that this function can guarantee NUL termination.
  832. CheckedArrayByteSink sink(keywords == nullptr ? buffer + bufLen : keywords,
  833. bufferCapacity - baseLen - 1);
  834. int32_t reslen = ulocimp_setKeywordValue(
  835. keywords == nullptr ? std::string_view() : keywords,
  836. keywordName,
  837. keywordValue == nullptr ? std::string_view() : keywordValue,
  838. sink,
  839. *status);
  840. if (U_FAILURE(*status)) {
  841. return *status == U_BUFFER_OVERFLOW_ERROR ? reslen + baseLen : 0;
  842. }
  843. // See the documentation for this function, it's guaranteed to never
  844. // overflow the buffer but instead abort with BUFFER_OVERFLOW_ERROR.
  845. // In this case, nothing has been written to the sink, so it cannot have Overflowed().
  846. U_ASSERT(!sink.Overflowed());
  847. U_ASSERT(reslen >= 0);
  848. return u_terminateChars(buffer, bufferCapacity, reslen + baseLen, status);
  849. }
  850. U_EXPORT void
  851. ulocimp_setKeywordValue(std::string_view keywordName,
  852. std::string_view keywordValue,
  853. CharString& localeID,
  854. UErrorCode& status)
  855. {
  856. if (U_FAILURE(status)) { return; }
  857. std::string_view keywords;
  858. if (const char* start = locale_getKeywordsStart(localeID.data()); start != nullptr) {
  859. // This is safe because CharString::truncate() doesn't actually erase any
  860. // data, but simply sets the position for where new data will be written.
  861. int32_t size = start - localeID.data();
  862. keywords = localeID.toStringPiece();
  863. keywords.remove_prefix(size);
  864. localeID.truncate(size);
  865. }
  866. CharStringByteSink sink(&localeID);
  867. ulocimp_setKeywordValue(keywords, keywordName, keywordValue, sink, status);
  868. }
  869. U_EXPORT int32_t
  870. ulocimp_setKeywordValue(std::string_view keywords,
  871. std::string_view keywordName,
  872. std::string_view keywordValue,
  873. ByteSink& sink,
  874. UErrorCode& status)
  875. {
  876. if (U_FAILURE(status)) { return 0; }
  877. /* TODO: sorting. removal. */
  878. int32_t needLen = 0;
  879. int32_t rc;
  880. CharString updatedKeysAndValues;
  881. bool handledInputKeyAndValue = false;
  882. char keyValuePrefix = '@';
  883. if (status == U_STRING_NOT_TERMINATED_WARNING) {
  884. status = U_ZERO_ERROR;
  885. }
  886. if (keywordName.empty()) {
  887. status = U_ILLEGAL_ARGUMENT_ERROR;
  888. return 0;
  889. }
  890. CharString canonKeywordName = locale_canonKeywordName(keywordName, status);
  891. if (U_FAILURE(status)) {
  892. return 0;
  893. }
  894. CharString canonKeywordValue;
  895. for (char c : keywordValue) {
  896. if (!UPRV_ISALPHANUM(c) && !UPRV_OK_VALUE_PUNCTUATION(c)) {
  897. status = U_ILLEGAL_ARGUMENT_ERROR; /* malformed key value */
  898. return 0;
  899. }
  900. /* Should we force lowercase in value to set? */
  901. canonKeywordValue.append(c, status);
  902. }
  903. if (U_FAILURE(status)) {
  904. return 0;
  905. }
  906. if (keywords.size() <= 1) {
  907. if (canonKeywordValue.isEmpty()) { /* no keywords = nothing to remove */
  908. U_ASSERT(status != U_STRING_NOT_TERMINATED_WARNING);
  909. return 0;
  910. }
  911. needLen = 1 + canonKeywordName.length() + 1 + canonKeywordValue.length();
  912. int32_t capacity = 0;
  913. char* buffer = sink.GetAppendBuffer(
  914. needLen, needLen, nullptr, needLen, &capacity);
  915. if (capacity < needLen || buffer == nullptr) {
  916. status = U_BUFFER_OVERFLOW_ERROR;
  917. return needLen; /* no change */
  918. }
  919. char* it = buffer;
  920. *it++ = '@';
  921. uprv_memcpy(it, canonKeywordName.data(), canonKeywordName.length());
  922. it += canonKeywordName.length();
  923. *it++ = '=';
  924. uprv_memcpy(it, canonKeywordValue.data(), canonKeywordValue.length());
  925. sink.Append(buffer, needLen);
  926. U_ASSERT(status != U_STRING_NOT_TERMINATED_WARNING);
  927. return needLen;
  928. } /* end shortcut - no @ */
  929. /* search for keyword */
  930. for (size_t keywordStart = 0; keywordStart != std::string_view::npos;) {
  931. keywordStart++; /* skip @ or ; */
  932. size_t nextEqualsign = keywords.find('=', keywordStart);
  933. if (nextEqualsign == std::string_view::npos) {
  934. status = U_ILLEGAL_ARGUMENT_ERROR; /* key must have =value */
  935. return 0;
  936. }
  937. /* strip leading & trailing spaces (TC decided to tolerate these) */
  938. while (keywordStart < keywords.size() && keywords[keywordStart] == ' ') {
  939. keywordStart++;
  940. }
  941. size_t keyValueTail = nextEqualsign;
  942. while (keyValueTail > keywordStart && keywords[keyValueTail - 1] == ' ') {
  943. keyValueTail--;
  944. }
  945. /* now keyValueTail points to first char after the keyName */
  946. /* copy & normalize keyName from locale */
  947. if (keywordStart == keyValueTail) {
  948. status = U_ILLEGAL_ARGUMENT_ERROR; /* empty keyword name in passed-in locale */
  949. return 0;
  950. }
  951. CharString localeKeywordName;
  952. while (keywordStart < keyValueTail) {
  953. if (!UPRV_ISALPHANUM(keywords[keywordStart])) {
  954. status = U_ILLEGAL_ARGUMENT_ERROR; /* malformed keyword name */
  955. return 0;
  956. }
  957. localeKeywordName.append(uprv_tolower(keywords[keywordStart++]), status);
  958. }
  959. if (U_FAILURE(status)) {
  960. return 0;
  961. }
  962. size_t nextSeparator = keywords.find(';', nextEqualsign);
  963. /* start processing the value part */
  964. nextEqualsign++; /* skip '=' */
  965. /* First strip leading & trailing spaces (TC decided to tolerate these) */
  966. while (nextEqualsign < keywords.size() && keywords[nextEqualsign] == ' ') {
  967. nextEqualsign++;
  968. }
  969. keyValueTail = nextSeparator == std::string_view::npos ? keywords.size() : nextSeparator;
  970. while (keyValueTail > nextEqualsign && keywords[keyValueTail - 1] == ' ') {
  971. keyValueTail--;
  972. }
  973. if (nextEqualsign == keyValueTail) {
  974. status = U_ILLEGAL_ARGUMENT_ERROR; /* empty key value in passed-in locale */
  975. return 0;
  976. }
  977. rc = uprv_strcmp(canonKeywordName.data(), localeKeywordName.data());
  978. if(rc == 0) {
  979. /* Current entry matches the input keyword. Update the entry */
  980. if (!canonKeywordValue.isEmpty()) { /* updating a value */
  981. updatedKeysAndValues.append(keyValuePrefix, status);
  982. keyValuePrefix = ';'; /* for any subsequent key-value pair */
  983. updatedKeysAndValues.append(canonKeywordName, status);
  984. updatedKeysAndValues.append('=', status);
  985. updatedKeysAndValues.append(canonKeywordValue, status);
  986. } /* else removing this entry, don't emit anything */
  987. handledInputKeyAndValue = true;
  988. } else {
  989. /* input keyword sorts earlier than current entry, add before current entry */
  990. if (rc < 0 && !canonKeywordValue.isEmpty() && !handledInputKeyAndValue) {
  991. /* insert new entry at this location */
  992. updatedKeysAndValues.append(keyValuePrefix, status);
  993. keyValuePrefix = ';'; /* for any subsequent key-value pair */
  994. updatedKeysAndValues.append(canonKeywordName, status);
  995. updatedKeysAndValues.append('=', status);
  996. updatedKeysAndValues.append(canonKeywordValue, status);
  997. handledInputKeyAndValue = true;
  998. }
  999. /* copy the current entry */
  1000. updatedKeysAndValues.append(keyValuePrefix, status);
  1001. keyValuePrefix = ';'; /* for any subsequent key-value pair */
  1002. updatedKeysAndValues.append(localeKeywordName, status);
  1003. updatedKeysAndValues.append('=', status);
  1004. updatedKeysAndValues.append(keywords.data() + nextEqualsign,
  1005. static_cast<int32_t>(keyValueTail - nextEqualsign), status);
  1006. }
  1007. if (nextSeparator == std::string_view::npos && !canonKeywordValue.isEmpty() && !handledInputKeyAndValue) {
  1008. /* append new entry at the end, it sorts later than existing entries */
  1009. updatedKeysAndValues.append(keyValuePrefix, status);
  1010. /* skip keyValuePrefix update, no subsequent key-value pair */
  1011. updatedKeysAndValues.append(canonKeywordName, status);
  1012. updatedKeysAndValues.append('=', status);
  1013. updatedKeysAndValues.append(canonKeywordValue, status);
  1014. handledInputKeyAndValue = true;
  1015. }
  1016. keywordStart = nextSeparator;
  1017. } /* end loop searching */
  1018. /* Any error from updatedKeysAndValues.append above would be internal and not due to
  1019. * problems with the passed-in locale. So if we did encounter problems with the
  1020. * passed-in locale above, those errors took precedence and overrode any error
  1021. * status from updatedKeysAndValues.append, and also caused a return of 0. If there
  1022. * are errors here they are from updatedKeysAndValues.append; they do cause an
  1023. * error return but the passed-in locale is unmodified and the original bufLen is
  1024. * returned.
  1025. */
  1026. if (!handledInputKeyAndValue || U_FAILURE(status)) {
  1027. /* if input key/value specified removal of a keyword not present in locale, or
  1028. * there was an error in CharString.append, leave original locale alone. */
  1029. U_ASSERT(status != U_STRING_NOT_TERMINATED_WARNING);
  1030. return static_cast<int32_t>(keywords.size());
  1031. }
  1032. needLen = updatedKeysAndValues.length();
  1033. // Check to see can we fit the updatedKeysAndValues, if not, return
  1034. // U_BUFFER_OVERFLOW_ERROR without copy updatedKeysAndValues into it.
  1035. // We do this because this API function does not behave like most others:
  1036. // It promises never to set a U_STRING_NOT_TERMINATED_WARNING.
  1037. // When the contents fits but without the terminating NUL, in this case we need to not change
  1038. // the buffer contents and return with a buffer overflow error.
  1039. if (needLen > 0) {
  1040. int32_t capacity = 0;
  1041. char* buffer = sink.GetAppendBuffer(
  1042. needLen, needLen, nullptr, needLen, &capacity);
  1043. if (capacity < needLen || buffer == nullptr) {
  1044. status = U_BUFFER_OVERFLOW_ERROR;
  1045. return needLen;
  1046. }
  1047. uprv_memcpy(buffer, updatedKeysAndValues.data(), needLen);
  1048. sink.Append(buffer, needLen);
  1049. }
  1050. U_ASSERT(status != U_STRING_NOT_TERMINATED_WARNING);
  1051. return needLen;
  1052. }
  1053. /* ### ID parsing implementation **************************************************/
  1054. namespace {
  1055. inline bool _isPrefixLetter(char a) { return a == 'x' || a == 'X' || a == 'i' || a == 'I'; }
  1056. /*returns true if one of the special prefixes is here (s=string)
  1057. 'x-' or 'i-' */
  1058. inline bool _isIDPrefix(const char *s) { return _isPrefixLetter(s[0]) && _isIDSeparator(s[1]); }
  1059. /* Dot terminates it because of POSIX form where dot precedes the codepage
  1060. * except for variant
  1061. */
  1062. inline bool _isTerminator(char a) { return a == 0 || a == '.' || a == '@'; }
  1063. inline bool _isBCP47Extension(const char* p) {
  1064. return p[0] == '-' &&
  1065. (p[1] == 't' || p[1] == 'T' ||
  1066. p[1] == 'u' || p[1] == 'U' ||
  1067. p[1] == 'x' || p[1] == 'X') &&
  1068. p[2] == '-';
  1069. }
  1070. /**
  1071. * Lookup 'key' in the array 'list'. The array 'list' should contain
  1072. * a nullptr entry, followed by more entries, and a second nullptr entry.
  1073. *
  1074. * The 'list' param should be LANGUAGES, LANGUAGES_3, COUNTRIES, or
  1075. * COUNTRIES_3.
  1076. */
  1077. std::optional<int16_t> _findIndex(const char* const* list, const char* key)
  1078. {
  1079. const char* const* anchor = list;
  1080. int32_t pass = 0;
  1081. /* Make two passes through two nullptr-terminated arrays at 'list' */
  1082. while (pass++ < 2) {
  1083. while (*list) {
  1084. if (uprv_strcmp(key, *list) == 0) {
  1085. return static_cast<int16_t>(list - anchor);
  1086. }
  1087. list++;
  1088. }
  1089. ++list; /* skip final nullptr *CWB*/
  1090. }
  1091. return std::nullopt;
  1092. }
  1093. } // namespace
  1094. U_CFUNC const char*
  1095. uloc_getCurrentCountryID(const char* oldID){
  1096. std::optional<int16_t> offset = _findIndex(DEPRECATED_COUNTRIES, oldID);
  1097. return offset.has_value() ? REPLACEMENT_COUNTRIES[*offset] : oldID;
  1098. }
  1099. U_CFUNC const char*
  1100. uloc_getCurrentLanguageID(const char* oldID){
  1101. std::optional<int16_t> offset = _findIndex(DEPRECATED_LANGUAGES, oldID);
  1102. return offset.has_value() ? REPLACEMENT_LANGUAGES[*offset] : oldID;
  1103. }
  1104. namespace {
  1105. /*
  1106. * the internal functions _getLanguage(), _getScript(), _getRegion(), _getVariant()
  1107. * avoid duplicating code to handle the earlier locale ID pieces
  1108. * in the functions for the later ones by
  1109. * setting the *pEnd pointer to where they stopped parsing
  1110. *
  1111. * TODO try to use this in Locale
  1112. */
  1113. void
  1114. _getLanguage(const char* localeID,
  1115. ByteSink* sink,
  1116. const char** pEnd,
  1117. UErrorCode& status) {
  1118. U_ASSERT(pEnd != nullptr);
  1119. *pEnd = localeID;
  1120. if (uprv_stricmp(localeID, "root") == 0) {
  1121. localeID += 4;
  1122. } else if (uprv_strnicmp(localeID, "und", 3) == 0 &&
  1123. (localeID[3] == '\0' ||
  1124. localeID[3] == '-' ||
  1125. localeID[3] == '_' ||
  1126. localeID[3] == '@')) {
  1127. localeID += 3;
  1128. }
  1129. constexpr int32_t MAXLEN = ULOC_LANG_CAPACITY - 1; // Minus NUL.
  1130. /* if it starts with i- or x- then copy that prefix */
  1131. int32_t len = _isIDPrefix(localeID) ? 2 : 0;
  1132. while (!_isTerminator(localeID[len]) && !_isIDSeparator(localeID[len])) {
  1133. if (len == MAXLEN) {
  1134. status = U_ILLEGAL_ARGUMENT_ERROR;
  1135. return;
  1136. }
  1137. len++;
  1138. }
  1139. *pEnd = localeID + len;
  1140. if (sink == nullptr || len == 0) { return; }
  1141. int32_t minCapacity = uprv_max(len, 4); // Minimum 3 letters plus NUL.
  1142. char scratch[MAXLEN];
  1143. int32_t capacity = 0;
  1144. char* buffer = sink->GetAppendBuffer(
  1145. minCapacity, minCapacity, scratch, UPRV_LENGTHOF(scratch), &capacity);
  1146. for (int32_t i = 0; i < len; ++i) {
  1147. buffer[i] = uprv_tolower(localeID[i]);
  1148. }
  1149. if (_isIDSeparator(localeID[1])) {
  1150. buffer[1] = '-';
  1151. }
  1152. if (len == 3) {
  1153. /* convert 3 character code to 2 character code if possible *CWB*/
  1154. U_ASSERT(capacity >= 4);
  1155. buffer[3] = '\0';
  1156. std::optional<int16_t> offset = _findIndex(LANGUAGES_3, buffer);
  1157. if (offset.has_value()) {
  1158. const char* const alias = LANGUAGES[*offset];
  1159. sink->Append(alias, static_cast<int32_t>(uprv_strlen(alias)));
  1160. return;
  1161. }
  1162. }
  1163. sink->Append(buffer, len);
  1164. }
  1165. void
  1166. _getScript(const char* localeID,
  1167. ByteSink* sink,
  1168. const char** pEnd) {
  1169. U_ASSERT(pEnd != nullptr);
  1170. *pEnd = localeID;
  1171. constexpr int32_t LENGTH = 4;
  1172. int32_t len = 0;
  1173. while (!_isTerminator(localeID[len]) && !_isIDSeparator(localeID[len]) &&
  1174. uprv_isASCIILetter(localeID[len])) {
  1175. if (len == LENGTH) { return; }
  1176. len++;
  1177. }
  1178. if (len != LENGTH) { return; }
  1179. *pEnd = localeID + LENGTH;
  1180. if (sink == nullptr) { return; }
  1181. char scratch[LENGTH];
  1182. int32_t capacity = 0;
  1183. char* buffer = sink->GetAppendBuffer(
  1184. LENGTH, LENGTH, scratch, UPRV_LENGTHOF(scratch), &capacity);
  1185. buffer[0] = uprv_toupper(localeID[0]);
  1186. for (int32_t i = 1; i < LENGTH; ++i) {
  1187. buffer[i] = uprv_tolower(localeID[i]);
  1188. }
  1189. sink->Append(buffer, LENGTH);
  1190. }
  1191. void
  1192. _getRegion(const char* localeID,
  1193. ByteSink* sink,
  1194. const char** pEnd) {
  1195. U_ASSERT(pEnd != nullptr);
  1196. *pEnd = localeID;
  1197. constexpr int32_t MINLEN = 2;
  1198. constexpr int32_t MAXLEN = ULOC_COUNTRY_CAPACITY - 1; // Minus NUL.
  1199. int32_t len = 0;
  1200. while (!_isTerminator(localeID[len]) && !_isIDSeparator(localeID[len])) {
  1201. if (len == MAXLEN) { return; }
  1202. len++;
  1203. }
  1204. if (len < MINLEN) { return; }
  1205. *pEnd = localeID + len;
  1206. if (sink == nullptr) { return; }
  1207. char scratch[ULOC_COUNTRY_CAPACITY];
  1208. int32_t capacity = 0;
  1209. char* buffer = sink->GetAppendBuffer(
  1210. ULOC_COUNTRY_CAPACITY,
  1211. ULOC_COUNTRY_CAPACITY,
  1212. scratch,
  1213. UPRV_LENGTHOF(scratch),
  1214. &capacity);
  1215. for (int32_t i = 0; i < len; ++i) {
  1216. buffer[i] = uprv_toupper(localeID[i]);
  1217. }
  1218. if (len == 3) {
  1219. /* convert 3 character code to 2 character code if possible *CWB*/
  1220. U_ASSERT(capacity >= 4);
  1221. buffer[3] = '\0';
  1222. std::optional<int16_t> offset = _findIndex(COUNTRIES_3, buffer);
  1223. if (offset.has_value()) {
  1224. const char* const alias = COUNTRIES[*offset];
  1225. sink->Append(alias, static_cast<int32_t>(uprv_strlen(alias)));
  1226. return;
  1227. }
  1228. }
  1229. sink->Append(buffer, len);
  1230. }
  1231. /**
  1232. * @param needSeparator if true, then add leading '_' if any variants
  1233. * are added to 'variant'
  1234. */
  1235. void
  1236. _getVariant(const char* localeID,
  1237. char prev,
  1238. ByteSink* sink,
  1239. const char** pEnd,
  1240. bool needSeparator,
  1241. UErrorCode& status) {
  1242. if (U_FAILURE(status)) return;
  1243. if (pEnd != nullptr) { *pEnd = localeID; }
  1244. // Reasonable upper limit for variants
  1245. // There are no strict limitation of the syntax of variant in the legacy
  1246. // locale format. If the locale is constructed from unicode_locale_id
  1247. // as defined in UTS35, then we know each unicode_variant_subtag
  1248. // could have max length of 8 ((alphanum{5,8} | digit alphanum{3})
  1249. // 179 would allow 20 unicode_variant_subtag with sep in the
  1250. // unicode_locale_id
  1251. // 8*20 + 1*(20-1) = 179
  1252. constexpr int32_t MAX_VARIANTS_LENGTH = 179;
  1253. /* get one or more variant tags and separate them with '_' */
  1254. int32_t index = 0;
  1255. if (_isIDSeparator(prev)) {
  1256. /* get a variant string after a '-' or '_' */
  1257. for (index=0; !_isTerminator(localeID[index]); index++) {
  1258. if (index >= MAX_VARIANTS_LENGTH) { // same as length > MAX_VARIANTS_LENGTH
  1259. status = U_ILLEGAL_ARGUMENT_ERROR;
  1260. return;
  1261. }
  1262. if (needSeparator) {
  1263. if (sink != nullptr) {
  1264. sink->Append("_", 1);
  1265. }
  1266. needSeparator = false;
  1267. }
  1268. if (sink != nullptr) {
  1269. char c = uprv_toupper(localeID[index]);
  1270. if (c == '-') c = '_';
  1271. sink->Append(&c, 1);
  1272. }
  1273. }
  1274. if (pEnd != nullptr) { *pEnd = localeID+index; }
  1275. }
  1276. /* if there is no variant tag after a '-' or '_' then look for '@' */
  1277. if (index == 0) {
  1278. if (prev=='@') {
  1279. /* keep localeID */
  1280. } else if((localeID=locale_getKeywordsStart(localeID))!=nullptr) {
  1281. ++localeID; /* point after the '@' */
  1282. } else {
  1283. return;
  1284. }
  1285. for(; !_isTerminator(localeID[index]); index++) {
  1286. if (index >= MAX_VARIANTS_LENGTH) { // same as length > MAX_VARIANTS_LENGTH
  1287. status = U_ILLEGAL_ARGUMENT_ERROR;
  1288. return;
  1289. }
  1290. if (needSeparator) {
  1291. if (sink != nullptr) {
  1292. sink->Append("_", 1);
  1293. }
  1294. needSeparator = false;
  1295. }
  1296. if (sink != nullptr) {
  1297. char c = uprv_toupper(localeID[index]);
  1298. if (c == '-' || c == ',') c = '_';
  1299. sink->Append(&c, 1);
  1300. }
  1301. }
  1302. if (pEnd != nullptr) { *pEnd = localeID + index; }
  1303. }
  1304. }
  1305. } // namespace
  1306. U_EXPORT CharString
  1307. ulocimp_getLanguage(const char* localeID, UErrorCode& status) {
  1308. return ByteSinkUtil::viaByteSinkToCharString(
  1309. [&](ByteSink& sink, UErrorCode& status) {
  1310. ulocimp_getSubtags(
  1311. localeID,
  1312. &sink,
  1313. nullptr,
  1314. nullptr,
  1315. nullptr,
  1316. nullptr,
  1317. status);
  1318. },
  1319. status);
  1320. }
  1321. U_EXPORT CharString
  1322. ulocimp_getScript(const char* localeID, UErrorCode& status) {
  1323. return ByteSinkUtil::viaByteSinkToCharString(
  1324. [&](ByteSink& sink, UErrorCode& status) {
  1325. ulocimp_getSubtags(
  1326. localeID,
  1327. nullptr,
  1328. &sink,
  1329. nullptr,
  1330. nullptr,
  1331. nullptr,
  1332. status);
  1333. },
  1334. status);
  1335. }
  1336. U_EXPORT CharString
  1337. ulocimp_getRegion(const char* localeID, UErrorCode& status) {
  1338. return ByteSinkUtil::viaByteSinkToCharString(
  1339. [&](ByteSink& sink, UErrorCode& status) {
  1340. ulocimp_getSubtags(
  1341. localeID,
  1342. nullptr,
  1343. nullptr,
  1344. &sink,
  1345. nullptr,
  1346. nullptr,
  1347. status);
  1348. },
  1349. status);
  1350. }
  1351. U_EXPORT CharString
  1352. ulocimp_getVariant(const char* localeID, UErrorCode& status) {
  1353. return ByteSinkUtil::viaByteSinkToCharString(
  1354. [&](ByteSink& sink, UErrorCode& status) {
  1355. ulocimp_getSubtags(
  1356. localeID,
  1357. nullptr,
  1358. nullptr,
  1359. nullptr,
  1360. &sink,
  1361. nullptr,
  1362. status);
  1363. },
  1364. status);
  1365. }
  1366. U_EXPORT void
  1367. ulocimp_getSubtags(
  1368. const char* localeID,
  1369. CharString* language,
  1370. CharString* script,
  1371. CharString* region,
  1372. CharString* variant,
  1373. const char** pEnd,
  1374. UErrorCode& status) {
  1375. if (U_FAILURE(status)) { return; }
  1376. std::optional<CharStringByteSink> languageSink;
  1377. std::optional<CharStringByteSink> scriptSink;
  1378. std::optional<CharStringByteSink> regionSink;
  1379. std::optional<CharStringByteSink> variantSink;
  1380. if (language != nullptr) { languageSink.emplace(language); }
  1381. if (script != nullptr) { scriptSink.emplace(script); }
  1382. if (region != nullptr) { regionSink.emplace(region); }
  1383. if (variant != nullptr) { variantSink.emplace(variant); }
  1384. ulocimp_getSubtags(
  1385. localeID,
  1386. languageSink.has_value() ? &*languageSink : nullptr,
  1387. scriptSink.has_value() ? &*scriptSink : nullptr,
  1388. regionSink.has_value() ? &*regionSink : nullptr,
  1389. variantSink.has_value() ? &*variantSink : nullptr,
  1390. pEnd,
  1391. status);
  1392. }
  1393. U_EXPORT void
  1394. ulocimp_getSubtags(
  1395. const char* localeID,
  1396. ByteSink* language,
  1397. ByteSink* script,
  1398. ByteSink* region,
  1399. ByteSink* variant,
  1400. const char** pEnd,
  1401. UErrorCode& status) {
  1402. if (U_FAILURE(status)) { return; }
  1403. if (pEnd != nullptr) {
  1404. *pEnd = localeID;
  1405. } else if (language == nullptr &&
  1406. script == nullptr &&
  1407. region == nullptr &&
  1408. variant == nullptr) {
  1409. return;
  1410. }
  1411. bool hasRegion = false;
  1412. if (localeID == nullptr) {
  1413. localeID = uloc_getDefault();
  1414. }
  1415. _getLanguage(localeID, language, &localeID, status);
  1416. if (U_FAILURE(status)) { return; }
  1417. U_ASSERT(localeID != nullptr);
  1418. if (pEnd != nullptr) {
  1419. *pEnd = localeID;
  1420. } else if (script == nullptr &&
  1421. region == nullptr &&
  1422. variant == nullptr) {
  1423. return;
  1424. }
  1425. if (_isIDSeparator(*localeID)) {
  1426. const char* begin = localeID + 1;
  1427. const char* end = nullptr;
  1428. _getScript(begin, script, &end);
  1429. U_ASSERT(end != nullptr);
  1430. if (end != begin) {
  1431. localeID = end;
  1432. if (pEnd != nullptr) { *pEnd = localeID; }
  1433. }
  1434. }
  1435. if (region == nullptr && variant == nullptr && pEnd == nullptr) { return; }
  1436. if (_isIDSeparator(*localeID)) {
  1437. const char* begin = localeID + 1;
  1438. const char* end = nullptr;
  1439. _getRegion(begin, region, &end);
  1440. U_ASSERT(end != nullptr);
  1441. if (end != begin) {
  1442. hasRegion = true;
  1443. localeID = end;
  1444. if (pEnd != nullptr) { *pEnd = localeID; }
  1445. }
  1446. }
  1447. if (variant == nullptr && pEnd == nullptr) { return; }
  1448. if (_isIDSeparator(*localeID) && !_isBCP47Extension(localeID)) {
  1449. /* If there was no country ID, skip a possible extra IDSeparator */
  1450. if (!hasRegion && _isIDSeparator(localeID[1])) {
  1451. localeID++;
  1452. }
  1453. const char* begin = localeID + 1;
  1454. const char* end = nullptr;
  1455. _getVariant(begin, *localeID, variant, &end, false, status);
  1456. if (U_FAILURE(status)) { return; }
  1457. U_ASSERT(end != nullptr);
  1458. if (end != begin && pEnd != nullptr) { *pEnd = end; }
  1459. }
  1460. }
  1461. /* Keyword enumeration */
  1462. typedef struct UKeywordsContext {
  1463. char* keywords;
  1464. char* current;
  1465. } UKeywordsContext;
  1466. U_CDECL_BEGIN
  1467. static void U_CALLCONV
  1468. uloc_kw_closeKeywords(UEnumeration *enumerator) {
  1469. uprv_free(((UKeywordsContext *)enumerator->context)->keywords);
  1470. uprv_free(enumerator->context);
  1471. uprv_free(enumerator);
  1472. }
  1473. static int32_t U_CALLCONV
  1474. uloc_kw_countKeywords(UEnumeration *en, UErrorCode * /*status*/) {
  1475. char *kw = ((UKeywordsContext *)en->context)->keywords;
  1476. int32_t result = 0;
  1477. while(*kw) {
  1478. result++;
  1479. kw += uprv_strlen(kw)+1;
  1480. }
  1481. return result;
  1482. }
  1483. static const char * U_CALLCONV
  1484. uloc_kw_nextKeyword(UEnumeration* en,
  1485. int32_t* resultLength,
  1486. UErrorCode* /*status*/) {
  1487. const char* result = ((UKeywordsContext *)en->context)->current;
  1488. int32_t len = 0;
  1489. if(*result) {
  1490. len = (int32_t)uprv_strlen(((UKeywordsContext *)en->context)->current);
  1491. ((UKeywordsContext *)en->context)->current += len+1;
  1492. } else {
  1493. result = nullptr;
  1494. }
  1495. if (resultLength) {
  1496. *resultLength = len;
  1497. }
  1498. return result;
  1499. }
  1500. static void U_CALLCONV
  1501. uloc_kw_resetKeywords(UEnumeration* en,
  1502. UErrorCode* /*status*/) {
  1503. ((UKeywordsContext *)en->context)->current = ((UKeywordsContext *)en->context)->keywords;
  1504. }
  1505. U_CDECL_END
  1506. static const UEnumeration gKeywordsEnum = {
  1507. nullptr,
  1508. nullptr,
  1509. uloc_kw_closeKeywords,
  1510. uloc_kw_countKeywords,
  1511. uenum_unextDefault,
  1512. uloc_kw_nextKeyword,
  1513. uloc_kw_resetKeywords
  1514. };
  1515. U_CAPI UEnumeration* U_EXPORT2
  1516. uloc_openKeywordList(const char *keywordList, int32_t keywordListSize, UErrorCode* status)
  1517. {
  1518. if (U_FAILURE(*status)) { return nullptr; }
  1519. LocalMemory<UKeywordsContext> myContext;
  1520. LocalMemory<UEnumeration> result;
  1521. myContext.adoptInstead(static_cast<UKeywordsContext *>(uprv_malloc(sizeof(UKeywordsContext))));
  1522. result.adoptInstead(static_cast<UEnumeration *>(uprv_malloc(sizeof(UEnumeration))));
  1523. if (myContext.isNull() || result.isNull()) {
  1524. *status = U_MEMORY_ALLOCATION_ERROR;
  1525. return nullptr;
  1526. }
  1527. uprv_memcpy(result.getAlias(), &gKeywordsEnum, sizeof(UEnumeration));
  1528. myContext->keywords = static_cast<char *>(uprv_malloc(keywordListSize+1));
  1529. if (myContext->keywords == nullptr) {
  1530. *status = U_MEMORY_ALLOCATION_ERROR;
  1531. return nullptr;
  1532. }
  1533. uprv_memcpy(myContext->keywords, keywordList, keywordListSize);
  1534. myContext->keywords[keywordListSize] = 0;
  1535. myContext->current = myContext->keywords;
  1536. result->context = myContext.orphan();
  1537. return result.orphan();
  1538. }
  1539. U_CAPI UEnumeration* U_EXPORT2
  1540. uloc_openKeywords(const char* localeID,
  1541. UErrorCode* status)
  1542. {
  1543. if(status==nullptr || U_FAILURE(*status)) {
  1544. return nullptr;
  1545. }
  1546. CharString tempBuffer;
  1547. const char* tmpLocaleID;
  1548. if (_hasBCP47Extension(localeID)) {
  1549. tempBuffer = ulocimp_forLanguageTag(localeID, -1, nullptr, *status);
  1550. tmpLocaleID = U_SUCCESS(*status) && !tempBuffer.isEmpty() ? tempBuffer.data() : localeID;
  1551. } else {
  1552. if (localeID==nullptr) {
  1553. localeID=uloc_getDefault();
  1554. }
  1555. tmpLocaleID=localeID;
  1556. }
  1557. ulocimp_getSubtags(
  1558. tmpLocaleID,
  1559. nullptr,
  1560. nullptr,
  1561. nullptr,
  1562. nullptr,
  1563. &tmpLocaleID,
  1564. *status);
  1565. if (U_FAILURE(*status)) {
  1566. return nullptr;
  1567. }
  1568. /* keywords are located after '@' */
  1569. if((tmpLocaleID = locale_getKeywordsStart(tmpLocaleID)) != nullptr) {
  1570. CharString keywords = ulocimp_getKeywords(tmpLocaleID + 1, '@', false, *status);
  1571. if (U_FAILURE(*status)) {
  1572. return nullptr;
  1573. }
  1574. return uloc_openKeywordList(keywords.data(), keywords.length(), status);
  1575. }
  1576. return nullptr;
  1577. }
  1578. /* bit-flags for 'options' parameter of _canonicalize */
  1579. #define _ULOC_STRIP_KEYWORDS 0x2
  1580. #define _ULOC_CANONICALIZE 0x1
  1581. namespace {
  1582. inline bool OPTION_SET(uint32_t options, uint32_t mask) { return (options & mask) != 0; }
  1583. constexpr char i_default[] = {'i', '-', 'd', 'e', 'f', 'a', 'u', 'l', 't'};
  1584. constexpr int32_t I_DEFAULT_LENGTH = UPRV_LENGTHOF(i_default);
  1585. /**
  1586. * Canonicalize the given localeID, to level 1 or to level 2,
  1587. * depending on the options. To specify level 1, pass in options=0.
  1588. * To specify level 2, pass in options=_ULOC_CANONICALIZE.
  1589. *
  1590. * This is the code underlying uloc_getName and uloc_canonicalize.
  1591. */
  1592. void
  1593. _canonicalize(const char* localeID,
  1594. ByteSink& sink,
  1595. uint32_t options,
  1596. UErrorCode& err) {
  1597. if (U_FAILURE(err)) {
  1598. return;
  1599. }
  1600. int32_t j, fieldCount=0;
  1601. CharString tempBuffer; // if localeID has a BCP47 extension, tmpLocaleID points to this
  1602. CharString localeIDWithHyphens; // if localeID has a BPC47 extension and have _, tmpLocaleID points to this
  1603. const char* origLocaleID;
  1604. const char* tmpLocaleID;
  1605. const char* keywordAssign = nullptr;
  1606. const char* separatorIndicator = nullptr;
  1607. if (_hasBCP47Extension(localeID)) {
  1608. const char* localeIDPtr = localeID;
  1609. // convert all underbars to hyphens, unless the "BCP47 extension" comes at the beginning of the string
  1610. if (uprv_strchr(localeID, '_') != nullptr && localeID[1] != '-' && localeID[1] != '_') {
  1611. localeIDWithHyphens.append(localeID, -1, err);
  1612. if (U_SUCCESS(err)) {
  1613. for (char* p = localeIDWithHyphens.data(); *p != '\0'; ++p) {
  1614. if (*p == '_') {
  1615. *p = '-';
  1616. }
  1617. }
  1618. localeIDPtr = localeIDWithHyphens.data();
  1619. }
  1620. }
  1621. tempBuffer = ulocimp_forLanguageTag(localeIDPtr, -1, nullptr, err);
  1622. tmpLocaleID = U_SUCCESS(err) && !tempBuffer.isEmpty() ? tempBuffer.data() : localeIDPtr;
  1623. } else {
  1624. if (localeID==nullptr) {
  1625. localeID=uloc_getDefault();
  1626. }
  1627. tmpLocaleID=localeID;
  1628. }
  1629. origLocaleID=tmpLocaleID;
  1630. /* get all pieces, one after another, and separate with '_' */
  1631. CharString tag;
  1632. CharString script;
  1633. CharString country;
  1634. CharString variant;
  1635. ulocimp_getSubtags(
  1636. tmpLocaleID,
  1637. &tag,
  1638. &script,
  1639. &country,
  1640. &variant,
  1641. &tmpLocaleID,
  1642. err);
  1643. if (U_FAILURE(err)) {
  1644. return;
  1645. }
  1646. if (tag.length() == I_DEFAULT_LENGTH &&
  1647. uprv_strncmp(origLocaleID, i_default, I_DEFAULT_LENGTH) == 0) {
  1648. tag.clear();
  1649. tag.append(uloc_getDefault(), err);
  1650. } else {
  1651. if (!script.isEmpty()) {
  1652. ++fieldCount;
  1653. tag.append('_', err);
  1654. tag.append(script, err);
  1655. }
  1656. if (!country.isEmpty()) {
  1657. ++fieldCount;
  1658. tag.append('_', err);
  1659. tag.append(country, err);
  1660. }
  1661. if (!variant.isEmpty()) {
  1662. ++fieldCount;
  1663. if (country.isEmpty()) {
  1664. tag.append('_', err);
  1665. }
  1666. tag.append('_', err);
  1667. tag.append(variant, err);
  1668. }
  1669. }
  1670. /* Copy POSIX-style charset specifier, if any [mr.utf8] */
  1671. if (!OPTION_SET(options, _ULOC_CANONICALIZE) && *tmpLocaleID == '.') {
  1672. tag.append('.', err);
  1673. ++tmpLocaleID;
  1674. const char *atPos = nullptr;
  1675. size_t length;
  1676. if((atPos = uprv_strchr(tmpLocaleID, '@')) != nullptr) {
  1677. length = atPos - tmpLocaleID;
  1678. } else {
  1679. length = uprv_strlen(tmpLocaleID);
  1680. }
  1681. // The longest charset name we found in IANA charset registry
  1682. // https://www.iana.org/assignments/character-sets/ is
  1683. // "Extended_UNIX_Code_Packed_Format_for_Japanese" in length 45.
  1684. // we therefore restrict the length here to be 64 which is a power of 2
  1685. // number that is longer than 45.
  1686. constexpr size_t kMaxCharsetLength = 64;
  1687. if (length > kMaxCharsetLength) {
  1688. err = U_ILLEGAL_ARGUMENT_ERROR; /* malformed keyword name */
  1689. return;
  1690. }
  1691. tag.append(tmpLocaleID, static_cast<int32_t>(length), err);
  1692. tmpLocaleID += length;
  1693. }
  1694. /* Scan ahead to next '@' and determine if it is followed by '=' and/or ';'
  1695. After this, tmpLocaleID either points to '@' or is nullptr */
  1696. if ((tmpLocaleID=locale_getKeywordsStart(tmpLocaleID))!=nullptr) {
  1697. keywordAssign = uprv_strchr(tmpLocaleID, '=');
  1698. separatorIndicator = uprv_strchr(tmpLocaleID, ';');
  1699. }
  1700. /* Copy POSIX-style variant, if any [mr@FOO] */
  1701. if (!OPTION_SET(options, _ULOC_CANONICALIZE) &&
  1702. tmpLocaleID != nullptr && keywordAssign == nullptr) {
  1703. for (;;) {
  1704. char c = *tmpLocaleID;
  1705. if (c == 0) {
  1706. break;
  1707. }
  1708. tag.append(c, err);
  1709. ++tmpLocaleID;
  1710. }
  1711. }
  1712. if (OPTION_SET(options, _ULOC_CANONICALIZE)) {
  1713. /* Handle @FOO variant if @ is present and not followed by = */
  1714. if (tmpLocaleID!=nullptr && keywordAssign==nullptr) {
  1715. /* Add missing '_' if needed */
  1716. if (fieldCount < 2 || (fieldCount < 3 && !script.isEmpty())) {
  1717. do {
  1718. tag.append('_', err);
  1719. ++fieldCount;
  1720. } while(fieldCount<2);
  1721. }
  1722. CharStringByteSink s(&tag);
  1723. _getVariant(tmpLocaleID+1, '@', &s, nullptr, !variant.isEmpty(), err);
  1724. if (U_FAILURE(err)) { return; }
  1725. }
  1726. /* Look up the ID in the canonicalization map */
  1727. for (j=0; j<UPRV_LENGTHOF(CANONICALIZE_MAP); j++) {
  1728. StringPiece id(CANONICALIZE_MAP[j].id);
  1729. if (tag == id) {
  1730. if (id.empty() && tmpLocaleID != nullptr) {
  1731. break; /* Don't remap "" if keywords present */
  1732. }
  1733. tag.clear();
  1734. tag.append(CANONICALIZE_MAP[j].canonicalID, err);
  1735. break;
  1736. }
  1737. }
  1738. }
  1739. sink.Append(tag.data(), tag.length());
  1740. if (!OPTION_SET(options, _ULOC_STRIP_KEYWORDS)) {
  1741. if (tmpLocaleID!=nullptr && keywordAssign!=nullptr &&
  1742. (!separatorIndicator || separatorIndicator > keywordAssign)) {
  1743. sink.Append("@", 1);
  1744. ++fieldCount;
  1745. ulocimp_getKeywords(tmpLocaleID+1, '@', sink, true, err);
  1746. }
  1747. }
  1748. }
  1749. } // namespace
  1750. /* ### ID parsing API **************************************************/
  1751. U_CAPI int32_t U_EXPORT2
  1752. uloc_getParent(const char* localeID,
  1753. char* parent,
  1754. int32_t parentCapacity,
  1755. UErrorCode* err)
  1756. {
  1757. return ByteSinkUtil::viaByteSinkToTerminatedChars(
  1758. parent, parentCapacity,
  1759. [&](ByteSink& sink, UErrorCode& status) {
  1760. ulocimp_getParent(localeID, sink, status);
  1761. },
  1762. *err);
  1763. }
  1764. U_EXPORT CharString
  1765. ulocimp_getParent(const char* localeID,
  1766. UErrorCode& err)
  1767. {
  1768. return ByteSinkUtil::viaByteSinkToCharString(
  1769. [&](ByteSink& sink, UErrorCode& status) {
  1770. ulocimp_getParent(localeID, sink, status);
  1771. },
  1772. err);
  1773. }
  1774. U_EXPORT void
  1775. ulocimp_getParent(const char* localeID,
  1776. icu::ByteSink& sink,
  1777. UErrorCode& err)
  1778. {
  1779. if (U_FAILURE(err)) { return; }
  1780. const char *lastUnderscore;
  1781. int32_t i;
  1782. if (localeID == nullptr)
  1783. localeID = uloc_getDefault();
  1784. lastUnderscore=uprv_strrchr(localeID, '_');
  1785. if(lastUnderscore!=nullptr) {
  1786. i = static_cast<int32_t>(lastUnderscore - localeID);
  1787. } else {
  1788. i=0;
  1789. }
  1790. if (i > 0) {
  1791. if (uprv_strnicmp(localeID, "und_", 4) == 0) {
  1792. localeID += 3;
  1793. i -= 3;
  1794. }
  1795. sink.Append(localeID, i);
  1796. }
  1797. }
  1798. U_CAPI int32_t U_EXPORT2
  1799. uloc_getLanguage(const char* localeID,
  1800. char* language,
  1801. int32_t languageCapacity,
  1802. UErrorCode* err)
  1803. {
  1804. /* uloc_getLanguage will return a 2 character iso-639 code if one exists. *CWB*/
  1805. return ByteSinkUtil::viaByteSinkToTerminatedChars(
  1806. language, languageCapacity,
  1807. [&](ByteSink& sink, UErrorCode& status) {
  1808. ulocimp_getSubtags(
  1809. localeID,
  1810. &sink,
  1811. nullptr,
  1812. nullptr,
  1813. nullptr,
  1814. nullptr,
  1815. status);
  1816. },
  1817. *err);
  1818. }
  1819. U_CAPI int32_t U_EXPORT2
  1820. uloc_getScript(const char* localeID,
  1821. char* script,
  1822. int32_t scriptCapacity,
  1823. UErrorCode* err)
  1824. {
  1825. return ByteSinkUtil::viaByteSinkToTerminatedChars(
  1826. script, scriptCapacity,
  1827. [&](ByteSink& sink, UErrorCode& status) {
  1828. ulocimp_getSubtags(
  1829. localeID,
  1830. nullptr,
  1831. &sink,
  1832. nullptr,
  1833. nullptr,
  1834. nullptr,
  1835. status);
  1836. },
  1837. *err);
  1838. }
  1839. U_CAPI int32_t U_EXPORT2
  1840. uloc_getCountry(const char* localeID,
  1841. char* country,
  1842. int32_t countryCapacity,
  1843. UErrorCode* err)
  1844. {
  1845. return ByteSinkUtil::viaByteSinkToTerminatedChars(
  1846. country, countryCapacity,
  1847. [&](ByteSink& sink, UErrorCode& status) {
  1848. ulocimp_getSubtags(
  1849. localeID,
  1850. nullptr,
  1851. nullptr,
  1852. &sink,
  1853. nullptr,
  1854. nullptr,
  1855. status);
  1856. },
  1857. *err);
  1858. }
  1859. U_CAPI int32_t U_EXPORT2
  1860. uloc_getVariant(const char* localeID,
  1861. char* variant,
  1862. int32_t variantCapacity,
  1863. UErrorCode* err)
  1864. {
  1865. return ByteSinkUtil::viaByteSinkToTerminatedChars(
  1866. variant, variantCapacity,
  1867. [&](ByteSink& sink, UErrorCode& status) {
  1868. ulocimp_getSubtags(
  1869. localeID,
  1870. nullptr,
  1871. nullptr,
  1872. nullptr,
  1873. &sink,
  1874. nullptr,
  1875. status);
  1876. },
  1877. *err);
  1878. }
  1879. U_CAPI int32_t U_EXPORT2
  1880. uloc_getName(const char* localeID,
  1881. char* name,
  1882. int32_t nameCapacity,
  1883. UErrorCode* err)
  1884. {
  1885. return ByteSinkUtil::viaByteSinkToTerminatedChars(
  1886. name, nameCapacity,
  1887. [&](ByteSink& sink, UErrorCode& status) {
  1888. ulocimp_getName(localeID, sink, status);
  1889. },
  1890. *err);
  1891. }
  1892. U_EXPORT CharString
  1893. ulocimp_getName(const char* localeID,
  1894. UErrorCode& err)
  1895. {
  1896. return ByteSinkUtil::viaByteSinkToCharString(
  1897. [&](ByteSink& sink, UErrorCode& status) {
  1898. ulocimp_getName(localeID, sink, status);
  1899. },
  1900. err);
  1901. }
  1902. U_EXPORT void
  1903. ulocimp_getName(const char* localeID,
  1904. ByteSink& sink,
  1905. UErrorCode& err)
  1906. {
  1907. _canonicalize(localeID, sink, 0, err);
  1908. }
  1909. U_CAPI int32_t U_EXPORT2
  1910. uloc_getBaseName(const char* localeID,
  1911. char* name,
  1912. int32_t nameCapacity,
  1913. UErrorCode* err)
  1914. {
  1915. return ByteSinkUtil::viaByteSinkToTerminatedChars(
  1916. name, nameCapacity,
  1917. [&](ByteSink& sink, UErrorCode& status) {
  1918. ulocimp_getBaseName(localeID, sink, status);
  1919. },
  1920. *err);
  1921. }
  1922. U_EXPORT CharString
  1923. ulocimp_getBaseName(const char* localeID,
  1924. UErrorCode& err)
  1925. {
  1926. return ByteSinkUtil::viaByteSinkToCharString(
  1927. [&](ByteSink& sink, UErrorCode& status) {
  1928. ulocimp_getBaseName(localeID, sink, status);
  1929. },
  1930. err);
  1931. }
  1932. U_EXPORT void
  1933. ulocimp_getBaseName(const char* localeID,
  1934. ByteSink& sink,
  1935. UErrorCode& err)
  1936. {
  1937. _canonicalize(localeID, sink, _ULOC_STRIP_KEYWORDS, err);
  1938. }
  1939. U_CAPI int32_t U_EXPORT2
  1940. uloc_canonicalize(const char* localeID,
  1941. char* name,
  1942. int32_t nameCapacity,
  1943. UErrorCode* err)
  1944. {
  1945. return ByteSinkUtil::viaByteSinkToTerminatedChars(
  1946. name, nameCapacity,
  1947. [&](ByteSink& sink, UErrorCode& status) {
  1948. ulocimp_canonicalize(localeID, sink, status);
  1949. },
  1950. *err);
  1951. }
  1952. U_EXPORT CharString
  1953. ulocimp_canonicalize(const char* localeID,
  1954. UErrorCode& err)
  1955. {
  1956. return ByteSinkUtil::viaByteSinkToCharString(
  1957. [&](ByteSink& sink, UErrorCode& status) {
  1958. ulocimp_canonicalize(localeID, sink, status);
  1959. },
  1960. err);
  1961. }
  1962. U_EXPORT void
  1963. ulocimp_canonicalize(const char* localeID,
  1964. ByteSink& sink,
  1965. UErrorCode& err)
  1966. {
  1967. _canonicalize(localeID, sink, _ULOC_CANONICALIZE, err);
  1968. }
  1969. U_CAPI const char* U_EXPORT2
  1970. uloc_getISO3Language(const char* localeID)
  1971. {
  1972. UErrorCode err = U_ZERO_ERROR;
  1973. if (localeID == nullptr)
  1974. {
  1975. localeID = uloc_getDefault();
  1976. }
  1977. CharString lang = ulocimp_getLanguage(localeID, err);
  1978. if (U_FAILURE(err))
  1979. return "";
  1980. std::optional<int16_t> offset = _findIndex(LANGUAGES, lang.data());
  1981. return offset.has_value() ? LANGUAGES_3[*offset] : "";
  1982. }
  1983. U_CAPI const char* U_EXPORT2
  1984. uloc_getISO3Country(const char* localeID)
  1985. {
  1986. UErrorCode err = U_ZERO_ERROR;
  1987. if (localeID == nullptr)
  1988. {
  1989. localeID = uloc_getDefault();
  1990. }
  1991. CharString cntry = ulocimp_getRegion(localeID, err);
  1992. if (U_FAILURE(err))
  1993. return "";
  1994. std::optional<int16_t> offset = _findIndex(COUNTRIES, cntry.data());
  1995. return offset.has_value() ? COUNTRIES_3[*offset] : "";
  1996. }
  1997. U_CAPI uint32_t U_EXPORT2
  1998. uloc_getLCID(const char* localeID)
  1999. {
  2000. UErrorCode status = U_ZERO_ERROR;
  2001. uint32_t lcid = 0;
  2002. /* Check for incomplete id. */
  2003. if (!localeID || uprv_strlen(localeID) < 2) {
  2004. return 0;
  2005. }
  2006. // First, attempt Windows platform lookup if available, but fall
  2007. // through to catch any special cases (ICU vs Windows name differences).
  2008. lcid = uprv_convertToLCIDPlatform(localeID, &status);
  2009. if (U_FAILURE(status)) {
  2010. return 0;
  2011. }
  2012. if (lcid > 0) {
  2013. // Windows found an LCID, return that
  2014. return lcid;
  2015. }
  2016. CharString langID = ulocimp_getLanguage(localeID, status);
  2017. if (U_FAILURE(status)) {
  2018. return 0;
  2019. }
  2020. if (uprv_strchr(localeID, '@')) {
  2021. // uprv_convertToLCID does not support keywords other than collation.
  2022. // Remove all keywords except collation.
  2023. CharString collVal = ulocimp_getKeywordValue(localeID, "collation", status);
  2024. if (U_SUCCESS(status) && !collVal.isEmpty()) {
  2025. CharString tmpLocaleID = ulocimp_getBaseName(localeID, status);
  2026. ulocimp_setKeywordValue("collation", collVal.toStringPiece(), tmpLocaleID, status);
  2027. if (U_SUCCESS(status)) {
  2028. return uprv_convertToLCID(langID.data(), tmpLocaleID.data(), &status);
  2029. }
  2030. }
  2031. // fall through - all keywords are simply ignored
  2032. status = U_ZERO_ERROR;
  2033. }
  2034. return uprv_convertToLCID(langID.data(), localeID, &status);
  2035. }
  2036. U_CAPI int32_t U_EXPORT2
  2037. uloc_getLocaleForLCID(uint32_t hostid, char *locale, int32_t localeCapacity,
  2038. UErrorCode *status)
  2039. {
  2040. return uprv_convertToPosix(hostid, locale, localeCapacity, status);
  2041. }
  2042. /* ### Default locale **************************************************/
  2043. U_CAPI const char* U_EXPORT2
  2044. uloc_getDefault()
  2045. {
  2046. return locale_get_default();
  2047. }
  2048. U_CAPI void U_EXPORT2
  2049. uloc_setDefault(const char* newDefaultLocale,
  2050. UErrorCode* err)
  2051. {
  2052. if (U_FAILURE(*err))
  2053. return;
  2054. /* the error code isn't currently used for anything by this function*/
  2055. /* propagate change to C++ */
  2056. locale_set_default(newDefaultLocale);
  2057. }
  2058. /**
  2059. * Returns a list of all 2-letter language codes defined in ISO 639. This is a pointer
  2060. * to an array of pointers to arrays of char. All of these pointers are owned
  2061. * by ICU-- do not delete them, and do not write through them. The array is
  2062. * terminated with a null pointer.
  2063. */
  2064. U_CAPI const char* const* U_EXPORT2
  2065. uloc_getISOLanguages()
  2066. {
  2067. return LANGUAGES;
  2068. }
  2069. /**
  2070. * Returns a list of all 2-letter country codes defined in ISO 639. This is a
  2071. * pointer to an array of pointers to arrays of char. All of these pointers are
  2072. * owned by ICU-- do not delete them, and do not write through them. The array is
  2073. * terminated with a null pointer.
  2074. */
  2075. U_CAPI const char* const* U_EXPORT2
  2076. uloc_getISOCountries()
  2077. {
  2078. return COUNTRIES;
  2079. }
  2080. U_CAPI const char* U_EXPORT2
  2081. uloc_toUnicodeLocaleKey(const char* keyword)
  2082. {
  2083. if (keyword == nullptr || *keyword == '\0') { return nullptr; }
  2084. std::optional<std::string_view> result = ulocimp_toBcpKeyWithFallback(keyword);
  2085. return result.has_value() ? result->data() : nullptr; // Known to be NUL terminated.
  2086. }
  2087. U_EXPORT std::optional<std::string_view>
  2088. ulocimp_toBcpKeyWithFallback(std::string_view keyword)
  2089. {
  2090. std::optional<std::string_view> bcpKey = ulocimp_toBcpKey(keyword);
  2091. if (!bcpKey.has_value() &&
  2092. ultag_isUnicodeLocaleKey(keyword.data(), static_cast<int32_t>(keyword.size()))) {
  2093. // unknown keyword, but syntax is fine..
  2094. return keyword;
  2095. }
  2096. return bcpKey;
  2097. }
  2098. U_CAPI const char* U_EXPORT2
  2099. uloc_toUnicodeLocaleType(const char* keyword, const char* value)
  2100. {
  2101. if (keyword == nullptr || *keyword == '\0' ||
  2102. value == nullptr || *value == '\0') { return nullptr; }
  2103. std::optional<std::string_view> result = ulocimp_toBcpTypeWithFallback(keyword, value);
  2104. return result.has_value() ? result->data() : nullptr; // Known to be NUL terminated.
  2105. }
  2106. U_EXPORT std::optional<std::string_view>
  2107. ulocimp_toBcpTypeWithFallback(std::string_view keyword, std::string_view value)
  2108. {
  2109. std::optional<std::string_view> bcpType = ulocimp_toBcpType(keyword, value);
  2110. if (!bcpType.has_value() &&
  2111. ultag_isUnicodeLocaleType(value.data(), static_cast<int32_t>(value.size()))) {
  2112. // unknown keyword, but syntax is fine..
  2113. return value;
  2114. }
  2115. return bcpType;
  2116. }
  2117. namespace {
  2118. bool
  2119. isWellFormedLegacyKey(std::string_view key)
  2120. {
  2121. return std::all_of(key.begin(), key.end(), UPRV_ISALPHANUM);
  2122. }
  2123. bool
  2124. isWellFormedLegacyType(std::string_view legacyType)
  2125. {
  2126. int32_t alphaNumLen = 0;
  2127. for (char c : legacyType) {
  2128. if (c == '_' || c == '/' || c == '-') {
  2129. if (alphaNumLen == 0) {
  2130. return false;
  2131. }
  2132. alphaNumLen = 0;
  2133. } else if (UPRV_ISALPHANUM(c)) {
  2134. alphaNumLen++;
  2135. } else {
  2136. return false;
  2137. }
  2138. }
  2139. return alphaNumLen != 0;
  2140. }
  2141. } // namespace
  2142. U_CAPI const char* U_EXPORT2
  2143. uloc_toLegacyKey(const char* keyword)
  2144. {
  2145. if (keyword == nullptr || *keyword == '\0') { return nullptr; }
  2146. std::optional<std::string_view> result = ulocimp_toLegacyKeyWithFallback(keyword);
  2147. return result.has_value() ? result->data() : nullptr; // Known to be NUL terminated.
  2148. }
  2149. U_EXPORT std::optional<std::string_view>
  2150. ulocimp_toLegacyKeyWithFallback(std::string_view keyword)
  2151. {
  2152. std::optional<std::string_view> legacyKey = ulocimp_toLegacyKey(keyword);
  2153. if (!legacyKey.has_value() && isWellFormedLegacyKey(keyword)) {
  2154. // Checks if the specified locale key is well-formed with the legacy locale syntax.
  2155. //
  2156. // Note:
  2157. // LDML/CLDR provides some definition of keyword syntax in
  2158. // * http://www.unicode.org/reports/tr35/#Unicode_locale_identifier and
  2159. // * http://www.unicode.org/reports/tr35/#Old_Locale_Extension_Syntax
  2160. // Keys can only consist of [0-9a-zA-Z].
  2161. return keyword;
  2162. }
  2163. return legacyKey;
  2164. }
  2165. U_CAPI const char* U_EXPORT2
  2166. uloc_toLegacyType(const char* keyword, const char* value)
  2167. {
  2168. if (keyword == nullptr || *keyword == '\0' ||
  2169. value == nullptr || *value == '\0') { return nullptr; }
  2170. std::optional<std::string_view> result = ulocimp_toLegacyTypeWithFallback(keyword, value);
  2171. return result.has_value() ? result->data() : nullptr; // Known to be NUL terminated.
  2172. }
  2173. U_EXPORT std::optional<std::string_view>
  2174. ulocimp_toLegacyTypeWithFallback(std::string_view keyword, std::string_view value)
  2175. {
  2176. std::optional<std::string_view> legacyType = ulocimp_toLegacyType(keyword, value);
  2177. if (!legacyType.has_value() && isWellFormedLegacyType(value)) {
  2178. // Checks if the specified locale type is well-formed with the legacy locale syntax.
  2179. //
  2180. // Note:
  2181. // LDML/CLDR provides some definition of keyword syntax in
  2182. // * http://www.unicode.org/reports/tr35/#Unicode_locale_identifier and
  2183. // * http://www.unicode.org/reports/tr35/#Old_Locale_Extension_Syntax
  2184. // Values (types) can only consist of [0-9a-zA-Z], plus for legacy values
  2185. // we allow [/_-+] in the middle (e.g. "Etc/GMT+1", "Asia/Tel_Aviv")
  2186. return value;
  2187. }
  2188. return legacyType;
  2189. }
  2190. /*eof*/