Coverage Report

Created: 2023-03-29 06:15

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