uloc.cpp 77 KB

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