ucurr.cpp 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. **********************************************************************
  5. * Copyright (c) 2002-2016, International Business Machines
  6. * Corporation and others. All Rights Reserved.
  7. **********************************************************************
  8. */
  9. #include "unicode/utypes.h"
  10. #if !UCONFIG_NO_FORMATTING
  11. #include <utility>
  12. #include "unicode/ucurr.h"
  13. #include "unicode/locid.h"
  14. #include "unicode/ures.h"
  15. #include "unicode/ustring.h"
  16. #include "unicode/parsepos.h"
  17. #include "unicode/uniset.h"
  18. #include "unicode/usetiter.h"
  19. #include "unicode/utf16.h"
  20. #include "ustr_imp.h"
  21. #include "charstr.h"
  22. #include "cmemory.h"
  23. #include "cstring.h"
  24. #include "static_unicode_sets.h"
  25. #include "uassert.h"
  26. #include "umutex.h"
  27. #include "ucln_cmn.h"
  28. #include "uenumimp.h"
  29. #include "uhash.h"
  30. #include "hash.h"
  31. #include "uinvchar.h"
  32. #include "uresimp.h"
  33. #include "ulist.h"
  34. #include "uresimp.h"
  35. #include "ureslocs.h"
  36. #include "ulocimp.h"
  37. using namespace icu;
  38. //#define UCURR_DEBUG_EQUIV 1
  39. #ifdef UCURR_DEBUG_EQUIV
  40. #include "stdio.h"
  41. #endif
  42. //#define UCURR_DEBUG 1
  43. #ifdef UCURR_DEBUG
  44. #include "stdio.h"
  45. #endif
  46. typedef struct IsoCodeEntry {
  47. const char16_t *isoCode; /* const because it's a reference to a resource bundle string. */
  48. UDate from;
  49. UDate to;
  50. } IsoCodeEntry;
  51. //------------------------------------------------------------
  52. // Constants
  53. // Default currency meta data of last resort. We try to use the
  54. // defaults encoded in the meta data resource bundle. If there is a
  55. // configuration/build error and these are not available, we use these
  56. // hard-coded defaults (which should be identical).
  57. static const int32_t LAST_RESORT_DATA[] = { 2, 0, 2, 0 };
  58. // POW10[i] = 10^i, i=0..MAX_POW10
  59. static const int32_t POW10[] = { 1, 10, 100, 1000, 10000, 100000,
  60. 1000000, 10000000, 100000000, 1000000000 };
  61. static const int32_t MAX_POW10 = UPRV_LENGTHOF(POW10) - 1;
  62. #define ISO_CURRENCY_CODE_LENGTH 3
  63. //------------------------------------------------------------
  64. // Resource tags
  65. //
  66. static const char CURRENCY_DATA[] = "supplementalData";
  67. // Tag for meta-data, in root.
  68. static const char CURRENCY_META[] = "CurrencyMeta";
  69. // Tag for map from countries to currencies, in root.
  70. static const char CURRENCY_MAP[] = "CurrencyMap";
  71. // Tag for default meta-data, in CURRENCY_META
  72. static const char DEFAULT_META[] = "DEFAULT";
  73. // Variant delimiter
  74. static const char VAR_DELIM = '_';
  75. // Tag for localized display names (symbols) of currencies
  76. static const char CURRENCIES[] = "Currencies";
  77. static const char CURRENCIES_NARROW[] = "Currencies%narrow";
  78. static const char CURRENCIES_FORMAL[] = "Currencies%formal";
  79. static const char CURRENCIES_VARIANT[] = "Currencies%variant";
  80. static const char CURRENCYPLURALS[] = "CurrencyPlurals";
  81. // ISO codes mapping table
  82. static const UHashtable* gIsoCodes = nullptr;
  83. static icu::UInitOnce gIsoCodesInitOnce {};
  84. // Currency symbol equivalances
  85. static const icu::Hashtable* gCurrSymbolsEquiv = nullptr;
  86. static icu::UInitOnce gCurrSymbolsEquivInitOnce {};
  87. U_NAMESPACE_BEGIN
  88. // EquivIterator iterates over all strings that are equivalent to a given
  89. // string, s. Note that EquivIterator will never yield s itself.
  90. class EquivIterator : public icu::UMemory {
  91. public:
  92. // Constructor. hash stores the equivalence relationships; s is the string
  93. // for which we find equivalent strings.
  94. inline EquivIterator(const icu::Hashtable& hash, const icu::UnicodeString& s)
  95. : _hash(hash) {
  96. _start = _current = &s;
  97. }
  98. inline ~EquivIterator() { }
  99. // next returns the next equivalent string or nullptr if there are no more.
  100. // If s has no equivalent strings, next returns nullptr on the first call.
  101. const icu::UnicodeString *next();
  102. private:
  103. const icu::Hashtable& _hash;
  104. const icu::UnicodeString* _start;
  105. const icu::UnicodeString* _current;
  106. };
  107. const icu::UnicodeString *
  108. EquivIterator::next() {
  109. const icu::UnicodeString* _next = static_cast<const icu::UnicodeString*>(_hash.get(*_current));
  110. if (_next == nullptr) {
  111. U_ASSERT(_current == _start);
  112. return nullptr;
  113. }
  114. if (*_next == *_start) {
  115. return nullptr;
  116. }
  117. _current = _next;
  118. return _next;
  119. }
  120. U_NAMESPACE_END
  121. // makeEquivalent makes lhs and rhs equivalent by updating the equivalence
  122. // relations in hash accordingly.
  123. static void makeEquivalent(
  124. const icu::UnicodeString &lhs,
  125. const icu::UnicodeString &rhs,
  126. icu::Hashtable* hash, UErrorCode &status) {
  127. if (U_FAILURE(status)) {
  128. return;
  129. }
  130. if (lhs == rhs) {
  131. // already equivalent
  132. return;
  133. }
  134. icu::EquivIterator leftIter(*hash, lhs);
  135. icu::EquivIterator rightIter(*hash, rhs);
  136. const icu::UnicodeString *firstLeft = leftIter.next();
  137. const icu::UnicodeString *firstRight = rightIter.next();
  138. const icu::UnicodeString *nextLeft = firstLeft;
  139. const icu::UnicodeString *nextRight = firstRight;
  140. while (nextLeft != nullptr && nextRight != nullptr) {
  141. if (*nextLeft == rhs || *nextRight == lhs) {
  142. // Already equivalent
  143. return;
  144. }
  145. nextLeft = leftIter.next();
  146. nextRight = rightIter.next();
  147. }
  148. // Not equivalent. Must join.
  149. icu::UnicodeString *newFirstLeft;
  150. icu::UnicodeString *newFirstRight;
  151. if (firstRight == nullptr && firstLeft == nullptr) {
  152. // Neither lhs or rhs belong to an equivalence circle, so we form
  153. // a new equivalnce circle of just lhs and rhs.
  154. newFirstLeft = new icu::UnicodeString(rhs);
  155. newFirstRight = new icu::UnicodeString(lhs);
  156. } else if (firstRight == nullptr) {
  157. // lhs belongs to an equivalence circle, but rhs does not, so we link
  158. // rhs into lhs' circle.
  159. newFirstLeft = new icu::UnicodeString(rhs);
  160. newFirstRight = new icu::UnicodeString(*firstLeft);
  161. } else if (firstLeft == nullptr) {
  162. // rhs belongs to an equivlance circle, but lhs does not, so we link
  163. // lhs into rhs' circle.
  164. newFirstLeft = new icu::UnicodeString(*firstRight);
  165. newFirstRight = new icu::UnicodeString(lhs);
  166. } else {
  167. // Both lhs and rhs belong to different equivalnce circles. We link
  168. // them together to form one single, larger equivalnce circle.
  169. newFirstLeft = new icu::UnicodeString(*firstRight);
  170. newFirstRight = new icu::UnicodeString(*firstLeft);
  171. }
  172. if (newFirstLeft == nullptr || newFirstRight == nullptr) {
  173. delete newFirstLeft;
  174. delete newFirstRight;
  175. status = U_MEMORY_ALLOCATION_ERROR;
  176. return;
  177. }
  178. hash->put(lhs, (void *) newFirstLeft, status);
  179. hash->put(rhs, (void *) newFirstRight, status);
  180. }
  181. // countEquivalent counts how many strings are equivalent to s.
  182. // hash stores all the equivalnce relations.
  183. // countEquivalent does not include s itself in the count.
  184. static int32_t countEquivalent(const icu::Hashtable &hash, const icu::UnicodeString &s) {
  185. int32_t result = 0;
  186. icu::EquivIterator iter(hash, s);
  187. while (iter.next() != nullptr) {
  188. ++result;
  189. }
  190. #ifdef UCURR_DEBUG_EQUIV
  191. {
  192. char tmp[200];
  193. s.extract(0,s.length(),tmp, "UTF-8");
  194. printf("CountEquivalent('%s') = %d\n", tmp, result);
  195. }
  196. #endif
  197. return result;
  198. }
  199. static const icu::Hashtable* getCurrSymbolsEquiv();
  200. //------------------------------------------------------------
  201. // Code
  202. /**
  203. * Cleanup callback func
  204. */
  205. static UBool U_CALLCONV
  206. isoCodes_cleanup()
  207. {
  208. if (gIsoCodes != nullptr) {
  209. uhash_close(const_cast<UHashtable *>(gIsoCodes));
  210. gIsoCodes = nullptr;
  211. }
  212. gIsoCodesInitOnce.reset();
  213. return true;
  214. }
  215. /**
  216. * Cleanup callback func
  217. */
  218. static UBool U_CALLCONV
  219. currSymbolsEquiv_cleanup()
  220. {
  221. delete const_cast<icu::Hashtable *>(gCurrSymbolsEquiv);
  222. gCurrSymbolsEquiv = nullptr;
  223. gCurrSymbolsEquivInitOnce.reset();
  224. return true;
  225. }
  226. /**
  227. * Deleter for IsoCodeEntry
  228. */
  229. static void U_CALLCONV
  230. deleteIsoCodeEntry(void *obj) {
  231. IsoCodeEntry* entry = static_cast<IsoCodeEntry*>(obj);
  232. uprv_free(entry);
  233. }
  234. /**
  235. * Deleter for gCurrSymbolsEquiv.
  236. */
  237. static void U_CALLCONV
  238. deleteUnicode(void *obj) {
  239. icu::UnicodeString* entry = static_cast<icu::UnicodeString*>(obj);
  240. delete entry;
  241. }
  242. /**
  243. * Unfortunately, we have to convert the char16_t* currency code to char*
  244. * to use it as a resource key.
  245. */
  246. static inline char*
  247. myUCharsToChars(char* resultOfLen4, const char16_t* currency) {
  248. u_UCharsToChars(currency, resultOfLen4, ISO_CURRENCY_CODE_LENGTH);
  249. resultOfLen4[ISO_CURRENCY_CODE_LENGTH] = 0;
  250. return resultOfLen4;
  251. }
  252. /**
  253. * Internal function to look up currency data. Result is an array of
  254. * four integers. The first is the fraction digits. The second is the
  255. * rounding increment, or 0 if none. The rounding increment is in
  256. * units of 10^(-fraction_digits). The third and fourth are the same
  257. * except that they are those used in cash transactions ( cashDigits
  258. * and cashRounding ).
  259. */
  260. static const int32_t*
  261. _findMetaData(const char16_t* currency, UErrorCode& ec) {
  262. if (currency == nullptr || *currency == 0) {
  263. if (U_SUCCESS(ec)) {
  264. ec = U_ILLEGAL_ARGUMENT_ERROR;
  265. }
  266. return LAST_RESORT_DATA;
  267. }
  268. // Get CurrencyMeta resource out of root locale file. [This may
  269. // move out of the root locale file later; if it does, update this
  270. // code.]
  271. UResourceBundle* currencyData = ures_openDirect(U_ICUDATA_CURR, CURRENCY_DATA, &ec);
  272. LocalUResourceBundlePointer currencyMeta(ures_getByKey(currencyData, CURRENCY_META, currencyData, &ec));
  273. if (U_FAILURE(ec)) {
  274. // Config/build error; return hard-coded defaults
  275. return LAST_RESORT_DATA;
  276. }
  277. // Look up our currency, or if that's not available, then DEFAULT
  278. char buf[ISO_CURRENCY_CODE_LENGTH+1];
  279. UErrorCode ec2 = U_ZERO_ERROR; // local error code: soft failure
  280. LocalUResourceBundlePointer rb(ures_getByKey(currencyMeta.getAlias(), myUCharsToChars(buf, currency), nullptr, &ec2));
  281. if (U_FAILURE(ec2)) {
  282. rb.adoptInstead(ures_getByKey(currencyMeta.getAlias(),DEFAULT_META, nullptr, &ec));
  283. if (U_FAILURE(ec)) {
  284. // Config/build error; return hard-coded defaults
  285. return LAST_RESORT_DATA;
  286. }
  287. }
  288. int32_t len;
  289. const int32_t *data = ures_getIntVector(rb.getAlias(), &len, &ec);
  290. if (U_FAILURE(ec) || len != 4) {
  291. // Config/build error; return hard-coded defaults
  292. if (U_SUCCESS(ec)) {
  293. ec = U_INVALID_FORMAT_ERROR;
  294. }
  295. return LAST_RESORT_DATA;
  296. }
  297. return data;
  298. }
  299. // -------------------------------------
  300. static CharString
  301. idForLocale(const char* locale, UErrorCode* ec)
  302. {
  303. return ulocimp_getRegionForSupplementalData(locale, false, *ec);
  304. }
  305. // ------------------------------------------
  306. //
  307. // Registration
  308. //
  309. //-------------------------------------------
  310. // don't use ICUService since we don't need fallback
  311. U_CDECL_BEGIN
  312. static UBool U_CALLCONV currency_cleanup();
  313. U_CDECL_END
  314. #if !UCONFIG_NO_SERVICE
  315. struct CReg;
  316. static UMutex gCRegLock;
  317. static CReg* gCRegHead = nullptr;
  318. struct CReg : public icu::UMemory {
  319. CReg *next;
  320. char16_t iso[ISO_CURRENCY_CODE_LENGTH+1];
  321. char id[ULOC_FULLNAME_CAPACITY];
  322. CReg(const char16_t* _iso, const char* _id)
  323. : next(nullptr)
  324. {
  325. int32_t len = static_cast<int32_t>(uprv_strlen(_id));
  326. if (len > static_cast<int32_t>(sizeof(id) - 1)) {
  327. len = (sizeof(id)-1);
  328. }
  329. uprv_strncpy(id, _id, len);
  330. id[len] = 0;
  331. u_memcpy(iso, _iso, ISO_CURRENCY_CODE_LENGTH);
  332. iso[ISO_CURRENCY_CODE_LENGTH] = 0;
  333. }
  334. static UCurrRegistryKey reg(const char16_t* _iso, const char* _id, UErrorCode* status)
  335. {
  336. if (status && U_SUCCESS(*status) && _iso && _id) {
  337. CReg* n = new CReg(_iso, _id);
  338. if (n) {
  339. umtx_lock(&gCRegLock);
  340. if (!gCRegHead) {
  341. /* register for the first time */
  342. ucln_common_registerCleanup(UCLN_COMMON_CURRENCY, currency_cleanup);
  343. }
  344. n->next = gCRegHead;
  345. gCRegHead = n;
  346. umtx_unlock(&gCRegLock);
  347. return n;
  348. }
  349. *status = U_MEMORY_ALLOCATION_ERROR;
  350. }
  351. return nullptr;
  352. }
  353. static UBool unreg(UCurrRegistryKey key) {
  354. UBool found = false;
  355. umtx_lock(&gCRegLock);
  356. CReg** p = &gCRegHead;
  357. while (*p) {
  358. if (*p == key) {
  359. *p = ((CReg*)key)->next;
  360. delete (CReg*)key;
  361. found = true;
  362. break;
  363. }
  364. p = &((*p)->next);
  365. }
  366. umtx_unlock(&gCRegLock);
  367. return found;
  368. }
  369. static const char16_t* get(const char* id) {
  370. const char16_t* result = nullptr;
  371. umtx_lock(&gCRegLock);
  372. CReg* p = gCRegHead;
  373. /* register cleanup of the mutex */
  374. ucln_common_registerCleanup(UCLN_COMMON_CURRENCY, currency_cleanup);
  375. while (p) {
  376. if (uprv_strcmp(id, p->id) == 0) {
  377. result = p->iso;
  378. break;
  379. }
  380. p = p->next;
  381. }
  382. umtx_unlock(&gCRegLock);
  383. return result;
  384. }
  385. /* This doesn't need to be thread safe. It's for u_cleanup only. */
  386. static void cleanup() {
  387. while (gCRegHead) {
  388. CReg* n = gCRegHead;
  389. gCRegHead = gCRegHead->next;
  390. delete n;
  391. }
  392. }
  393. };
  394. // -------------------------------------
  395. U_CAPI UCurrRegistryKey U_EXPORT2
  396. ucurr_register(const char16_t* isoCode, const char* locale, UErrorCode *status)
  397. {
  398. if (status && U_SUCCESS(*status)) {
  399. CharString id = idForLocale(locale, status);
  400. return CReg::reg(isoCode, id.data(), status);
  401. }
  402. return nullptr;
  403. }
  404. // -------------------------------------
  405. U_CAPI UBool U_EXPORT2
  406. ucurr_unregister(UCurrRegistryKey key, UErrorCode* status)
  407. {
  408. if (status && U_SUCCESS(*status)) {
  409. return CReg::unreg(key);
  410. }
  411. return false;
  412. }
  413. #endif /* UCONFIG_NO_SERVICE */
  414. // -------------------------------------
  415. /**
  416. * Release all static memory held by currency.
  417. */
  418. /*The declaration here is needed so currency_cleanup()
  419. * can call this function.
  420. */
  421. static UBool U_CALLCONV
  422. currency_cache_cleanup();
  423. U_CDECL_BEGIN
  424. static UBool U_CALLCONV currency_cleanup() {
  425. #if !UCONFIG_NO_SERVICE
  426. CReg::cleanup();
  427. #endif
  428. /*
  429. * There might be some cached currency data or isoCodes data.
  430. */
  431. currency_cache_cleanup();
  432. isoCodes_cleanup();
  433. currSymbolsEquiv_cleanup();
  434. return true;
  435. }
  436. U_CDECL_END
  437. // -------------------------------------
  438. U_CAPI int32_t U_EXPORT2
  439. ucurr_forLocale(const char* locale,
  440. char16_t* buff,
  441. int32_t buffCapacity,
  442. UErrorCode* ec) {
  443. if (U_FAILURE(*ec)) { return 0; }
  444. if (buffCapacity < 0 || (buff == nullptr && buffCapacity > 0)) {
  445. *ec = U_ILLEGAL_ARGUMENT_ERROR;
  446. return 0;
  447. }
  448. UErrorCode localStatus = U_ZERO_ERROR;
  449. CharString currency = ulocimp_getKeywordValue(locale, "currency", localStatus);
  450. int32_t resLen = currency.length();
  451. if (U_SUCCESS(localStatus) && resLen == 3 && uprv_isInvariantString(currency.data(), resLen)) {
  452. if (resLen < buffCapacity) {
  453. T_CString_toUpperCase(currency.data());
  454. u_charsToUChars(currency.data(), buff, resLen);
  455. }
  456. return u_terminateUChars(buff, buffCapacity, resLen, ec);
  457. }
  458. // get country or country_variant in `id'
  459. CharString id = idForLocale(locale, ec);
  460. if (U_FAILURE(*ec)) {
  461. return 0;
  462. }
  463. #if !UCONFIG_NO_SERVICE
  464. const char16_t* result = CReg::get(id.data());
  465. if (result) {
  466. if(buffCapacity > u_strlen(result)) {
  467. u_strcpy(buff, result);
  468. }
  469. resLen = u_strlen(result);
  470. return u_terminateUChars(buff, buffCapacity, resLen, ec);
  471. }
  472. #endif
  473. // Remove variants, which is only needed for registration.
  474. char *idDelim = uprv_strchr(id.data(), VAR_DELIM);
  475. if (idDelim) {
  476. id.truncate(idDelim - id.data());
  477. }
  478. const char16_t* s = nullptr; // Currency code from data file.
  479. if (id.isEmpty()) {
  480. // No point looking in the data for an empty string.
  481. // This is what we would get.
  482. localStatus = U_MISSING_RESOURCE_ERROR;
  483. } else {
  484. // Look up the CurrencyMap element in the root bundle.
  485. localStatus = U_ZERO_ERROR;
  486. UResourceBundle *rb = ures_openDirect(U_ICUDATA_CURR, CURRENCY_DATA, &localStatus);
  487. UResourceBundle *cm = ures_getByKey(rb, CURRENCY_MAP, rb, &localStatus);
  488. LocalUResourceBundlePointer countryArray(ures_getByKey(rb, id.data(), cm, &localStatus));
  489. // https://unicode-org.atlassian.net/browse/ICU-21997
  490. // Prefer to use currencies that are legal tender.
  491. if (U_SUCCESS(localStatus)) {
  492. int32_t arrayLength = ures_getSize(countryArray.getAlias());
  493. for (int32_t i = 0; i < arrayLength; ++i) {
  494. LocalUResourceBundlePointer currencyReq(
  495. ures_getByIndex(countryArray.getAlias(), i, nullptr, &localStatus));
  496. // The currency is legal tender if it is *not* marked with tender{"false"}.
  497. UErrorCode tenderStatus = localStatus;
  498. const char16_t *tender =
  499. ures_getStringByKey(currencyReq.getAlias(), "tender", nullptr, &tenderStatus);
  500. bool isTender = U_FAILURE(tenderStatus) || u_strcmp(tender, u"false") != 0;
  501. if (!isTender && s != nullptr) {
  502. // We already have a non-tender currency. Ignore all following non-tender ones.
  503. continue;
  504. }
  505. // Fetch the currency code.
  506. s = ures_getStringByKey(currencyReq.getAlias(), "id", &resLen, &localStatus);
  507. if (isTender) {
  508. break;
  509. }
  510. }
  511. if (U_SUCCESS(localStatus) && s == nullptr) {
  512. localStatus = U_MISSING_RESOURCE_ERROR;
  513. }
  514. }
  515. }
  516. if ((U_FAILURE(localStatus)) && strchr(id.data(), '_') != nullptr) {
  517. // We don't know about it. Check to see if we support the variant.
  518. CharString parent = ulocimp_getParent(locale, *ec);
  519. *ec = U_USING_FALLBACK_WARNING;
  520. // TODO: Loop over the parent rather than recursing and
  521. // looking again for a currency keyword.
  522. return ucurr_forLocale(parent.data(), buff, buffCapacity, ec);
  523. }
  524. if (*ec == U_ZERO_ERROR || localStatus != U_ZERO_ERROR) {
  525. // There is nothing to fallback to. Report the failure/warning if possible.
  526. *ec = localStatus;
  527. }
  528. if (U_SUCCESS(*ec)) {
  529. if(buffCapacity > resLen) {
  530. u_strcpy(buff, s);
  531. }
  532. }
  533. return u_terminateUChars(buff, buffCapacity, resLen, ec);
  534. }
  535. // end registration
  536. /**
  537. * Modify the given locale name by removing the rightmost _-delimited
  538. * element. If there is none, empty the string ("" == root).
  539. * NOTE: The string "root" is not recognized; do not use it.
  540. * @return true if the fallback happened; false if locale is already
  541. * root ("").
  542. */
  543. static UBool fallback(CharString& loc) {
  544. if (loc.isEmpty()) {
  545. return false;
  546. }
  547. UErrorCode status = U_ZERO_ERROR;
  548. if (loc == "en_GB") {
  549. // HACK: See #13368. We need "en_GB" to fall back to "en_001" instead of "en"
  550. // in order to consume the correct data strings. This hack will be removed
  551. // when proper data sink loading is implemented here.
  552. loc.truncate(3);
  553. loc.append("001", status);
  554. } else {
  555. loc = ulocimp_getParent(loc.data(), status);
  556. }
  557. /*
  558. char *i = uprv_strrchr(loc, '_');
  559. if (i == nullptr) {
  560. i = loc;
  561. }
  562. *i = 0;
  563. */
  564. return true;
  565. }
  566. U_CAPI const char16_t* U_EXPORT2
  567. ucurr_getName(const char16_t* currency,
  568. const char* locale,
  569. UCurrNameStyle nameStyle,
  570. UBool* isChoiceFormat, // fillin
  571. int32_t* len, // fillin
  572. UErrorCode* ec) {
  573. // Look up the Currencies resource for the given locale. The
  574. // Currencies locale data looks like this:
  575. //|en {
  576. //| Currencies {
  577. //| USD { "US$", "US Dollar" }
  578. //| CHF { "Sw F", "Swiss Franc" }
  579. //| INR { "=0#Rs|1#Re|1<Rs", "=0#Rupees|1#Rupee|1<Rupees" }
  580. //| //...
  581. //| }
  582. //|}
  583. if (U_FAILURE(*ec)) {
  584. return nullptr;
  585. }
  586. int32_t choice = (int32_t) nameStyle;
  587. if (choice < 0 || choice > 4) {
  588. *ec = U_ILLEGAL_ARGUMENT_ERROR;
  589. return nullptr;
  590. }
  591. // In the future, resource bundles may implement multi-level
  592. // fallback. That is, if a currency is not found in the en_US
  593. // Currencies data, then the en Currencies data will be searched.
  594. // Currently, if a Currencies datum exists in en_US and en, the
  595. // en_US entry hides that in en.
  596. // We want multi-level fallback for this resource, so we implement
  597. // it manually.
  598. // Use a separate UErrorCode here that does not propagate out of
  599. // this function.
  600. UErrorCode ec2 = U_ZERO_ERROR;
  601. CharString loc = ulocimp_getName(locale, ec2);
  602. if (U_FAILURE(ec2)) {
  603. *ec = U_ILLEGAL_ARGUMENT_ERROR;
  604. return nullptr;
  605. }
  606. char buf[ISO_CURRENCY_CODE_LENGTH+1];
  607. myUCharsToChars(buf, currency);
  608. /* Normalize the keyword value to uppercase */
  609. T_CString_toUpperCase(buf);
  610. const char16_t* s = nullptr;
  611. ec2 = U_ZERO_ERROR;
  612. LocalUResourceBundlePointer rb(ures_open(U_ICUDATA_CURR, loc.data(), &ec2));
  613. if (nameStyle == UCURR_NARROW_SYMBOL_NAME || nameStyle == UCURR_FORMAL_SYMBOL_NAME || nameStyle == UCURR_VARIANT_SYMBOL_NAME) {
  614. CharString key;
  615. switch (nameStyle) {
  616. case UCURR_NARROW_SYMBOL_NAME:
  617. key.append(CURRENCIES_NARROW, ec2);
  618. break;
  619. case UCURR_FORMAL_SYMBOL_NAME:
  620. key.append(CURRENCIES_FORMAL, ec2);
  621. break;
  622. case UCURR_VARIANT_SYMBOL_NAME:
  623. key.append(CURRENCIES_VARIANT, ec2);
  624. break;
  625. default:
  626. *ec = U_UNSUPPORTED_ERROR;
  627. return nullptr;
  628. }
  629. key.append("/", ec2);
  630. key.append(buf, ec2);
  631. s = ures_getStringByKeyWithFallback(rb.getAlias(), key.data(), len, &ec2);
  632. if (ec2 == U_MISSING_RESOURCE_ERROR) {
  633. *ec = U_USING_FALLBACK_WARNING;
  634. ec2 = U_ZERO_ERROR;
  635. choice = UCURR_SYMBOL_NAME;
  636. }
  637. }
  638. if (s == nullptr) {
  639. ures_getByKey(rb.getAlias(), CURRENCIES, rb.getAlias(), &ec2);
  640. ures_getByKeyWithFallback(rb.getAlias(), buf, rb.getAlias(), &ec2);
  641. s = ures_getStringByIndex(rb.getAlias(), choice, len, &ec2);
  642. }
  643. // If we've succeeded we're done. Otherwise, try to fallback.
  644. // If that fails (because we are already at root) then exit.
  645. if (U_SUCCESS(ec2)) {
  646. if (ec2 == U_USING_DEFAULT_WARNING
  647. || (ec2 == U_USING_FALLBACK_WARNING && *ec != U_USING_DEFAULT_WARNING)) {
  648. *ec = ec2;
  649. }
  650. }
  651. // We no longer support choice format data in names. Data should not contain
  652. // choice patterns.
  653. if (isChoiceFormat != nullptr) {
  654. *isChoiceFormat = false;
  655. }
  656. if (U_SUCCESS(ec2)) {
  657. U_ASSERT(s != nullptr);
  658. return s;
  659. }
  660. // If we fail to find a match, use the ISO 4217 code
  661. *len = u_strlen(currency); // Should == ISO_CURRENCY_CODE_LENGTH, but maybe not...?
  662. *ec = U_USING_DEFAULT_WARNING;
  663. return currency;
  664. }
  665. U_CAPI const char16_t* U_EXPORT2
  666. ucurr_getPluralName(const char16_t* currency,
  667. const char* locale,
  668. UBool* isChoiceFormat,
  669. const char* pluralCount,
  670. int32_t* len, // fillin
  671. UErrorCode* ec) {
  672. // Look up the Currencies resource for the given locale. The
  673. // Currencies locale data looks like this:
  674. //|en {
  675. //| CurrencyPlurals {
  676. //| USD{
  677. //| one{"US dollar"}
  678. //| other{"US dollars"}
  679. //| }
  680. //| }
  681. //|}
  682. if (U_FAILURE(*ec)) {
  683. return nullptr;
  684. }
  685. // Use a separate UErrorCode here that does not propagate out of
  686. // this function.
  687. UErrorCode ec2 = U_ZERO_ERROR;
  688. CharString loc = ulocimp_getName(locale, ec2);
  689. if (U_FAILURE(ec2)) {
  690. *ec = U_ILLEGAL_ARGUMENT_ERROR;
  691. return nullptr;
  692. }
  693. char buf[ISO_CURRENCY_CODE_LENGTH+1];
  694. myUCharsToChars(buf, currency);
  695. const char16_t* s = nullptr;
  696. ec2 = U_ZERO_ERROR;
  697. UResourceBundle* rb = ures_open(U_ICUDATA_CURR, loc.data(), &ec2);
  698. rb = ures_getByKey(rb, CURRENCYPLURALS, rb, &ec2);
  699. // Fetch resource with multi-level resource inheritance fallback
  700. LocalUResourceBundlePointer curr(ures_getByKeyWithFallback(rb, buf, rb, &ec2));
  701. s = ures_getStringByKeyWithFallback(curr.getAlias(), pluralCount, len, &ec2);
  702. if (U_FAILURE(ec2)) {
  703. // fall back to "other"
  704. ec2 = U_ZERO_ERROR;
  705. s = ures_getStringByKeyWithFallback(curr.getAlias(), "other", len, &ec2);
  706. if (U_FAILURE(ec2)) {
  707. // fall back to long name in Currencies
  708. return ucurr_getName(currency, locale, UCURR_LONG_NAME,
  709. isChoiceFormat, len, ec);
  710. }
  711. }
  712. // If we've succeeded we're done. Otherwise, try to fallback.
  713. // If that fails (because we are already at root) then exit.
  714. if (U_SUCCESS(ec2)) {
  715. if (ec2 == U_USING_DEFAULT_WARNING
  716. || (ec2 == U_USING_FALLBACK_WARNING && *ec != U_USING_DEFAULT_WARNING)) {
  717. *ec = ec2;
  718. }
  719. U_ASSERT(s != nullptr);
  720. return s;
  721. }
  722. // If we fail to find a match, use the ISO 4217 code
  723. *len = u_strlen(currency); // Should == ISO_CURRENCY_CODE_LENGTH, but maybe not...?
  724. *ec = U_USING_DEFAULT_WARNING;
  725. return currency;
  726. }
  727. //========================================================================
  728. // Following are structure and function for parsing currency names
  729. #define NEED_TO_BE_DELETED 0x1
  730. // TODO: a better way to define this?
  731. #define MAX_CURRENCY_NAME_LEN 100
  732. typedef struct {
  733. const char* IsoCode; // key
  734. char16_t* currencyName; // value
  735. int32_t currencyNameLen; // value length
  736. int32_t flag; // flags
  737. } CurrencyNameStruct;
  738. #ifndef MIN
  739. #define MIN(a,b) (((a)<(b)) ? (a) : (b))
  740. #endif
  741. #ifndef MAX
  742. #define MAX(a,b) (((a)<(b)) ? (b) : (a))
  743. #endif
  744. // Comparison function used in quick sort.
  745. static int U_CALLCONV currencyNameComparator(const void* a, const void* b) {
  746. const CurrencyNameStruct* currName_1 = static_cast<const CurrencyNameStruct*>(a);
  747. const CurrencyNameStruct* currName_2 = static_cast<const CurrencyNameStruct*>(b);
  748. for (int32_t i = 0;
  749. i < MIN(currName_1->currencyNameLen, currName_2->currencyNameLen);
  750. ++i) {
  751. if (currName_1->currencyName[i] < currName_2->currencyName[i]) {
  752. return -1;
  753. }
  754. if (currName_1->currencyName[i] > currName_2->currencyName[i]) {
  755. return 1;
  756. }
  757. }
  758. if (currName_1->currencyNameLen < currName_2->currencyNameLen) {
  759. return -1;
  760. } else if (currName_1->currencyNameLen > currName_2->currencyNameLen) {
  761. return 1;
  762. }
  763. return 0;
  764. }
  765. // Give a locale, return the maximum number of currency names associated with
  766. // this locale.
  767. // It gets currency names from resource bundles using fallback.
  768. // It is the maximum number because in the fallback chain, some of the
  769. // currency names are duplicated.
  770. // For example, given locale as "en_US", the currency names get from resource
  771. // bundle in "en_US" and "en" are duplicated. The fallback mechanism will count
  772. // all currency names in "en_US" and "en".
  773. static void
  774. getCurrencyNameCount(const char* loc, int32_t* total_currency_name_count, int32_t* total_currency_symbol_count) {
  775. U_NAMESPACE_USE
  776. *total_currency_name_count = 0;
  777. *total_currency_symbol_count = 0;
  778. const char16_t* s = nullptr;
  779. CharString locale;
  780. {
  781. UErrorCode status = U_ZERO_ERROR;
  782. locale.append(loc, status);
  783. if (U_FAILURE(status)) { return; }
  784. }
  785. const icu::Hashtable *currencySymbolsEquiv = getCurrSymbolsEquiv();
  786. for (;;) {
  787. UErrorCode ec2 = U_ZERO_ERROR;
  788. // TODO: ures_openDirect?
  789. LocalUResourceBundlePointer rb(ures_open(U_ICUDATA_CURR, locale.data(), &ec2));
  790. LocalUResourceBundlePointer curr(ures_getByKey(rb.getAlias(), CURRENCIES, nullptr, &ec2));
  791. int32_t n = ures_getSize(curr.getAlias());
  792. for (int32_t i=0; i<n; ++i) {
  793. LocalUResourceBundlePointer names(ures_getByIndex(curr.getAlias(), i, nullptr, &ec2));
  794. int32_t len;
  795. s = ures_getStringByIndex(names.getAlias(), UCURR_SYMBOL_NAME, &len, &ec2);
  796. ++(*total_currency_symbol_count); // currency symbol
  797. if (currencySymbolsEquiv != nullptr) {
  798. *total_currency_symbol_count += countEquivalent(*currencySymbolsEquiv, UnicodeString(true, s, len));
  799. }
  800. ++(*total_currency_symbol_count); // iso code
  801. ++(*total_currency_name_count); // long name
  802. }
  803. // currency plurals
  804. UErrorCode ec3 = U_ZERO_ERROR;
  805. LocalUResourceBundlePointer curr_p(ures_getByKey(rb.getAlias(), CURRENCYPLURALS, nullptr, &ec3));
  806. n = ures_getSize(curr_p.getAlias());
  807. for (int32_t i=0; i<n; ++i) {
  808. LocalUResourceBundlePointer names(ures_getByIndex(curr_p.getAlias(), i, nullptr, &ec3));
  809. *total_currency_name_count += ures_getSize(names.getAlias());
  810. }
  811. if (!fallback(locale)) {
  812. break;
  813. }
  814. }
  815. }
  816. static char16_t*
  817. toUpperCase(const char16_t* source, int32_t len, const char* locale) {
  818. char16_t* dest = nullptr;
  819. UErrorCode ec = U_ZERO_ERROR;
  820. int32_t destLen = u_strToUpper(dest, 0, source, len, locale, &ec);
  821. ec = U_ZERO_ERROR;
  822. dest = static_cast<char16_t*>(uprv_malloc(sizeof(char16_t) * MAX(destLen, len)));
  823. if (dest == nullptr) {
  824. return nullptr;
  825. }
  826. u_strToUpper(dest, destLen, source, len, locale, &ec);
  827. if (U_FAILURE(ec)) {
  828. u_memcpy(dest, source, len);
  829. }
  830. return dest;
  831. }
  832. static void deleteCurrencyNames(CurrencyNameStruct* currencyNames, int32_t count);
  833. // Collect all available currency names associated with the given locale
  834. // (enable fallback chain).
  835. // Read currenc names defined in resource bundle "Currencies" and
  836. // "CurrencyPlural", enable fallback chain.
  837. // return the malloc-ed currency name arrays and the total number of currency
  838. // names in the array.
  839. static void
  840. collectCurrencyNames(const char* locale,
  841. CurrencyNameStruct** currencyNames,
  842. int32_t* total_currency_name_count,
  843. CurrencyNameStruct** currencySymbols,
  844. int32_t* total_currency_symbol_count,
  845. UErrorCode& ec) {
  846. if (U_FAILURE(ec)) {
  847. *currencyNames = *currencySymbols = nullptr;
  848. *total_currency_name_count = *total_currency_symbol_count = 0;
  849. return;
  850. }
  851. U_NAMESPACE_USE
  852. const icu::Hashtable *currencySymbolsEquiv = getCurrSymbolsEquiv();
  853. // Look up the Currencies resource for the given locale.
  854. UErrorCode ec2 = U_ZERO_ERROR;
  855. CharString loc = ulocimp_getName(locale, ec2);
  856. if (U_FAILURE(ec2)) {
  857. ec = U_ILLEGAL_ARGUMENT_ERROR;
  858. *currencyNames = *currencySymbols = nullptr;
  859. *total_currency_name_count = *total_currency_symbol_count = 0;
  860. return;
  861. }
  862. // Get maximum currency name count first.
  863. getCurrencyNameCount(loc.data(), total_currency_name_count, total_currency_symbol_count);
  864. *currencyNames = static_cast<CurrencyNameStruct*>(
  865. uprv_malloc(sizeof(CurrencyNameStruct) * (*total_currency_name_count)));
  866. if(*currencyNames == nullptr) {
  867. *currencySymbols = nullptr;
  868. *total_currency_name_count = *total_currency_symbol_count = 0;
  869. ec = U_MEMORY_ALLOCATION_ERROR;
  870. return;
  871. }
  872. *currencySymbols = static_cast<CurrencyNameStruct*>(
  873. uprv_malloc(sizeof(CurrencyNameStruct) * (*total_currency_symbol_count)));
  874. if(*currencySymbols == nullptr) {
  875. uprv_free(*currencyNames);
  876. *currencyNames = nullptr;
  877. *total_currency_name_count = *total_currency_symbol_count = 0;
  878. ec = U_MEMORY_ALLOCATION_ERROR;
  879. return;
  880. }
  881. const char16_t* s = nullptr; // currency name
  882. char* iso = nullptr; // currency ISO code
  883. *total_currency_name_count = 0;
  884. *total_currency_symbol_count = 0;
  885. UErrorCode ec3 = U_ZERO_ERROR;
  886. UErrorCode ec4 = U_ZERO_ERROR;
  887. // Using hash to remove duplicates caused by locale fallback
  888. LocalUHashtablePointer currencyIsoCodes(uhash_open(uhash_hashChars, uhash_compareChars, nullptr, &ec3));
  889. LocalUHashtablePointer currencyPluralIsoCodes(uhash_open(uhash_hashChars, uhash_compareChars, nullptr, &ec4));
  890. for (int32_t localeLevel = 0; ; ++localeLevel) {
  891. ec2 = U_ZERO_ERROR;
  892. // TODO: ures_openDirect
  893. LocalUResourceBundlePointer rb(ures_open(U_ICUDATA_CURR, loc.data(), &ec2));
  894. LocalUResourceBundlePointer curr(ures_getByKey(rb.getAlias(), CURRENCIES, nullptr, &ec2));
  895. int32_t n = ures_getSize(curr.getAlias());
  896. for (int32_t i=0; i<n; ++i) {
  897. LocalUResourceBundlePointer names(ures_getByIndex(curr.getAlias(), i, nullptr, &ec2));
  898. int32_t len;
  899. s = ures_getStringByIndex(names.getAlias(), UCURR_SYMBOL_NAME, &len, &ec2);
  900. // TODO: uhash_put wont change key/value?
  901. iso = const_cast<char*>(ures_getKey(names.getAlias()));
  902. if (localeLevel != 0 && uhash_get(currencyIsoCodes.getAlias(), iso) != nullptr) {
  903. continue;
  904. }
  905. uhash_put(currencyIsoCodes.getAlias(), iso, iso, &ec3);
  906. // Add currency symbol.
  907. (*currencySymbols)[(*total_currency_symbol_count)++] = {iso, const_cast<char16_t*>(s), len, 0};
  908. // Add equivalent symbols
  909. if (currencySymbolsEquiv != nullptr) {
  910. UnicodeString str(true, s, len);
  911. icu::EquivIterator iter(*currencySymbolsEquiv, str);
  912. const UnicodeString *symbol;
  913. while ((symbol = iter.next()) != nullptr) {
  914. (*currencySymbols)[(*total_currency_symbol_count)++]
  915. = {iso, const_cast<char16_t*>(symbol->getBuffer()), symbol->length(), 0};
  916. }
  917. }
  918. // Add currency long name.
  919. s = ures_getStringByIndex(names.getAlias(), UCURR_LONG_NAME, &len, &ec2);
  920. char16_t* upperName = toUpperCase(s, len, locale);
  921. if (upperName == nullptr) {
  922. ec = U_MEMORY_ALLOCATION_ERROR;
  923. goto error;
  924. }
  925. (*currencyNames)[(*total_currency_name_count)++] = {iso, upperName, len, NEED_TO_BE_DELETED};
  926. // put (iso, 3, and iso) in to array
  927. // Add currency ISO code.
  928. char16_t* isoCode = static_cast<char16_t*>(uprv_malloc(sizeof(char16_t) * 3));
  929. if (isoCode == nullptr) {
  930. ec = U_MEMORY_ALLOCATION_ERROR;
  931. goto error;
  932. }
  933. // Must convert iso[] into Unicode
  934. u_charsToUChars(iso, isoCode, 3);
  935. (*currencySymbols)[(*total_currency_symbol_count)++] = {iso, isoCode, 3, NEED_TO_BE_DELETED};
  936. }
  937. // currency plurals
  938. UErrorCode ec5 = U_ZERO_ERROR;
  939. LocalUResourceBundlePointer curr_p(ures_getByKey(rb.getAlias(), CURRENCYPLURALS, nullptr, &ec5));
  940. n = ures_getSize(curr_p.getAlias());
  941. for (int32_t i=0; i<n; ++i) {
  942. LocalUResourceBundlePointer names(ures_getByIndex(curr_p.getAlias(), i, nullptr, &ec5));
  943. iso = const_cast<char*>(ures_getKey(names.getAlias()));
  944. // Using hash to remove duplicated ISO codes in fallback chain.
  945. if (localeLevel != 0 && uhash_get(currencyPluralIsoCodes.getAlias(), iso) != nullptr) {
  946. continue;
  947. }
  948. uhash_put(currencyPluralIsoCodes.getAlias(), iso, iso, &ec4);
  949. int32_t num = ures_getSize(names.getAlias());
  950. int32_t len;
  951. for (int32_t j = 0; j < num; ++j) {
  952. // TODO: remove duplicates between singular name and
  953. // currency long name?
  954. s = ures_getStringByIndex(names.getAlias(), j, &len, &ec5);
  955. char16_t* upperName = toUpperCase(s, len, locale);
  956. if (upperName == nullptr) {
  957. ec = U_MEMORY_ALLOCATION_ERROR;
  958. goto error;
  959. }
  960. (*currencyNames)[(*total_currency_name_count)++] = {iso, upperName, len, NEED_TO_BE_DELETED};
  961. }
  962. }
  963. if (!fallback(loc)) {
  964. break;
  965. }
  966. }
  967. // quick sort the struct
  968. qsort(*currencyNames, *total_currency_name_count,
  969. sizeof(CurrencyNameStruct), currencyNameComparator);
  970. qsort(*currencySymbols, *total_currency_symbol_count,
  971. sizeof(CurrencyNameStruct), currencyNameComparator);
  972. #ifdef UCURR_DEBUG
  973. printf("currency name count: %d\n", *total_currency_name_count);
  974. for (int32_t index = 0; index < *total_currency_name_count; ++index) {
  975. printf("index: %d\n", index);
  976. printf("iso: %s\n", (*currencyNames)[index].IsoCode);
  977. char curNameBuf[1024];
  978. memset(curNameBuf, 0, 1024);
  979. u_austrncpy(curNameBuf, (*currencyNames)[index].currencyName, (*currencyNames)[index].currencyNameLen);
  980. printf("currencyName: %s\n", curNameBuf);
  981. printf("len: %d\n", (*currencyNames)[index].currencyNameLen);
  982. }
  983. printf("currency symbol count: %d\n", *total_currency_symbol_count);
  984. for (int32_t index = 0; index < *total_currency_symbol_count; ++index) {
  985. printf("index: %d\n", index);
  986. printf("iso: %s\n", (*currencySymbols)[index].IsoCode);
  987. char curNameBuf[1024];
  988. memset(curNameBuf, 0, 1024);
  989. u_austrncpy(curNameBuf, (*currencySymbols)[index].currencyName, (*currencySymbols)[index].currencyNameLen);
  990. printf("currencySymbol: %s\n", curNameBuf);
  991. printf("len: %d\n", (*currencySymbols)[index].currencyNameLen);
  992. }
  993. #endif
  994. // fail on hashtable errors
  995. if (U_FAILURE(ec3)) {
  996. ec = ec3;
  997. } else if (U_FAILURE(ec4)) {
  998. ec = ec4;
  999. }
  1000. error:
  1001. // clean up if we got error
  1002. if (U_FAILURE(ec)) {
  1003. deleteCurrencyNames(*currencyNames, *total_currency_name_count);
  1004. deleteCurrencyNames(*currencySymbols, *total_currency_symbol_count);
  1005. *currencyNames = *currencySymbols = nullptr;
  1006. *total_currency_name_count = *total_currency_symbol_count = 0;
  1007. }
  1008. }
  1009. // @param currencyNames: currency names array
  1010. // @param indexInCurrencyNames: the index of the character in currency names
  1011. // array against which the comparison is done
  1012. // @param key: input text char to compare against
  1013. // @param begin(IN/OUT): the begin index of matching range in currency names array
  1014. // @param end(IN/OUT): the end index of matching range in currency names array.
  1015. static int32_t
  1016. binarySearch(const CurrencyNameStruct* currencyNames,
  1017. int32_t indexInCurrencyNames,
  1018. const char16_t key,
  1019. int32_t* begin, int32_t* end) {
  1020. #ifdef UCURR_DEBUG
  1021. printf("key = %x\n", key);
  1022. #endif
  1023. int32_t first = *begin;
  1024. int32_t last = *end;
  1025. while (first <= last) {
  1026. int32_t mid = (first + last) / 2; // compute mid point.
  1027. if (indexInCurrencyNames >= currencyNames[mid].currencyNameLen) {
  1028. first = mid + 1;
  1029. } else {
  1030. if (key > currencyNames[mid].currencyName[indexInCurrencyNames]) {
  1031. first = mid + 1;
  1032. }
  1033. else if (key < currencyNames[mid].currencyName[indexInCurrencyNames]) {
  1034. last = mid - 1;
  1035. }
  1036. else {
  1037. // Find a match, and looking for ranges
  1038. // Now do two more binary searches. First, on the left side for
  1039. // the greatest L such that CurrencyNameStruct[L] < key.
  1040. int32_t L = *begin;
  1041. int32_t R = mid;
  1042. #ifdef UCURR_DEBUG
  1043. printf("mid = %d\n", mid);
  1044. #endif
  1045. while (L < R) {
  1046. int32_t M = (L + R) / 2;
  1047. #ifdef UCURR_DEBUG
  1048. printf("L = %d, R = %d, M = %d\n", L, R, M);
  1049. #endif
  1050. if (indexInCurrencyNames >= currencyNames[M].currencyNameLen) {
  1051. L = M + 1;
  1052. } else {
  1053. if (currencyNames[M].currencyName[indexInCurrencyNames] < key) {
  1054. L = M + 1;
  1055. } else {
  1056. #ifdef UCURR_DEBUG
  1057. U_ASSERT(currencyNames[M].currencyName[indexInCurrencyNames] == key);
  1058. #endif
  1059. R = M;
  1060. }
  1061. }
  1062. }
  1063. #ifdef UCURR_DEBUG
  1064. U_ASSERT(L == R);
  1065. #endif
  1066. *begin = L;
  1067. #ifdef UCURR_DEBUG
  1068. printf("begin = %d\n", *begin);
  1069. U_ASSERT(currencyNames[*begin].currencyName[indexInCurrencyNames] == key);
  1070. #endif
  1071. // Now for the second search, finding the least R such that
  1072. // key < CurrencyNameStruct[R].
  1073. L = mid;
  1074. R = *end;
  1075. while (L < R) {
  1076. int32_t M = (L + R) / 2;
  1077. #ifdef UCURR_DEBUG
  1078. printf("L = %d, R = %d, M = %d\n", L, R, M);
  1079. #endif
  1080. if (currencyNames[M].currencyNameLen < indexInCurrencyNames) {
  1081. L = M + 1;
  1082. } else {
  1083. if (currencyNames[M].currencyName[indexInCurrencyNames] > key) {
  1084. R = M;
  1085. } else {
  1086. #ifdef UCURR_DEBUG
  1087. U_ASSERT(currencyNames[M].currencyName[indexInCurrencyNames] == key);
  1088. #endif
  1089. L = M + 1;
  1090. }
  1091. }
  1092. }
  1093. #ifdef UCURR_DEBUG
  1094. U_ASSERT(L == R);
  1095. #endif
  1096. if (currencyNames[R].currencyName[indexInCurrencyNames] > key) {
  1097. *end = R - 1;
  1098. } else {
  1099. *end = R;
  1100. }
  1101. #ifdef UCURR_DEBUG
  1102. printf("end = %d\n", *end);
  1103. #endif
  1104. // now, found the range. check whether there is exact match
  1105. if (currencyNames[*begin].currencyNameLen == indexInCurrencyNames + 1) {
  1106. return *begin; // find range and exact match.
  1107. }
  1108. return -1; // find range, but no exact match.
  1109. }
  1110. }
  1111. }
  1112. *begin = -1;
  1113. *end = -1;
  1114. return -1; // failed to find range.
  1115. }
  1116. // Linear search "text" in "currencyNames".
  1117. // @param begin, end: the begin and end index in currencyNames, within which
  1118. // range should the search be performed.
  1119. // @param textLen: the length of the text to be compared
  1120. // @param maxMatchLen(IN/OUT): passing in the computed max matching length
  1121. // pass out the new max matching length
  1122. // @param maxMatchIndex: the index in currencyName which has the longest
  1123. // match with input text.
  1124. static void
  1125. linearSearch(const CurrencyNameStruct* currencyNames,
  1126. int32_t begin, int32_t end,
  1127. const char16_t* text, int32_t textLen,
  1128. int32_t *partialMatchLen,
  1129. int32_t *maxMatchLen, int32_t* maxMatchIndex) {
  1130. int32_t initialPartialMatchLen = *partialMatchLen;
  1131. for (int32_t index = begin; index <= end; ++index) {
  1132. int32_t len = currencyNames[index].currencyNameLen;
  1133. if (len > *maxMatchLen && len <= textLen &&
  1134. uprv_memcmp(currencyNames[index].currencyName, text, len * sizeof(char16_t)) == 0) {
  1135. *partialMatchLen = MAX(*partialMatchLen, len);
  1136. *maxMatchIndex = index;
  1137. *maxMatchLen = len;
  1138. #ifdef UCURR_DEBUG
  1139. printf("maxMatchIndex = %d, maxMatchLen = %d\n",
  1140. *maxMatchIndex, *maxMatchLen);
  1141. #endif
  1142. } else {
  1143. // Check for partial matches.
  1144. for (int32_t i=initialPartialMatchLen; i<MIN(len, textLen); i++) {
  1145. if (currencyNames[index].currencyName[i] != text[i]) {
  1146. break;
  1147. }
  1148. *partialMatchLen = MAX(*partialMatchLen, i + 1);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. #define LINEAR_SEARCH_THRESHOLD 10
  1154. // Find longest match between "text" and currency names in "currencyNames".
  1155. // @param total_currency_count: total number of currency names in CurrencyNames.
  1156. // @param textLen: the length of the text to be compared
  1157. // @param maxMatchLen: passing in the computed max matching length
  1158. // pass out the new max matching length
  1159. // @param maxMatchIndex: the index in currencyName which has the longest
  1160. // match with input text.
  1161. static void
  1162. searchCurrencyName(const CurrencyNameStruct* currencyNames,
  1163. int32_t total_currency_count,
  1164. const char16_t* text, int32_t textLen,
  1165. int32_t *partialMatchLen,
  1166. int32_t* maxMatchLen, int32_t* maxMatchIndex) {
  1167. *maxMatchIndex = -1;
  1168. *maxMatchLen = 0;
  1169. int32_t matchIndex = -1;
  1170. int32_t binarySearchBegin = 0;
  1171. int32_t binarySearchEnd = total_currency_count - 1;
  1172. // It is a variant of binary search.
  1173. // For example, given the currency names in currencyNames array are:
  1174. // A AB ABC AD AZ B BB BBEX BBEXYZ BS C D E....
  1175. // and the input text is BBEXST
  1176. // The first round binary search search "B" in the text against
  1177. // the first char in currency names, and find the first char matching range
  1178. // to be "B BB BBEX BBEXYZ BS" (and the maximum matching "B").
  1179. // The 2nd round binary search search the second "B" in the text against
  1180. // the 2nd char in currency names, and narrow the matching range to
  1181. // "BB BBEX BBEXYZ" (and the maximum matching "BB").
  1182. // The 3rd round returns the range as "BBEX BBEXYZ" (without changing
  1183. // maximum matching).
  1184. // The 4th round returns the same range (the maximum matching is "BBEX").
  1185. // The 5th round returns no matching range.
  1186. for (int32_t index = 0; index < textLen; ++index) {
  1187. // matchIndex saves the one with exact match till the current point.
  1188. // [binarySearchBegin, binarySearchEnd] saves the matching range.
  1189. matchIndex = binarySearch(currencyNames, index,
  1190. text[index],
  1191. &binarySearchBegin, &binarySearchEnd);
  1192. if (binarySearchBegin == -1) { // did not find the range
  1193. break;
  1194. }
  1195. *partialMatchLen = MAX(*partialMatchLen, index + 1);
  1196. if (matchIndex != -1) {
  1197. // find an exact match for text from text[0] to text[index]
  1198. // in currencyNames array.
  1199. *maxMatchLen = index + 1;
  1200. *maxMatchIndex = matchIndex;
  1201. }
  1202. if (binarySearchEnd - binarySearchBegin < LINEAR_SEARCH_THRESHOLD) {
  1203. // linear search if within threshold.
  1204. linearSearch(currencyNames, binarySearchBegin, binarySearchEnd,
  1205. text, textLen,
  1206. partialMatchLen,
  1207. maxMatchLen, maxMatchIndex);
  1208. break;
  1209. }
  1210. }
  1211. }
  1212. //========================= currency name cache =====================
  1213. typedef struct {
  1214. char locale[ULOC_FULLNAME_CAPACITY]; //key
  1215. // currency names, case insensitive
  1216. CurrencyNameStruct* currencyNames; // value
  1217. int32_t totalCurrencyNameCount; // currency name count
  1218. // currency symbols and ISO code, case sensitive
  1219. CurrencyNameStruct* currencySymbols; // value
  1220. int32_t totalCurrencySymbolCount; // count
  1221. // reference count.
  1222. // reference count is set to 1 when an entry is put to cache.
  1223. // it increases by 1 before accessing, and decreased by 1 after accessing.
  1224. // The entry is deleted when ref count is zero, which means
  1225. // the entry is replaced out of cache and no process is accessing it.
  1226. int32_t refCount;
  1227. } CurrencyNameCacheEntry;
  1228. #define CURRENCY_NAME_CACHE_NUM 10
  1229. // Reserve 10 cache entries.
  1230. static CurrencyNameCacheEntry* currCache[CURRENCY_NAME_CACHE_NUM] = {nullptr};
  1231. // Using an index to indicate which entry to be replaced when cache is full.
  1232. // It is a simple round-robin replacement strategy.
  1233. static int8_t currentCacheEntryIndex = 0;
  1234. static UMutex gCurrencyCacheMutex;
  1235. // Cache deletion
  1236. static void
  1237. deleteCurrencyNames(CurrencyNameStruct* currencyNames, int32_t count) {
  1238. for (int32_t index = 0; index < count; ++index) {
  1239. if ( (currencyNames[index].flag & NEED_TO_BE_DELETED) ) {
  1240. uprv_free(currencyNames[index].currencyName);
  1241. }
  1242. }
  1243. uprv_free(currencyNames);
  1244. }
  1245. static void
  1246. deleteCacheEntry(CurrencyNameCacheEntry* entry) {
  1247. deleteCurrencyNames(entry->currencyNames, entry->totalCurrencyNameCount);
  1248. deleteCurrencyNames(entry->currencySymbols, entry->totalCurrencySymbolCount);
  1249. uprv_free(entry);
  1250. }
  1251. // Cache clean up
  1252. static UBool U_CALLCONV
  1253. currency_cache_cleanup() {
  1254. for (int32_t i = 0; i < CURRENCY_NAME_CACHE_NUM; ++i) {
  1255. if (currCache[i]) {
  1256. deleteCacheEntry(currCache[i]);
  1257. currCache[i] = nullptr;
  1258. }
  1259. }
  1260. return true;
  1261. }
  1262. /**
  1263. * Loads the currency name data from the cache, or from resource bundles if necessary.
  1264. * The refCount is automatically incremented. It is the caller's responsibility
  1265. * to decrement it when done!
  1266. */
  1267. static CurrencyNameCacheEntry*
  1268. getCacheEntry(const char* locale, UErrorCode& ec) {
  1269. int32_t total_currency_name_count = 0;
  1270. CurrencyNameStruct* currencyNames = nullptr;
  1271. int32_t total_currency_symbol_count = 0;
  1272. CurrencyNameStruct* currencySymbols = nullptr;
  1273. CurrencyNameCacheEntry* cacheEntry = nullptr;
  1274. umtx_lock(&gCurrencyCacheMutex);
  1275. // in order to handle racing correctly,
  1276. // not putting 'search' in a separate function.
  1277. int8_t found = -1;
  1278. for (int8_t i = 0; i < CURRENCY_NAME_CACHE_NUM; ++i) {
  1279. if (currCache[i]!= nullptr &&
  1280. uprv_strcmp(locale, currCache[i]->locale) == 0) {
  1281. found = i;
  1282. break;
  1283. }
  1284. }
  1285. if (found != -1) {
  1286. cacheEntry = currCache[found];
  1287. ++(cacheEntry->refCount);
  1288. }
  1289. umtx_unlock(&gCurrencyCacheMutex);
  1290. if (found == -1) {
  1291. collectCurrencyNames(locale, &currencyNames, &total_currency_name_count, &currencySymbols, &total_currency_symbol_count, ec);
  1292. if (U_FAILURE(ec)) {
  1293. return nullptr;
  1294. }
  1295. umtx_lock(&gCurrencyCacheMutex);
  1296. // check again.
  1297. for (int8_t i = 0; i < CURRENCY_NAME_CACHE_NUM; ++i) {
  1298. if (currCache[i]!= nullptr &&
  1299. uprv_strcmp(locale, currCache[i]->locale) == 0) {
  1300. found = i;
  1301. break;
  1302. }
  1303. }
  1304. if (found == -1) {
  1305. // insert new entry to
  1306. // currentCacheEntryIndex % CURRENCY_NAME_CACHE_NUM
  1307. // and remove the existing entry
  1308. // currentCacheEntryIndex % CURRENCY_NAME_CACHE_NUM
  1309. // from cache.
  1310. cacheEntry = currCache[currentCacheEntryIndex];
  1311. if (cacheEntry) {
  1312. --(cacheEntry->refCount);
  1313. // delete if the ref count is zero
  1314. if (cacheEntry->refCount == 0) {
  1315. deleteCacheEntry(cacheEntry);
  1316. }
  1317. }
  1318. cacheEntry = static_cast<CurrencyNameCacheEntry*>(uprv_malloc(sizeof(CurrencyNameCacheEntry)));
  1319. if (cacheEntry == nullptr) {
  1320. deleteCurrencyNames(currencyNames, total_currency_name_count);
  1321. deleteCurrencyNames(currencySymbols, total_currency_symbol_count);
  1322. ec = U_MEMORY_ALLOCATION_ERROR;
  1323. return nullptr;
  1324. }
  1325. currCache[currentCacheEntryIndex] = cacheEntry;
  1326. uprv_strcpy(cacheEntry->locale, locale);
  1327. cacheEntry->currencyNames = currencyNames;
  1328. cacheEntry->totalCurrencyNameCount = total_currency_name_count;
  1329. cacheEntry->currencySymbols = currencySymbols;
  1330. cacheEntry->totalCurrencySymbolCount = total_currency_symbol_count;
  1331. cacheEntry->refCount = 2; // one for cache, one for reference
  1332. currentCacheEntryIndex = (currentCacheEntryIndex + 1) % CURRENCY_NAME_CACHE_NUM;
  1333. ucln_common_registerCleanup(UCLN_COMMON_CURRENCY, currency_cleanup);
  1334. } else {
  1335. deleteCurrencyNames(currencyNames, total_currency_name_count);
  1336. deleteCurrencyNames(currencySymbols, total_currency_symbol_count);
  1337. cacheEntry = currCache[found];
  1338. ++(cacheEntry->refCount);
  1339. }
  1340. umtx_unlock(&gCurrencyCacheMutex);
  1341. }
  1342. return cacheEntry;
  1343. }
  1344. static void releaseCacheEntry(CurrencyNameCacheEntry* cacheEntry) {
  1345. umtx_lock(&gCurrencyCacheMutex);
  1346. --(cacheEntry->refCount);
  1347. if (cacheEntry->refCount == 0) { // remove
  1348. deleteCacheEntry(cacheEntry);
  1349. }
  1350. umtx_unlock(&gCurrencyCacheMutex);
  1351. }
  1352. U_CAPI void
  1353. uprv_parseCurrency(const char* locale,
  1354. const icu::UnicodeString& text,
  1355. icu::ParsePosition& pos,
  1356. int8_t type,
  1357. int32_t* partialMatchLen,
  1358. char16_t* result,
  1359. UErrorCode& ec) {
  1360. U_NAMESPACE_USE
  1361. if (U_FAILURE(ec)) {
  1362. return;
  1363. }
  1364. CurrencyNameCacheEntry* cacheEntry = getCacheEntry(locale, ec);
  1365. if (U_FAILURE(ec)) {
  1366. return;
  1367. }
  1368. int32_t total_currency_name_count = cacheEntry->totalCurrencyNameCount;
  1369. CurrencyNameStruct* currencyNames = cacheEntry->currencyNames;
  1370. int32_t total_currency_symbol_count = cacheEntry->totalCurrencySymbolCount;
  1371. CurrencyNameStruct* currencySymbols = cacheEntry->currencySymbols;
  1372. int32_t start = pos.getIndex();
  1373. char16_t inputText[MAX_CURRENCY_NAME_LEN];
  1374. char16_t upperText[MAX_CURRENCY_NAME_LEN];
  1375. int32_t textLen = MIN(MAX_CURRENCY_NAME_LEN, text.length() - start);
  1376. text.extract(start, textLen, inputText);
  1377. UErrorCode ec1 = U_ZERO_ERROR;
  1378. textLen = u_strToUpper(upperText, MAX_CURRENCY_NAME_LEN, inputText, textLen, locale, &ec1);
  1379. // Make sure partialMatchLen is initialized
  1380. *partialMatchLen = 0;
  1381. int32_t max = 0;
  1382. int32_t matchIndex = -1;
  1383. // case in-sensitive comparison against currency names
  1384. searchCurrencyName(currencyNames, total_currency_name_count,
  1385. upperText, textLen, partialMatchLen, &max, &matchIndex);
  1386. #ifdef UCURR_DEBUG
  1387. printf("search in names, max = %d, matchIndex = %d\n", max, matchIndex);
  1388. #endif
  1389. int32_t maxInSymbol = 0;
  1390. int32_t matchIndexInSymbol = -1;
  1391. if (type != UCURR_LONG_NAME) { // not name only
  1392. // case sensitive comparison against currency symbols and ISO code.
  1393. searchCurrencyName(currencySymbols, total_currency_symbol_count,
  1394. inputText, textLen,
  1395. partialMatchLen,
  1396. &maxInSymbol, &matchIndexInSymbol);
  1397. }
  1398. #ifdef UCURR_DEBUG
  1399. printf("search in symbols, maxInSymbol = %d, matchIndexInSymbol = %d\n", maxInSymbol, matchIndexInSymbol);
  1400. if(matchIndexInSymbol != -1) {
  1401. printf("== ISO=%s\n", currencySymbols[matchIndexInSymbol].IsoCode);
  1402. }
  1403. #endif
  1404. if (max >= maxInSymbol && matchIndex != -1) {
  1405. u_charsToUChars(currencyNames[matchIndex].IsoCode, result, 4);
  1406. pos.setIndex(start + max);
  1407. } else if (maxInSymbol >= max && matchIndexInSymbol != -1) {
  1408. u_charsToUChars(currencySymbols[matchIndexInSymbol].IsoCode, result, 4);
  1409. pos.setIndex(start + maxInSymbol);
  1410. }
  1411. // decrease reference count
  1412. releaseCacheEntry(cacheEntry);
  1413. }
  1414. void uprv_currencyLeads(const char* locale, icu::UnicodeSet& result, UErrorCode& ec) {
  1415. U_NAMESPACE_USE
  1416. if (U_FAILURE(ec)) {
  1417. return;
  1418. }
  1419. CurrencyNameCacheEntry* cacheEntry = getCacheEntry(locale, ec);
  1420. if (U_FAILURE(ec)) {
  1421. return;
  1422. }
  1423. for (int32_t i=0; i<cacheEntry->totalCurrencySymbolCount; i++) {
  1424. const CurrencyNameStruct& info = cacheEntry->currencySymbols[i];
  1425. UChar32 cp;
  1426. U16_GET(info.currencyName, 0, 0, info.currencyNameLen, cp);
  1427. result.add(cp);
  1428. }
  1429. for (int32_t i=0; i<cacheEntry->totalCurrencyNameCount; i++) {
  1430. const CurrencyNameStruct& info = cacheEntry->currencyNames[i];
  1431. UChar32 cp;
  1432. U16_GET(info.currencyName, 0, 0, info.currencyNameLen, cp);
  1433. result.add(cp);
  1434. }
  1435. // decrease reference count
  1436. releaseCacheEntry(cacheEntry);
  1437. }
  1438. /**
  1439. * Internal method. Given a currency ISO code and a locale, return
  1440. * the "static" currency name. This is usually the same as the
  1441. * UCURR_SYMBOL_NAME, but if the latter is a choice format, then the
  1442. * format is applied to the number 2.0 (to yield the more common
  1443. * plural) to return a static name.
  1444. *
  1445. * This is used for backward compatibility with old currency logic in
  1446. * DecimalFormat and DecimalFormatSymbols.
  1447. */
  1448. U_CAPI void
  1449. uprv_getStaticCurrencyName(const char16_t* iso, const char* loc,
  1450. icu::UnicodeString& result, UErrorCode& ec)
  1451. {
  1452. U_NAMESPACE_USE
  1453. int32_t len;
  1454. const char16_t* currname = ucurr_getName(iso, loc, UCURR_SYMBOL_NAME,
  1455. nullptr /* isChoiceFormat */, &len, &ec);
  1456. if (U_SUCCESS(ec)) {
  1457. result.setTo(currname, len);
  1458. }
  1459. }
  1460. U_CAPI int32_t U_EXPORT2
  1461. ucurr_getDefaultFractionDigits(const char16_t* currency, UErrorCode* ec) {
  1462. return ucurr_getDefaultFractionDigitsForUsage(currency,UCURR_USAGE_STANDARD,ec);
  1463. }
  1464. U_CAPI int32_t U_EXPORT2
  1465. ucurr_getDefaultFractionDigitsForUsage(const char16_t* currency, const UCurrencyUsage usage, UErrorCode* ec) {
  1466. int32_t fracDigits = 0;
  1467. if (U_SUCCESS(*ec)) {
  1468. switch (usage) {
  1469. case UCURR_USAGE_STANDARD:
  1470. fracDigits = (_findMetaData(currency, *ec))[0];
  1471. break;
  1472. case UCURR_USAGE_CASH:
  1473. fracDigits = (_findMetaData(currency, *ec))[2];
  1474. break;
  1475. default:
  1476. *ec = U_UNSUPPORTED_ERROR;
  1477. }
  1478. }
  1479. return fracDigits;
  1480. }
  1481. U_CAPI double U_EXPORT2
  1482. ucurr_getRoundingIncrement(const char16_t* currency, UErrorCode* ec) {
  1483. return ucurr_getRoundingIncrementForUsage(currency, UCURR_USAGE_STANDARD, ec);
  1484. }
  1485. U_CAPI double U_EXPORT2
  1486. ucurr_getRoundingIncrementForUsage(const char16_t* currency, const UCurrencyUsage usage, UErrorCode* ec) {
  1487. double result = 0.0;
  1488. const int32_t *data = _findMetaData(currency, *ec);
  1489. if (U_SUCCESS(*ec)) {
  1490. int32_t fracDigits;
  1491. int32_t increment;
  1492. switch (usage) {
  1493. case UCURR_USAGE_STANDARD:
  1494. fracDigits = data[0];
  1495. increment = data[1];
  1496. break;
  1497. case UCURR_USAGE_CASH:
  1498. fracDigits = data[2];
  1499. increment = data[3];
  1500. break;
  1501. default:
  1502. *ec = U_UNSUPPORTED_ERROR;
  1503. return result;
  1504. }
  1505. // If the meta data is invalid, return 0.0
  1506. if (fracDigits < 0 || fracDigits > MAX_POW10) {
  1507. *ec = U_INVALID_FORMAT_ERROR;
  1508. } else {
  1509. // A rounding value of 0 or 1 indicates no rounding.
  1510. if (increment >= 2) {
  1511. // Return (increment) / 10^(fracDigits). The only actual rounding data,
  1512. // as of this writing, is CHF { 2, 5 }.
  1513. result = double(increment) / POW10[fracDigits];
  1514. }
  1515. }
  1516. }
  1517. return result;
  1518. }
  1519. U_CDECL_BEGIN
  1520. typedef struct UCurrencyContext {
  1521. uint32_t currType; /* UCurrCurrencyType */
  1522. uint32_t listIdx;
  1523. } UCurrencyContext;
  1524. /*
  1525. Please keep this list in alphabetical order.
  1526. You can look at the CLDR supplemental data or ISO-4217 for the meaning of some
  1527. of these items.
  1528. ISO-4217: http://www.iso.org/iso/en/prods-services/popstds/currencycodeslist.html
  1529. */
  1530. static const struct CurrencyList {
  1531. const char *currency;
  1532. uint32_t currType;
  1533. } gCurrencyList[] = {
  1534. {"ADP", UCURR_COMMON|UCURR_DEPRECATED},
  1535. {"AED", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1536. {"AFA", UCURR_COMMON|UCURR_DEPRECATED},
  1537. {"AFN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1538. {"ALK", UCURR_COMMON|UCURR_DEPRECATED},
  1539. {"ALL", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1540. {"AMD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1541. {"ANG", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1542. {"AOA", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1543. {"AOK", UCURR_COMMON|UCURR_DEPRECATED},
  1544. {"AON", UCURR_COMMON|UCURR_DEPRECATED},
  1545. {"AOR", UCURR_COMMON|UCURR_DEPRECATED},
  1546. {"ARA", UCURR_COMMON|UCURR_DEPRECATED},
  1547. {"ARL", UCURR_COMMON|UCURR_DEPRECATED},
  1548. {"ARM", UCURR_COMMON|UCURR_DEPRECATED},
  1549. {"ARP", UCURR_COMMON|UCURR_DEPRECATED},
  1550. {"ARS", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1551. {"ATS", UCURR_COMMON|UCURR_DEPRECATED},
  1552. {"AUD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1553. {"AWG", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1554. {"AZM", UCURR_COMMON|UCURR_DEPRECATED},
  1555. {"AZN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1556. {"BAD", UCURR_COMMON|UCURR_DEPRECATED},
  1557. {"BAM", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1558. {"BAN", UCURR_COMMON|UCURR_DEPRECATED},
  1559. {"BBD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1560. {"BDT", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1561. {"BEC", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1562. {"BEF", UCURR_COMMON|UCURR_DEPRECATED},
  1563. {"BEL", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1564. {"BGL", UCURR_COMMON|UCURR_DEPRECATED},
  1565. {"BGM", UCURR_COMMON|UCURR_DEPRECATED},
  1566. {"BGN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1567. {"BGO", UCURR_COMMON|UCURR_DEPRECATED},
  1568. {"BHD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1569. {"BIF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1570. {"BMD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1571. {"BND", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1572. {"BOB", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1573. {"BOL", UCURR_COMMON|UCURR_DEPRECATED},
  1574. {"BOP", UCURR_COMMON|UCURR_DEPRECATED},
  1575. {"BOV", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1576. {"BRB", UCURR_COMMON|UCURR_DEPRECATED},
  1577. {"BRC", UCURR_COMMON|UCURR_DEPRECATED},
  1578. {"BRE", UCURR_COMMON|UCURR_DEPRECATED},
  1579. {"BRL", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1580. {"BRN", UCURR_COMMON|UCURR_DEPRECATED},
  1581. {"BRR", UCURR_COMMON|UCURR_DEPRECATED},
  1582. {"BRZ", UCURR_COMMON|UCURR_DEPRECATED},
  1583. {"BSD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1584. {"BTN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1585. {"BUK", UCURR_COMMON|UCURR_DEPRECATED},
  1586. {"BWP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1587. {"BYB", UCURR_COMMON|UCURR_DEPRECATED},
  1588. {"BYN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1589. {"BYR", UCURR_COMMON|UCURR_DEPRECATED},
  1590. {"BZD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1591. {"CAD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1592. {"CDF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1593. {"CHE", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1594. {"CHF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1595. {"CHW", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1596. {"CLE", UCURR_COMMON|UCURR_DEPRECATED},
  1597. {"CLF", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1598. {"CLP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1599. {"CNH", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1600. {"CNX", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1601. {"CNY", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1602. {"COP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1603. {"COU", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1604. {"CRC", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1605. {"CSD", UCURR_COMMON|UCURR_DEPRECATED},
  1606. {"CSK", UCURR_COMMON|UCURR_DEPRECATED},
  1607. {"CUC", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1608. {"CUP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1609. {"CVE", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1610. {"CYP", UCURR_COMMON|UCURR_DEPRECATED},
  1611. {"CZK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1612. {"DDM", UCURR_COMMON|UCURR_DEPRECATED},
  1613. {"DEM", UCURR_COMMON|UCURR_DEPRECATED},
  1614. {"DJF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1615. {"DKK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1616. {"DOP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1617. {"DZD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1618. {"ECS", UCURR_COMMON|UCURR_DEPRECATED},
  1619. {"ECV", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1620. {"EEK", UCURR_COMMON|UCURR_DEPRECATED},
  1621. {"EGP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1622. {"ERN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1623. {"ESA", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1624. {"ESB", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1625. {"ESP", UCURR_COMMON|UCURR_DEPRECATED},
  1626. {"ETB", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1627. {"EUR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1628. {"FIM", UCURR_COMMON|UCURR_DEPRECATED},
  1629. {"FJD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1630. {"FKP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1631. {"FRF", UCURR_COMMON|UCURR_DEPRECATED},
  1632. {"GBP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1633. {"GEK", UCURR_COMMON|UCURR_DEPRECATED},
  1634. {"GEL", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1635. {"GHC", UCURR_COMMON|UCURR_DEPRECATED},
  1636. {"GHS", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1637. {"GIP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1638. {"GMD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1639. {"GNF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1640. {"GNS", UCURR_COMMON|UCURR_DEPRECATED},
  1641. {"GQE", UCURR_COMMON|UCURR_DEPRECATED},
  1642. {"GRD", UCURR_COMMON|UCURR_DEPRECATED},
  1643. {"GTQ", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1644. {"GWE", UCURR_COMMON|UCURR_DEPRECATED},
  1645. {"GWP", UCURR_COMMON|UCURR_DEPRECATED},
  1646. {"GYD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1647. {"HKD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1648. {"HNL", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1649. {"HRD", UCURR_COMMON|UCURR_DEPRECATED},
  1650. {"HRK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1651. {"HTG", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1652. {"HUF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1653. {"IDR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1654. {"IEP", UCURR_COMMON|UCURR_DEPRECATED},
  1655. {"ILP", UCURR_COMMON|UCURR_DEPRECATED},
  1656. {"ILR", UCURR_COMMON|UCURR_DEPRECATED},
  1657. {"ILS", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1658. {"INR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1659. {"IQD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1660. {"IRR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1661. {"ISJ", UCURR_COMMON|UCURR_DEPRECATED},
  1662. {"ISK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1663. {"ITL", UCURR_COMMON|UCURR_DEPRECATED},
  1664. {"JMD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1665. {"JOD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1666. {"JPY", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1667. {"KES", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1668. {"KGS", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1669. {"KHR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1670. {"KMF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1671. {"KPW", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1672. {"KRH", UCURR_COMMON|UCURR_DEPRECATED},
  1673. {"KRO", UCURR_COMMON|UCURR_DEPRECATED},
  1674. {"KRW", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1675. {"KWD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1676. {"KYD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1677. {"KZT", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1678. {"LAK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1679. {"LBP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1680. {"LKR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1681. {"LRD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1682. {"LSL", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1683. {"LSM", UCURR_COMMON|UCURR_DEPRECATED}, // questionable, remove?
  1684. {"LTL", UCURR_COMMON|UCURR_DEPRECATED},
  1685. {"LTT", UCURR_COMMON|UCURR_DEPRECATED},
  1686. {"LUC", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1687. {"LUF", UCURR_COMMON|UCURR_DEPRECATED},
  1688. {"LUL", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1689. {"LVL", UCURR_COMMON|UCURR_DEPRECATED},
  1690. {"LVR", UCURR_COMMON|UCURR_DEPRECATED},
  1691. {"LYD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1692. {"MAD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1693. {"MAF", UCURR_COMMON|UCURR_DEPRECATED},
  1694. {"MCF", UCURR_COMMON|UCURR_DEPRECATED},
  1695. {"MDC", UCURR_COMMON|UCURR_DEPRECATED},
  1696. {"MDL", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1697. {"MGA", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1698. {"MGF", UCURR_COMMON|UCURR_DEPRECATED},
  1699. {"MKD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1700. {"MKN", UCURR_COMMON|UCURR_DEPRECATED},
  1701. {"MLF", UCURR_COMMON|UCURR_DEPRECATED},
  1702. {"MMK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1703. {"MNT", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1704. {"MOP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1705. {"MRO", UCURR_COMMON|UCURR_DEPRECATED},
  1706. {"MRU", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1707. {"MTL", UCURR_COMMON|UCURR_DEPRECATED},
  1708. {"MTP", UCURR_COMMON|UCURR_DEPRECATED},
  1709. {"MUR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1710. {"MVP", UCURR_COMMON|UCURR_DEPRECATED}, // questionable, remove?
  1711. {"MVR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1712. {"MWK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1713. {"MXN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1714. {"MXP", UCURR_COMMON|UCURR_DEPRECATED},
  1715. {"MXV", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1716. {"MYR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1717. {"MZE", UCURR_COMMON|UCURR_DEPRECATED},
  1718. {"MZM", UCURR_COMMON|UCURR_DEPRECATED},
  1719. {"MZN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1720. {"NAD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1721. {"NGN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1722. {"NIC", UCURR_COMMON|UCURR_DEPRECATED},
  1723. {"NIO", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1724. {"NLG", UCURR_COMMON|UCURR_DEPRECATED},
  1725. {"NOK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1726. {"NPR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1727. {"NZD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1728. {"OMR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1729. {"PAB", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1730. {"PEI", UCURR_COMMON|UCURR_DEPRECATED},
  1731. {"PEN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1732. {"PES", UCURR_COMMON|UCURR_DEPRECATED},
  1733. {"PGK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1734. {"PHP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1735. {"PKR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1736. {"PLN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1737. {"PLZ", UCURR_COMMON|UCURR_DEPRECATED},
  1738. {"PTE", UCURR_COMMON|UCURR_DEPRECATED},
  1739. {"PYG", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1740. {"QAR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1741. {"RHD", UCURR_COMMON|UCURR_DEPRECATED},
  1742. {"ROL", UCURR_COMMON|UCURR_DEPRECATED},
  1743. {"RON", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1744. {"RSD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1745. {"RUB", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1746. {"RUR", UCURR_COMMON|UCURR_DEPRECATED},
  1747. {"RWF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1748. {"SAR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1749. {"SBD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1750. {"SCR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1751. {"SDD", UCURR_COMMON|UCURR_DEPRECATED},
  1752. {"SDG", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1753. {"SDP", UCURR_COMMON|UCURR_DEPRECATED},
  1754. {"SEK", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1755. {"SGD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1756. {"SHP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1757. {"SIT", UCURR_COMMON|UCURR_DEPRECATED},
  1758. {"SKK", UCURR_COMMON|UCURR_DEPRECATED},
  1759. {"SLE", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1760. {"SLL", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1761. {"SOS", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1762. {"SRD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1763. {"SRG", UCURR_COMMON|UCURR_DEPRECATED},
  1764. {"SSP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1765. {"STD", UCURR_COMMON|UCURR_DEPRECATED},
  1766. {"STN", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1767. {"SUR", UCURR_COMMON|UCURR_DEPRECATED},
  1768. {"SVC", UCURR_COMMON|UCURR_DEPRECATED},
  1769. {"SYP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1770. {"SZL", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1771. {"THB", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1772. {"TJR", UCURR_COMMON|UCURR_DEPRECATED},
  1773. {"TJS", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1774. {"TMM", UCURR_COMMON|UCURR_DEPRECATED},
  1775. {"TMT", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1776. {"TND", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1777. {"TOP", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1778. {"TPE", UCURR_COMMON|UCURR_DEPRECATED},
  1779. {"TRL", UCURR_COMMON|UCURR_DEPRECATED},
  1780. {"TRY", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1781. {"TTD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1782. {"TWD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1783. {"TZS", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1784. {"UAH", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1785. {"UAK", UCURR_COMMON|UCURR_DEPRECATED},
  1786. {"UGS", UCURR_COMMON|UCURR_DEPRECATED},
  1787. {"UGX", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1788. {"USD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1789. {"USN", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1790. {"USS", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1791. {"UYI", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1792. {"UYP", UCURR_COMMON|UCURR_DEPRECATED},
  1793. {"UYU", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1794. {"UYW", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1795. {"UZS", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1796. {"VEB", UCURR_COMMON|UCURR_DEPRECATED},
  1797. {"VED", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1798. {"VEF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1799. {"VES", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1800. {"VND", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1801. {"VNN", UCURR_COMMON|UCURR_DEPRECATED},
  1802. {"VUV", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1803. {"WST", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1804. {"XAF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1805. {"XAG", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1806. {"XAU", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1807. {"XBA", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1808. {"XBB", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1809. {"XBC", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1810. {"XBD", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1811. {"XCD", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1812. {"XCG", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1813. {"XDR", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1814. {"XEU", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1815. {"XFO", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1816. {"XFU", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1817. {"XOF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1818. {"XPD", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1819. {"XPF", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1820. {"XPT", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1821. {"XRE", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1822. {"XSU", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1823. {"XTS", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1824. {"XUA", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1825. {"XXX", UCURR_UNCOMMON|UCURR_NON_DEPRECATED},
  1826. {"YDD", UCURR_COMMON|UCURR_DEPRECATED},
  1827. {"YER", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1828. {"YUD", UCURR_COMMON|UCURR_DEPRECATED},
  1829. {"YUM", UCURR_COMMON|UCURR_DEPRECATED},
  1830. {"YUN", UCURR_COMMON|UCURR_DEPRECATED},
  1831. {"YUR", UCURR_COMMON|UCURR_DEPRECATED},
  1832. {"ZAL", UCURR_UNCOMMON|UCURR_DEPRECATED},
  1833. {"ZAR", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1834. {"ZMK", UCURR_COMMON|UCURR_DEPRECATED},
  1835. {"ZMW", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1836. {"ZRN", UCURR_COMMON|UCURR_DEPRECATED},
  1837. {"ZRZ", UCURR_COMMON|UCURR_DEPRECATED},
  1838. {"ZWD", UCURR_COMMON|UCURR_DEPRECATED},
  1839. {"ZWG", UCURR_COMMON|UCURR_NON_DEPRECATED},
  1840. {"ZWL", UCURR_COMMON|UCURR_DEPRECATED},
  1841. {"ZWR", UCURR_COMMON|UCURR_DEPRECATED},
  1842. { nullptr, 0 } // Leave here to denote the end of the list.
  1843. };
  1844. #define UCURR_MATCHES_BITMASK(variable, typeToMatch) \
  1845. ((typeToMatch) == UCURR_ALL || ((variable) & (typeToMatch)) == (typeToMatch))
  1846. static int32_t U_CALLCONV
  1847. ucurr_countCurrencyList(UEnumeration *enumerator, UErrorCode * /*pErrorCode*/) {
  1848. UCurrencyContext *myContext = (UCurrencyContext *)(enumerator->context);
  1849. uint32_t currType = myContext->currType;
  1850. int32_t count = 0;
  1851. /* Count the number of items matching the type we are looking for. */
  1852. for (int32_t idx = 0; gCurrencyList[idx].currency != nullptr; idx++) {
  1853. if (UCURR_MATCHES_BITMASK(gCurrencyList[idx].currType, currType)) {
  1854. count++;
  1855. }
  1856. }
  1857. return count;
  1858. }
  1859. static const char* U_CALLCONV
  1860. ucurr_nextCurrencyList(UEnumeration *enumerator,
  1861. int32_t* resultLength,
  1862. UErrorCode * /*pErrorCode*/)
  1863. {
  1864. UCurrencyContext *myContext = (UCurrencyContext *)(enumerator->context);
  1865. /* Find the next in the list that matches the type we are looking for. */
  1866. while (myContext->listIdx < UPRV_LENGTHOF(gCurrencyList)-1) {
  1867. const struct CurrencyList *currItem = &gCurrencyList[myContext->listIdx++];
  1868. if (UCURR_MATCHES_BITMASK(currItem->currType, myContext->currType))
  1869. {
  1870. if (resultLength) {
  1871. *resultLength = 3; /* Currency codes are only 3 chars long */
  1872. }
  1873. return currItem->currency;
  1874. }
  1875. }
  1876. /* We enumerated too far. */
  1877. if (resultLength) {
  1878. *resultLength = 0;
  1879. }
  1880. return nullptr;
  1881. }
  1882. static void U_CALLCONV
  1883. ucurr_resetCurrencyList(UEnumeration *enumerator, UErrorCode * /*pErrorCode*/) {
  1884. ((UCurrencyContext *)(enumerator->context))->listIdx = 0;
  1885. }
  1886. static void U_CALLCONV
  1887. ucurr_closeCurrencyList(UEnumeration *enumerator) {
  1888. uprv_free(enumerator->context);
  1889. uprv_free(enumerator);
  1890. }
  1891. static void U_CALLCONV
  1892. ucurr_createCurrencyList(UHashtable *isoCodes, UErrorCode* status){
  1893. UErrorCode localStatus = U_ZERO_ERROR;
  1894. // Look up the CurrencyMap element in the root bundle.
  1895. UResourceBundle *rb = ures_openDirect(U_ICUDATA_CURR, CURRENCY_DATA, &localStatus);
  1896. LocalUResourceBundlePointer currencyMapArray(ures_getByKey(rb, CURRENCY_MAP, rb, &localStatus));
  1897. if (U_SUCCESS(localStatus)) {
  1898. // process each entry in currency map
  1899. for (int32_t i=0; i<ures_getSize(currencyMapArray.getAlias()); i++) {
  1900. // get the currency resource
  1901. LocalUResourceBundlePointer currencyArray(ures_getByIndex(currencyMapArray.getAlias(), i, nullptr, &localStatus));
  1902. // process each currency
  1903. if (U_SUCCESS(localStatus)) {
  1904. for (int32_t j=0; j<ures_getSize(currencyArray.getAlias()); j++) {
  1905. // get the currency resource
  1906. LocalUResourceBundlePointer currencyRes(ures_getByIndex(currencyArray.getAlias(), j, nullptr, &localStatus));
  1907. IsoCodeEntry *entry = (IsoCodeEntry*)uprv_malloc(sizeof(IsoCodeEntry));
  1908. if (entry == nullptr) {
  1909. *status = U_MEMORY_ALLOCATION_ERROR;
  1910. return;
  1911. }
  1912. // get the ISO code
  1913. int32_t isoLength = 0;
  1914. LocalUResourceBundlePointer idRes(ures_getByKey(currencyRes.getAlias(), "id", nullptr, &localStatus));
  1915. if (idRes.isNull()) {
  1916. continue;
  1917. }
  1918. const char16_t *isoCode = ures_getString(idRes.getAlias(), &isoLength, &localStatus);
  1919. // get from date
  1920. UDate fromDate = U_DATE_MIN;
  1921. LocalUResourceBundlePointer fromRes(ures_getByKey(currencyRes.getAlias(), "from", nullptr, &localStatus));
  1922. if (U_SUCCESS(localStatus)) {
  1923. int32_t fromLength = 0;
  1924. const int32_t *fromArray = ures_getIntVector(fromRes.getAlias(), &fromLength, &localStatus);
  1925. int64_t currDate64 = ((uint64_t)fromArray[0]) << 32;
  1926. currDate64 |= ((int64_t)fromArray[1] & (int64_t)INT64_C(0x00000000FFFFFFFF));
  1927. fromDate = (UDate)currDate64;
  1928. }
  1929. // get to date
  1930. UDate toDate = U_DATE_MAX;
  1931. localStatus = U_ZERO_ERROR;
  1932. LocalUResourceBundlePointer toRes(ures_getByKey(currencyRes.getAlias(), "to", nullptr, &localStatus));
  1933. if (U_SUCCESS(localStatus)) {
  1934. int32_t toLength = 0;
  1935. const int32_t *toArray = ures_getIntVector(toRes.getAlias(), &toLength, &localStatus);
  1936. int64_t currDate64 = (uint64_t)toArray[0] << 32;
  1937. currDate64 |= ((int64_t)toArray[1] & (int64_t)INT64_C(0x00000000FFFFFFFF));
  1938. toDate = (UDate)currDate64;
  1939. }
  1940. entry->isoCode = isoCode;
  1941. entry->from = fromDate;
  1942. entry->to = toDate;
  1943. localStatus = U_ZERO_ERROR;
  1944. uhash_put(isoCodes, (char16_t *)isoCode, entry, &localStatus);
  1945. }
  1946. } else {
  1947. *status = localStatus;
  1948. }
  1949. }
  1950. } else {
  1951. *status = localStatus;
  1952. }
  1953. }
  1954. static const UEnumeration gEnumCurrencyList = {
  1955. nullptr,
  1956. nullptr,
  1957. ucurr_closeCurrencyList,
  1958. ucurr_countCurrencyList,
  1959. uenum_unextDefault,
  1960. ucurr_nextCurrencyList,
  1961. ucurr_resetCurrencyList
  1962. };
  1963. U_CDECL_END
  1964. static void U_CALLCONV initIsoCodes(UErrorCode &status) {
  1965. U_ASSERT(gIsoCodes == nullptr);
  1966. ucln_common_registerCleanup(UCLN_COMMON_CURRENCY, currency_cleanup);
  1967. LocalUHashtablePointer isoCodes(uhash_open(uhash_hashUChars, uhash_compareUChars, nullptr, &status));
  1968. if (U_FAILURE(status)) {
  1969. return;
  1970. }
  1971. uhash_setValueDeleter(isoCodes.getAlias(), deleteIsoCodeEntry);
  1972. ucurr_createCurrencyList(isoCodes.getAlias(), &status);
  1973. if (U_FAILURE(status)) {
  1974. return;
  1975. }
  1976. gIsoCodes = isoCodes.orphan(); // Note: gIsoCodes is const. Once set up here it is never altered,
  1977. // and read only access is safe without synchronization.
  1978. }
  1979. static void populateCurrSymbolsEquiv(icu::Hashtable *hash, UErrorCode &status) {
  1980. if (U_FAILURE(status)) { return; }
  1981. for (const auto& entry : unisets::kCurrencyEntries) {
  1982. UnicodeString exemplar(entry.exemplar);
  1983. const UnicodeSet* set = unisets::get(entry.key);
  1984. if (set == nullptr) { return; }
  1985. UnicodeSetIterator it(*set);
  1986. while (it.next()) {
  1987. UnicodeString value = it.getString();
  1988. if (value == exemplar) {
  1989. // No need to mark the exemplar character as an equivalent
  1990. continue;
  1991. }
  1992. makeEquivalent(exemplar, value, hash, status);
  1993. if (U_FAILURE(status)) { return; }
  1994. }
  1995. }
  1996. }
  1997. static void U_CALLCONV initCurrSymbolsEquiv() {
  1998. U_ASSERT(gCurrSymbolsEquiv == nullptr);
  1999. UErrorCode status = U_ZERO_ERROR;
  2000. ucln_common_registerCleanup(UCLN_COMMON_CURRENCY, currency_cleanup);
  2001. icu::Hashtable *temp = new icu::Hashtable(status);
  2002. if (temp == nullptr) {
  2003. return;
  2004. }
  2005. if (U_FAILURE(status)) {
  2006. delete temp;
  2007. return;
  2008. }
  2009. temp->setValueDeleter(deleteUnicode);
  2010. populateCurrSymbolsEquiv(temp, status);
  2011. if (U_FAILURE(status)) {
  2012. delete temp;
  2013. return;
  2014. }
  2015. gCurrSymbolsEquiv = temp;
  2016. }
  2017. U_CAPI UBool U_EXPORT2
  2018. ucurr_isAvailable(const char16_t* isoCode, UDate from, UDate to, UErrorCode* eErrorCode) {
  2019. umtx_initOnce(gIsoCodesInitOnce, &initIsoCodes, *eErrorCode);
  2020. if (U_FAILURE(*eErrorCode)) {
  2021. return false;
  2022. }
  2023. IsoCodeEntry* result = (IsoCodeEntry *) uhash_get(gIsoCodes, isoCode);
  2024. if (result == nullptr) {
  2025. return false;
  2026. } else if (from > to) {
  2027. *eErrorCode = U_ILLEGAL_ARGUMENT_ERROR;
  2028. return false;
  2029. } else if ((from > result->to) || (to < result->from)) {
  2030. return false;
  2031. }
  2032. return true;
  2033. }
  2034. static const icu::Hashtable* getCurrSymbolsEquiv() {
  2035. umtx_initOnce(gCurrSymbolsEquivInitOnce, &initCurrSymbolsEquiv);
  2036. return gCurrSymbolsEquiv;
  2037. }
  2038. U_CAPI UEnumeration * U_EXPORT2
  2039. ucurr_openISOCurrencies(uint32_t currType, UErrorCode *pErrorCode) {
  2040. UEnumeration *myEnum = nullptr;
  2041. UCurrencyContext *myContext;
  2042. myEnum = (UEnumeration*)uprv_malloc(sizeof(UEnumeration));
  2043. if (myEnum == nullptr) {
  2044. *pErrorCode = U_MEMORY_ALLOCATION_ERROR;
  2045. return nullptr;
  2046. }
  2047. uprv_memcpy(myEnum, &gEnumCurrencyList, sizeof(UEnumeration));
  2048. myContext = (UCurrencyContext*)uprv_malloc(sizeof(UCurrencyContext));
  2049. if (myContext == nullptr) {
  2050. *pErrorCode = U_MEMORY_ALLOCATION_ERROR;
  2051. uprv_free(myEnum);
  2052. return nullptr;
  2053. }
  2054. myContext->currType = currType;
  2055. myContext->listIdx = 0;
  2056. myEnum->context = myContext;
  2057. return myEnum;
  2058. }
  2059. U_CAPI int32_t U_EXPORT2
  2060. ucurr_countCurrencies(const char* locale,
  2061. UDate date,
  2062. UErrorCode* ec)
  2063. {
  2064. int32_t currCount = 0;
  2065. if (ec != nullptr && U_SUCCESS(*ec))
  2066. {
  2067. // local variables
  2068. UErrorCode localStatus = U_ZERO_ERROR;
  2069. // get country or country_variant in `id'
  2070. CharString id = idForLocale(locale, ec);
  2071. if (U_FAILURE(*ec))
  2072. {
  2073. return 0;
  2074. }
  2075. // Remove variants, which is only needed for registration.
  2076. char *idDelim = strchr(id.data(), VAR_DELIM);
  2077. if (idDelim)
  2078. {
  2079. id.truncate(idDelim - id.data());
  2080. }
  2081. // Look up the CurrencyMap element in the root bundle.
  2082. UResourceBundle *rb = ures_openDirect(U_ICUDATA_CURR, CURRENCY_DATA, &localStatus);
  2083. UResourceBundle *cm = ures_getByKey(rb, CURRENCY_MAP, rb, &localStatus);
  2084. // Using the id derived from the local, get the currency data
  2085. LocalUResourceBundlePointer countryArray(ures_getByKey(rb, id.data(), cm, &localStatus));
  2086. // process each currency to see which one is valid for the given date
  2087. if (U_SUCCESS(localStatus))
  2088. {
  2089. for (int32_t i=0; i<ures_getSize(countryArray.getAlias()); i++)
  2090. {
  2091. // get the currency resource
  2092. LocalUResourceBundlePointer currencyRes(ures_getByIndex(countryArray.getAlias(), i, nullptr, &localStatus));
  2093. // get the from date
  2094. int32_t fromLength = 0;
  2095. LocalUResourceBundlePointer fromRes(ures_getByKey(currencyRes.getAlias(), "from", nullptr, &localStatus));
  2096. const int32_t *fromArray = ures_getIntVector(fromRes.getAlias(), &fromLength, &localStatus);
  2097. int64_t currDate64 = (int64_t)((uint64_t)(fromArray[0]) << 32);
  2098. currDate64 |= ((int64_t)fromArray[1] & (int64_t)INT64_C(0x00000000FFFFFFFF));
  2099. UDate fromDate = (UDate)currDate64;
  2100. if (ures_getSize(currencyRes.getAlias())> 2)
  2101. {
  2102. int32_t toLength = 0;
  2103. LocalUResourceBundlePointer toRes(ures_getByKey(currencyRes.getAlias(), "to", nullptr, &localStatus));
  2104. const int32_t *toArray = ures_getIntVector(toRes.getAlias(), &toLength, &localStatus);
  2105. currDate64 = (int64_t)toArray[0] << 32;
  2106. currDate64 |= ((int64_t)toArray[1] & (int64_t)INT64_C(0x00000000FFFFFFFF));
  2107. UDate toDate = (UDate)currDate64;
  2108. if ((fromDate <= date) && (date < toDate))
  2109. {
  2110. currCount++;
  2111. }
  2112. }
  2113. else
  2114. {
  2115. if (fromDate <= date)
  2116. {
  2117. currCount++;
  2118. }
  2119. }
  2120. } // end For loop
  2121. } // end if (U_SUCCESS(localStatus))
  2122. // Check for errors
  2123. if (*ec == U_ZERO_ERROR || localStatus != U_ZERO_ERROR)
  2124. {
  2125. // There is nothing to fallback to.
  2126. // Report the failure/warning if possible.
  2127. *ec = localStatus;
  2128. }
  2129. if (U_SUCCESS(*ec))
  2130. {
  2131. // no errors
  2132. return currCount;
  2133. }
  2134. }
  2135. // If we got here, either error code is invalid or
  2136. // some argument passed is no good.
  2137. return 0;
  2138. }
  2139. U_CAPI int32_t U_EXPORT2
  2140. ucurr_forLocaleAndDate(const char* locale,
  2141. UDate date,
  2142. int32_t index,
  2143. char16_t* buff,
  2144. int32_t buffCapacity,
  2145. UErrorCode* ec)
  2146. {
  2147. int32_t resLen = 0;
  2148. int32_t currIndex = 0;
  2149. const char16_t* s = nullptr;
  2150. if (ec != nullptr && U_SUCCESS(*ec))
  2151. {
  2152. // check the arguments passed
  2153. if ((buff && buffCapacity) || !buffCapacity )
  2154. {
  2155. // local variables
  2156. UErrorCode localStatus = U_ZERO_ERROR;
  2157. // get country or country_variant in `id'
  2158. CharString id = idForLocale(locale, ec);
  2159. if (U_FAILURE(*ec))
  2160. {
  2161. return 0;
  2162. }
  2163. // Remove variants, which is only needed for registration.
  2164. char *idDelim = strchr(id.data(), VAR_DELIM);
  2165. if (idDelim)
  2166. {
  2167. id.truncate(idDelim - id.data());
  2168. }
  2169. // Look up the CurrencyMap element in the root bundle.
  2170. UResourceBundle *rb = ures_openDirect(U_ICUDATA_CURR, CURRENCY_DATA, &localStatus);
  2171. UResourceBundle *cm = ures_getByKey(rb, CURRENCY_MAP, rb, &localStatus);
  2172. // Using the id derived from the local, get the currency data
  2173. LocalUResourceBundlePointer countryArray(ures_getByKey(rb, id.data(), cm, &localStatus));
  2174. // process each currency to see which one is valid for the given date
  2175. bool matchFound = false;
  2176. if (U_SUCCESS(localStatus))
  2177. {
  2178. if ((index <= 0) || (index> ures_getSize(countryArray.getAlias())))
  2179. {
  2180. // requested index is out of bounds
  2181. return 0;
  2182. }
  2183. for (int32_t i=0; i<ures_getSize(countryArray.getAlias()); i++)
  2184. {
  2185. // get the currency resource
  2186. LocalUResourceBundlePointer currencyRes(ures_getByIndex(countryArray.getAlias(), i, nullptr, &localStatus));
  2187. s = ures_getStringByKey(currencyRes.getAlias(), "id", &resLen, &localStatus);
  2188. // get the from date
  2189. int32_t fromLength = 0;
  2190. LocalUResourceBundlePointer fromRes(ures_getByKey(currencyRes.getAlias(), "from", nullptr, &localStatus));
  2191. const int32_t *fromArray = ures_getIntVector(fromRes.getAlias(), &fromLength, &localStatus);
  2192. int64_t currDate64 = (int64_t)((uint64_t)fromArray[0] << 32);
  2193. currDate64 |= ((int64_t)fromArray[1] & (int64_t)INT64_C(0x00000000FFFFFFFF));
  2194. UDate fromDate = (UDate)currDate64;
  2195. if (ures_getSize(currencyRes.getAlias()) > 2)
  2196. {
  2197. int32_t toLength = 0;
  2198. LocalUResourceBundlePointer toRes(ures_getByKey(currencyRes.getAlias(), "to", nullptr, &localStatus));
  2199. const int32_t *toArray = ures_getIntVector(toRes.getAlias(), &toLength, &localStatus);
  2200. currDate64 = (int64_t)toArray[0] << 32;
  2201. currDate64 |= ((int64_t)toArray[1] & (int64_t)INT64_C(0x00000000FFFFFFFF));
  2202. UDate toDate = (UDate)currDate64;
  2203. if ((fromDate <= date) && (date < toDate))
  2204. {
  2205. currIndex++;
  2206. if (currIndex == index)
  2207. {
  2208. matchFound = true;
  2209. }
  2210. }
  2211. }
  2212. else
  2213. {
  2214. if (fromDate <= date)
  2215. {
  2216. currIndex++;
  2217. if (currIndex == index)
  2218. {
  2219. matchFound = true;
  2220. }
  2221. }
  2222. }
  2223. // check for loop exit
  2224. if (matchFound)
  2225. {
  2226. break;
  2227. }
  2228. } // end For loop
  2229. }
  2230. // Check for errors
  2231. if (*ec == U_ZERO_ERROR || localStatus != U_ZERO_ERROR)
  2232. {
  2233. // There is nothing to fallback to.
  2234. // Report the failure/warning if possible.
  2235. *ec = localStatus;
  2236. }
  2237. if (U_SUCCESS(*ec))
  2238. {
  2239. // no errors
  2240. if((buffCapacity> resLen) && matchFound)
  2241. {
  2242. // write out the currency value
  2243. u_strcpy(buff, s);
  2244. }
  2245. else
  2246. {
  2247. return 0;
  2248. }
  2249. }
  2250. // return null terminated currency string
  2251. return u_terminateUChars(buff, buffCapacity, resLen, ec);
  2252. }
  2253. else
  2254. {
  2255. // illegal argument encountered
  2256. *ec = U_ILLEGAL_ARGUMENT_ERROR;
  2257. }
  2258. }
  2259. // If we got here, either error code is invalid or
  2260. // some argument passed is no good.
  2261. return resLen;
  2262. }
  2263. static const UEnumeration defaultKeywordValues = {
  2264. nullptr,
  2265. nullptr,
  2266. ulist_close_keyword_values_iterator,
  2267. ulist_count_keyword_values,
  2268. uenum_unextDefault,
  2269. ulist_next_keyword_value,
  2270. ulist_reset_keyword_values_iterator
  2271. };
  2272. U_CAPI UEnumeration *U_EXPORT2 ucurr_getKeywordValuesForLocale(const char *key, const char *locale, UBool commonlyUsed, UErrorCode* status) {
  2273. // Resolve region
  2274. CharString prefRegion = ulocimp_getRegionForSupplementalData(locale, true, *status);
  2275. // Read value from supplementalData
  2276. UList *values = ulist_createEmptyList(status);
  2277. UList *otherValues = ulist_createEmptyList(status);
  2278. UEnumeration *en = (UEnumeration *)uprv_malloc(sizeof(UEnumeration));
  2279. if (U_FAILURE(*status) || en == nullptr) {
  2280. if (en == nullptr) {
  2281. *status = U_MEMORY_ALLOCATION_ERROR;
  2282. } else {
  2283. uprv_free(en);
  2284. }
  2285. ulist_deleteList(values);
  2286. ulist_deleteList(otherValues);
  2287. return nullptr;
  2288. }
  2289. memcpy(en, &defaultKeywordValues, sizeof(UEnumeration));
  2290. en->context = values;
  2291. UResourceBundle* rb = ures_openDirect(U_ICUDATA_CURR, "supplementalData", status);
  2292. LocalUResourceBundlePointer bundle(ures_getByKey(rb, "CurrencyMap", rb, status));
  2293. StackUResourceBundle bundlekey, regbndl, curbndl, to;
  2294. while (U_SUCCESS(*status) && ures_hasNext(bundle.getAlias())) {
  2295. ures_getNextResource(bundle.getAlias(), bundlekey.getAlias(), status);
  2296. if (U_FAILURE(*status)) {
  2297. break;
  2298. }
  2299. const char *region = ures_getKey(bundlekey.getAlias());
  2300. UBool isPrefRegion = prefRegion == region;
  2301. if (!isPrefRegion && commonlyUsed) {
  2302. // With commonlyUsed=true, we do not put
  2303. // currencies for other regions in the
  2304. // result list.
  2305. continue;
  2306. }
  2307. ures_getByKey(bundle.getAlias(), region, regbndl.getAlias(), status);
  2308. if (U_FAILURE(*status)) {
  2309. break;
  2310. }
  2311. while (U_SUCCESS(*status) && ures_hasNext(regbndl.getAlias())) {
  2312. ures_getNextResource(regbndl.getAlias(), curbndl.getAlias(), status);
  2313. if (ures_getType(curbndl.getAlias()) != URES_TABLE) {
  2314. // Currently, an empty ARRAY is mixed in.
  2315. continue;
  2316. }
  2317. char *curID = (char *)uprv_malloc(sizeof(char) * ULOC_KEYWORDS_CAPACITY);
  2318. if (curID == nullptr) {
  2319. *status = U_MEMORY_ALLOCATION_ERROR;
  2320. break;
  2321. }
  2322. int32_t curIDLength = ULOC_KEYWORDS_CAPACITY;
  2323. #if U_CHARSET_FAMILY==U_ASCII_FAMILY
  2324. ures_getUTF8StringByKey(curbndl.getAlias(), "id", curID, &curIDLength, true, status);
  2325. /* optimize - use the utf-8 string */
  2326. #else
  2327. {
  2328. const char16_t* defString = ures_getStringByKey(curbndl.getAlias(), "id", &curIDLength, status);
  2329. if(U_SUCCESS(*status)) {
  2330. if(curIDLength+1 > ULOC_KEYWORDS_CAPACITY) {
  2331. *status = U_BUFFER_OVERFLOW_ERROR;
  2332. } else {
  2333. u_UCharsToChars(defString, curID, curIDLength+1);
  2334. }
  2335. }
  2336. }
  2337. #endif
  2338. if (U_FAILURE(*status)) {
  2339. break;
  2340. }
  2341. UBool hasTo = false;
  2342. ures_getByKey(curbndl.getAlias(), "to", to.getAlias(), status);
  2343. if (U_FAILURE(*status)) {
  2344. // Do nothing here...
  2345. *status = U_ZERO_ERROR;
  2346. } else {
  2347. hasTo = true;
  2348. }
  2349. if (isPrefRegion && !hasTo && !ulist_containsString(values, curID, (int32_t)uprv_strlen(curID))) {
  2350. // Currently active currency for the target country
  2351. ulist_addItemEndList(values, curID, true, status);
  2352. } else if (!ulist_containsString(otherValues, curID, (int32_t)uprv_strlen(curID)) && !commonlyUsed) {
  2353. ulist_addItemEndList(otherValues, curID, true, status);
  2354. } else {
  2355. uprv_free(curID);
  2356. }
  2357. }
  2358. }
  2359. if (U_SUCCESS(*status)) {
  2360. if (commonlyUsed) {
  2361. if (ulist_getListSize(values) == 0) {
  2362. // This could happen if no valid region is supplied in the input
  2363. // locale. In this case, we use the CLDR's default.
  2364. uenum_close(en);
  2365. en = ucurr_getKeywordValuesForLocale(key, "und", true, status);
  2366. }
  2367. } else {
  2368. // Consolidate the list
  2369. char *value = nullptr;
  2370. ulist_resetList(otherValues);
  2371. while ((value = (char *)ulist_getNext(otherValues)) != nullptr) {
  2372. if (!ulist_containsString(values, value, (int32_t)uprv_strlen(value))) {
  2373. char *tmpValue = (char *)uprv_malloc(sizeof(char) * ULOC_KEYWORDS_CAPACITY);
  2374. if (tmpValue == nullptr) {
  2375. *status = U_MEMORY_ALLOCATION_ERROR;
  2376. break;
  2377. }
  2378. uprv_memcpy(tmpValue, value, uprv_strlen(value) + 1);
  2379. ulist_addItemEndList(values, tmpValue, true, status);
  2380. if (U_FAILURE(*status)) {
  2381. break;
  2382. }
  2383. }
  2384. }
  2385. }
  2386. ulist_resetList((UList *)(en->context));
  2387. } else {
  2388. ulist_deleteList(values);
  2389. uprv_free(en);
  2390. values = nullptr;
  2391. en = nullptr;
  2392. }
  2393. ulist_deleteList(otherValues);
  2394. return en;
  2395. }
  2396. U_CAPI int32_t U_EXPORT2
  2397. ucurr_getNumericCode(const char16_t* currency) {
  2398. int32_t code = 0;
  2399. if (currency && u_strlen(currency) == ISO_CURRENCY_CODE_LENGTH) {
  2400. UErrorCode status = U_ZERO_ERROR;
  2401. UResourceBundle* bundle = ures_openDirect(nullptr, "currencyNumericCodes", &status);
  2402. LocalUResourceBundlePointer codeMap(ures_getByKey(bundle, "codeMap", bundle, &status));
  2403. if (U_SUCCESS(status)) {
  2404. char alphaCode[ISO_CURRENCY_CODE_LENGTH+1];
  2405. myUCharsToChars(alphaCode, currency);
  2406. T_CString_toUpperCase(alphaCode);
  2407. ures_getByKey(codeMap.getAlias(), alphaCode, codeMap.getAlias(), &status);
  2408. int tmpCode = ures_getInt(codeMap.getAlias(), &status);
  2409. if (U_SUCCESS(status)) {
  2410. code = tmpCode;
  2411. }
  2412. }
  2413. }
  2414. return code;
  2415. }
  2416. #endif /* #if !UCONFIG_NO_FORMATTING */
  2417. //eof