Coverage Report

Created: 2023-11-27 06:54

/src/icu/icu4c/source/i18n/numfmt.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) 1997-2015, International Business Machines Corporation and
6
* others. All Rights Reserved.
7
*******************************************************************************
8
*
9
* File NUMFMT.CPP
10
*
11
* Modification History:
12
*
13
*   Date        Name        Description
14
*   02/19/97    aliu        Converted from java.
15
*   03/18/97    clhuang     Implemented with C++ APIs.
16
*   04/17/97    aliu        Enlarged MAX_INTEGER_DIGITS to fully accommodate the
17
*                           largest double, by default.
18
*                           Changed DigitCount to int per code review.
19
*    07/20/98    stephen        Changed operator== to check for grouping
20
*                            Changed setMaxIntegerDigits per Java implementation.
21
*                            Changed setMinIntegerDigits per Java implementation.
22
*                            Changed setMinFractionDigits per Java implementation.
23
*                            Changed setMaxFractionDigits per Java implementation.
24
********************************************************************************
25
*/
26
27
#include "unicode/utypes.h"
28
29
#if !UCONFIG_NO_FORMATTING
30
31
#include "unicode/numfmt.h"
32
#include "unicode/locid.h"
33
#include "unicode/dcfmtsym.h"
34
#include "unicode/decimfmt.h"
35
#include "unicode/ustring.h"
36
#include "unicode/ucurr.h"
37
#include "unicode/curramt.h"
38
#include "unicode/numsys.h"
39
#include "unicode/rbnf.h"
40
#include "unicode/localpointer.h"
41
#include "unicode/udisplaycontext.h"
42
#include "charstr.h"
43
#include "winnmfmt.h"
44
#include "uresimp.h"
45
#include "uhash.h"
46
#include "cmemory.h"
47
#include "servloc.h"
48
#include "ucln_in.h"
49
#include "cstring.h"
50
#include "putilimp.h"
51
#include "uassert.h"
52
#include "umutex.h"
53
#include "mutex.h"
54
#include <float.h>
55
#include "sharednumberformat.h"
56
#include "unifiedcache.h"
57
#include "number_decimalquantity.h"
58
#include "number_utils.h"
59
60
//#define FMT_DEBUG
61
62
#ifdef FMT_DEBUG
63
#include <stdio.h>
64
static inline void debugout(UnicodeString s) {
65
    char buf[2000];
66
    s.extract((int32_t) 0, s.length(), buf);
67
    printf("%s", buf);
68
}
69
#define debug(x) printf("%s", x);
70
#else
71
#define debugout(x)
72
#define debug(x)
73
#endif
74
75
// If no number pattern can be located for a locale, this is the last
76
// resort. The patterns are same as the ones in root locale.
77
static const char16_t gLastResortDecimalPat[] = {
78
    0x23, 0x2C, 0x23, 0x23, 0x30, 0x2E, 0x23, 0x23, 0x23, 0 /* "#,##0.###" */
79
};
80
static const char16_t gLastResortCurrencyPat[] = {
81
    0xA4, 0xA0, 0x23, 0x2C, 0x23, 0x23, 0x30, 0x2E, 0x30, 0x30, 0 /* "\u00A4\u00A0#,##0.00" */
82
};
83
static const char16_t gLastResortPercentPat[] = {
84
    0x23, 0x2C, 0x23, 0x23, 0x30, 0x25, 0 /* "#,##0%" */
85
};
86
static const char16_t gLastResortScientificPat[] = {
87
    0x23, 0x45, 0x30, 0 /* "#E0" */
88
};
89
static const char16_t gLastResortIsoCurrencyPat[] = {
90
    0xA4, 0xA4, 0xA0, 0x23, 0x2C, 0x23, 0x23, 0x30, 0x2E, 0x30, 0x30, 0  /* "\u00A4\u00A4\u00A0#,##0.00" */
91
};
92
static const char16_t gLastResortPluralCurrencyPat[] = {
93
    0x23, 0x2C, 0x23, 0x23, 0x30, 0x2E, 0x23, 0x23, 0x23, 0x20, 0xA4, 0xA4, 0xA4, 0 /* "#,##0.### \u00A4\u00A4\u00A4*/
94
};
95
static const char16_t gLastResortAccountingCurrencyPat[] =  {
96
    0xA4, 0xA0, 0x23, 0x2C, 0x23, 0x23, 0x30, 0x2E, 0x30, 0x30, 0 /* "\u00A4\u00A0#,##0.00" */
97
};
98
99
static const char16_t gSingleCurrencySign[] = {0xA4, 0};
100
static const char16_t gDoubleCurrencySign[] = {0xA4, 0xA4, 0};
101
102
static const char16_t gSlash = 0x2f;
103
104
// If the maximum base 10 exponent were 4, then the largest number would
105
// be 99,999 which has 5 digits.
106
// On IEEE754 systems gMaxIntegerDigits is 308 + possible denormalized 15 digits + rounding digit
107
// With big decimal, the max exponent is 999,999,999 and the max number of digits is the same, 999,999,999
108
const int32_t icu::NumberFormat::gDefaultMaxIntegerDigits = 2000000000;
109
const int32_t icu::NumberFormat::gDefaultMinIntegerDigits = 127;
110
111
static const char16_t * const gLastResortNumberPatterns[UNUM_FORMAT_STYLE_COUNT] = {
112
    nullptr,  // UNUM_PATTERN_DECIMAL
113
    gLastResortDecimalPat,  // UNUM_DECIMAL
114
    gLastResortCurrencyPat,  // UNUM_CURRENCY
115
    gLastResortPercentPat,  // UNUM_PERCENT
116
    gLastResortScientificPat,  // UNUM_SCIENTIFIC
117
    nullptr,  // UNUM_SPELLOUT
118
    nullptr,  // UNUM_ORDINAL
119
    nullptr,  // UNUM_DURATION
120
    gLastResortDecimalPat,  // UNUM_NUMBERING_SYSTEM
121
    nullptr,  // UNUM_PATTERN_RULEBASED
122
    gLastResortIsoCurrencyPat,  // UNUM_CURRENCY_ISO
123
    gLastResortPluralCurrencyPat,  // UNUM_CURRENCY_PLURAL
124
    gLastResortAccountingCurrencyPat, // UNUM_CURRENCY_ACCOUNTING
125
    gLastResortCurrencyPat,  // UNUM_CASH_CURRENCY 
126
    nullptr,  // UNUM_DECIMAL_COMPACT_SHORT
127
    nullptr,  // UNUM_DECIMAL_COMPACT_LONG
128
    gLastResortCurrencyPat,  // UNUM_CURRENCY_STANDARD
129
};
130
131
// Keys used for accessing resource bundles
132
133
static const icu::number::impl::CldrPatternStyle gFormatCldrStyles[UNUM_FORMAT_STYLE_COUNT] = {
134
    /* nullptr */ icu::number::impl::CLDR_PATTERN_STYLE_COUNT,  // UNUM_PATTERN_DECIMAL
135
    icu::number::impl::CLDR_PATTERN_STYLE_DECIMAL,  // UNUM_DECIMAL
136
    icu::number::impl::CLDR_PATTERN_STYLE_CURRENCY,  // UNUM_CURRENCY
137
    icu::number::impl::CLDR_PATTERN_STYLE_PERCENT,  // UNUM_PERCENT
138
    icu::number::impl::CLDR_PATTERN_STYLE_SCIENTIFIC,  // UNUM_SCIENTIFIC
139
    /* nullptr */ icu::number::impl::CLDR_PATTERN_STYLE_COUNT,  // UNUM_SPELLOUT
140
    /* nullptr */ icu::number::impl::CLDR_PATTERN_STYLE_COUNT,  // UNUM_ORDINAL
141
    /* nullptr */ icu::number::impl::CLDR_PATTERN_STYLE_COUNT,  // UNUM_DURATION
142
    /* nullptr */ icu::number::impl::CLDR_PATTERN_STYLE_COUNT,  // UNUM_NUMBERING_SYSTEM
143
    /* nullptr */ icu::number::impl::CLDR_PATTERN_STYLE_COUNT,  // UNUM_PATTERN_RULEBASED
144
    // For UNUM_CURRENCY_ISO and UNUM_CURRENCY_PLURAL,
145
    // the pattern is the same as the pattern of UNUM_CURRENCY
146
    // except for replacing the single currency sign with
147
    // double currency sign or triple currency sign.
148
    icu::number::impl::CLDR_PATTERN_STYLE_CURRENCY,  // UNUM_CURRENCY_ISO
149
    icu::number::impl::CLDR_PATTERN_STYLE_CURRENCY,  // UNUM_CURRENCY_PLURAL
150
    icu::number::impl::CLDR_PATTERN_STYLE_ACCOUNTING,  // UNUM_CURRENCY_ACCOUNTING
151
    icu::number::impl::CLDR_PATTERN_STYLE_CURRENCY,  // UNUM_CASH_CURRENCY
152
    /* nullptr */ icu::number::impl::CLDR_PATTERN_STYLE_COUNT,  // UNUM_DECIMAL_COMPACT_SHORT
153
    /* nullptr */ icu::number::impl::CLDR_PATTERN_STYLE_COUNT,  // UNUM_DECIMAL_COMPACT_LONG
154
    icu::number::impl::CLDR_PATTERN_STYLE_CURRENCY,  // UNUM_CURRENCY_STANDARD
155
};
156
157
// Static hashtable cache of NumberingSystem objects used by NumberFormat
158
static UHashtable * NumberingSystem_cache = nullptr;
159
static icu::UInitOnce gNSCacheInitOnce {};
160
161
#if !UCONFIG_NO_SERVICE
162
static icu::ICULocaleService* gService = nullptr;
163
static icu::UInitOnce gServiceInitOnce {};
164
#endif
165
166
/**
167
 * Release all static memory held by Number Format.
168
 */
169
U_CDECL_BEGIN
170
static void U_CALLCONV
171
0
deleteNumberingSystem(void *obj) {
172
0
    delete (icu::NumberingSystem *)obj;
173
0
}
174
175
0
static UBool U_CALLCONV numfmt_cleanup() {
176
0
#if !UCONFIG_NO_SERVICE
177
0
    gServiceInitOnce.reset();
178
0
    if (gService) {
179
0
        delete gService;
180
0
        gService = nullptr;
181
0
    }
182
0
#endif
183
0
    gNSCacheInitOnce.reset();
184
0
    if (NumberingSystem_cache) {
185
        // delete NumberingSystem_cache;
186
0
        uhash_close(NumberingSystem_cache);
187
0
        NumberingSystem_cache = nullptr;
188
0
    }
189
0
    return true;
190
0
}
191
U_CDECL_END
192
193
// *****************************************************************************
194
// class NumberFormat
195
// *****************************************************************************
196
197
U_NAMESPACE_BEGIN
198
199
UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(NumberFormat)
200
201
#if !UCONFIG_NO_SERVICE
202
// -------------------------------------
203
// SimpleNumberFormatFactory implementation
204
0
NumberFormatFactory::~NumberFormatFactory() {}
205
SimpleNumberFormatFactory::SimpleNumberFormatFactory(const Locale& locale, UBool visible)
206
    : _visible(visible)
207
0
{
208
0
    LocaleUtility::initNameFromLocale(locale, _id);
209
0
}
210
211
0
SimpleNumberFormatFactory::~SimpleNumberFormatFactory() {}
212
213
0
UBool SimpleNumberFormatFactory::visible() const {
214
0
    return _visible;
215
0
}
216
217
const UnicodeString *
218
SimpleNumberFormatFactory::getSupportedIDs(int32_t &count, UErrorCode& status) const
219
0
{
220
0
    if (U_SUCCESS(status)) {
221
0
        count = 1;
222
0
        return &_id;
223
0
    }
224
0
    count = 0;
225
0
    return nullptr;
226
0
}
227
#endif /* #if !UCONFIG_NO_SERVICE */
228
229
// -------------------------------------
230
// default constructor
231
NumberFormat::NumberFormat()
232
:   fGroupingUsed(true),
233
    fMaxIntegerDigits(gDefaultMaxIntegerDigits),
234
    fMinIntegerDigits(1),
235
    fMaxFractionDigits(3), // invariant, >= minFractionDigits
236
    fMinFractionDigits(0),
237
    fParseIntegerOnly(false),
238
    fLenient(false),
239
    fCapitalizationContext(UDISPCTX_CAPITALIZATION_NONE)
240
15.7k
{
241
15.7k
    fCurrency[0] = 0;
242
15.7k
}
243
244
// -------------------------------------
245
246
NumberFormat::~NumberFormat()
247
56.4k
{
248
56.4k
}
249
250
2.58k
SharedNumberFormat::~SharedNumberFormat() {
251
2.58k
    delete ptr;
252
2.58k
}
253
254
// -------------------------------------
255
// copy constructor
256
257
NumberFormat::NumberFormat(const NumberFormat &source)
258
:   Format(source)
259
41.8k
{
260
41.8k
    *this = source;
261
41.8k
}
262
263
// -------------------------------------
264
// assignment operator
265
266
NumberFormat&
267
NumberFormat::operator=(const NumberFormat& rhs)
268
42.3k
{
269
42.3k
    if (this != &rhs)
270
42.3k
    {
271
42.3k
        Format::operator=(rhs);
272
42.3k
        fGroupingUsed = rhs.fGroupingUsed;
273
42.3k
        fMaxIntegerDigits = rhs.fMaxIntegerDigits;
274
42.3k
        fMinIntegerDigits = rhs.fMinIntegerDigits;
275
42.3k
        fMaxFractionDigits = rhs.fMaxFractionDigits;
276
42.3k
        fMinFractionDigits = rhs.fMinFractionDigits;
277
42.3k
        fParseIntegerOnly = rhs.fParseIntegerOnly;
278
42.3k
        u_strncpy(fCurrency, rhs.fCurrency, 3);
279
42.3k
        fCurrency[3] = 0;
280
42.3k
        fLenient = rhs.fLenient;
281
42.3k
        fCapitalizationContext = rhs.fCapitalizationContext;
282
42.3k
    }
283
42.3k
    return *this;
284
42.3k
}
285
286
// -------------------------------------
287
288
bool
289
NumberFormat::operator==(const Format& that) const
290
0
{
291
    // Format::operator== guarantees this cast is safe
292
0
    NumberFormat* other = (NumberFormat*)&that;
293
294
#ifdef FMT_DEBUG
295
    // This code makes it easy to determine why two format objects that should
296
    // be equal aren't.
297
    UBool first = true;
298
    if (!Format::operator==(that)) {
299
        if (first) { printf("[ "); first = false; } else { printf(", "); }
300
        debug("Format::!=");
301
    }
302
    if (!(fMaxIntegerDigits == other->fMaxIntegerDigits &&
303
          fMinIntegerDigits == other->fMinIntegerDigits)) {
304
        if (first) { printf("[ "); first = false; } else { printf(", "); }
305
        debug("Integer digits !=");
306
    }
307
    if (!(fMaxFractionDigits == other->fMaxFractionDigits &&
308
          fMinFractionDigits == other->fMinFractionDigits)) {
309
        if (first) { printf("[ "); first = false; } else { printf(", "); }
310
        debug("Fraction digits !=");
311
    }
312
    if (!(fGroupingUsed == other->fGroupingUsed)) {
313
        if (first) { printf("[ "); first = false; } else { printf(", "); }
314
        debug("fGroupingUsed != ");
315
    }
316
    if (!(fParseIntegerOnly == other->fParseIntegerOnly)) {
317
        if (first) { printf("[ "); first = false; } else { printf(", "); }
318
        debug("fParseIntegerOnly != ");
319
    }
320
    if (!(u_strcmp(fCurrency, other->fCurrency) == 0)) {
321
        if (first) { printf("[ "); first = false; } else { printf(", "); }
322
        debug("fCurrency !=");
323
    }
324
    if (!(fLenient == other->fLenient)) {
325
        if (first) { printf("[ "); first = false; } else { printf(", "); }
326
        debug("fLenient != ");
327
    }
328
    if (!(fCapitalizationContext == other->fCapitalizationContext)) {
329
        if (first) { printf("[ "); first = false; } else { printf(", "); }
330
        debug("fCapitalizationContext != ");
331
    }
332
    if (!first) { printf(" ]"); }
333
#endif
334
335
0
    return ((this == &that) ||
336
0
            ((Format::operator==(that) &&
337
0
              fMaxIntegerDigits == other->fMaxIntegerDigits &&
338
0
              fMinIntegerDigits == other->fMinIntegerDigits &&
339
0
              fMaxFractionDigits == other->fMaxFractionDigits &&
340
0
              fMinFractionDigits == other->fMinFractionDigits &&
341
0
              fGroupingUsed == other->fGroupingUsed &&
342
0
              fParseIntegerOnly == other->fParseIntegerOnly &&
343
0
              u_strcmp(fCurrency, other->fCurrency) == 0 &&
344
0
              fLenient == other->fLenient &&
345
0
              fCapitalizationContext == other->fCapitalizationContext)));
346
0
}
347
348
// -------------------------------------
349
// Default implementation sets unsupported error; subclasses should
350
// override.
351
352
UnicodeString&
353
NumberFormat::format(double /* unused number */,
354
                     UnicodeString& toAppendTo,
355
                     FieldPositionIterator* /* unused posIter */,
356
                     UErrorCode& status) const
357
0
{
358
0
    if (!U_FAILURE(status)) {
359
0
        status = U_UNSUPPORTED_ERROR;
360
0
    }
361
0
    return toAppendTo;
362
0
}
363
364
// -------------------------------------
365
// Default implementation sets unsupported error; subclasses should
366
// override.
367
368
UnicodeString&
369
NumberFormat::format(int32_t /* unused number */,
370
                     UnicodeString& toAppendTo,
371
                     FieldPositionIterator* /* unused posIter */,
372
                     UErrorCode& status) const
373
0
{
374
0
    if (!U_FAILURE(status)) {
375
0
        status = U_UNSUPPORTED_ERROR;
376
0
    }
377
0
    return toAppendTo;
378
0
}
379
380
// -------------------------------------
381
// Default implementation sets unsupported error; subclasses should
382
// override.
383
384
UnicodeString&
385
NumberFormat::format(int64_t /* unused number */,
386
                     UnicodeString& toAppendTo,
387
                     FieldPositionIterator* /* unused posIter */,
388
                     UErrorCode& status) const
389
0
{
390
0
    if (!U_FAILURE(status)) {
391
0
        status = U_UNSUPPORTED_ERROR;
392
0
    }
393
0
    return toAppendTo;
394
0
}
395
396
// ------------------------------------------
397
// These functions add the status code, just fall back to the non-status versions
398
UnicodeString&
399
NumberFormat::format(double number,
400
                     UnicodeString& appendTo,
401
                     FieldPosition& pos,
402
0
                     UErrorCode &status) const {
403
0
    if(U_SUCCESS(status)) {
404
0
        return format(number,appendTo,pos);
405
0
    } else {
406
0
        return appendTo;
407
0
    }
408
0
}
409
410
UnicodeString&
411
NumberFormat::format(int32_t number,
412
                     UnicodeString& appendTo,
413
                     FieldPosition& pos,
414
0
                     UErrorCode &status) const {
415
0
    if(U_SUCCESS(status)) {
416
0
        return format(number,appendTo,pos);
417
0
    } else {
418
0
        return appendTo;
419
0
    }
420
0
}
421
422
UnicodeString&
423
NumberFormat::format(int64_t number,
424
                     UnicodeString& appendTo,
425
                     FieldPosition& pos,
426
0
                     UErrorCode &status) const {
427
0
    if(U_SUCCESS(status)) {
428
0
        return format(number,appendTo,pos);
429
0
    } else {
430
0
        return appendTo;
431
0
    }
432
0
}
433
434
435
436
// -------------------------------------
437
// Decimal Number format() default implementation 
438
// Subclasses do not normally override this function, but rather the DigitList
439
// formatting functions..
440
//   The expected call chain from here is
441
//      this function ->
442
//      NumberFormat::format(Formattable  ->
443
//      DecimalFormat::format(DigitList    
444
//
445
//   Or, for subclasses of Formattable that do not know about DigitList,
446
//       this Function ->
447
//       NumberFormat::format(Formattable  ->
448
//       NumberFormat::format(DigitList  ->
449
//       XXXFormat::format(double
450
451
UnicodeString&
452
NumberFormat::format(StringPiece decimalNum,
453
                     UnicodeString& toAppendTo,
454
                     FieldPositionIterator* fpi,
455
                     UErrorCode& status) const
456
0
{
457
0
    Formattable f;
458
0
    f.setDecimalNumber(decimalNum, status);
459
0
    format(f, toAppendTo, fpi, status);
460
0
    return toAppendTo;
461
0
}
462
463
/**
464
 *
465
// Formats the number object and save the format
466
// result in the toAppendTo string buffer.
467
468
// utility to save/restore state, used in two overloads
469
// of format(const Formattable&...) below.
470
*
471
* Old purpose of ArgExtractor was to avoid const. Not thread safe!
472
*
473
* keeping it around as a shim.
474
*/
475
class ArgExtractor {
476
  const Formattable* num;
477
  char16_t save[4];
478
  UBool fWasCurrency;
479
480
 public:
481
  ArgExtractor(const NumberFormat& nf, const Formattable& obj, UErrorCode& status);
482
  ~ArgExtractor();
483
484
  const Formattable* number() const;
485
  const char16_t *iso() const;
486
  UBool wasCurrency() const;
487
};
488
489
inline const Formattable*
490
0
ArgExtractor::number() const {
491
0
  return num;
492
0
}
493
494
inline UBool
495
0
ArgExtractor::wasCurrency() const {
496
0
  return fWasCurrency;
497
0
}
498
499
inline const char16_t *
500
0
ArgExtractor::iso() const {
501
0
  return save;
502
0
}
503
504
ArgExtractor::ArgExtractor(const NumberFormat& /*nf*/, const Formattable& obj, UErrorCode& /*status*/)
505
0
  : num(&obj), fWasCurrency(false) {
506
507
0
    const UObject* o = obj.getObject(); // most commonly o==nullptr
508
0
    const CurrencyAmount* amt;
509
0
    if (o != nullptr && (amt = dynamic_cast<const CurrencyAmount*>(o)) != nullptr) {
510
        // getISOCurrency() returns a pointer to internal storage, so we
511
        // copy it to retain it across the call to setCurrency().
512
        //const char16_t* curr = amt->getISOCurrency();
513
0
        u_strcpy(save, amt->getISOCurrency());
514
0
        num = &amt->getNumber();
515
0
        fWasCurrency=true;
516
0
    } else {
517
0
      save[0]=0;
518
0
    }
519
0
}
520
521
0
ArgExtractor::~ArgExtractor() {
522
0
}
523
524
UnicodeString& NumberFormat::format(const number::impl::DecimalQuantity &number,
525
                      UnicodeString& appendTo,
526
                      FieldPositionIterator* posIter,
527
0
                      UErrorCode& status) const {
528
    // DecimalFormat overrides this function, and handles DigitList based big decimals.
529
    // Other subclasses (ChoiceFormat) do not (yet) handle DigitLists,
530
    // so this default implementation falls back to formatting decimal numbers as doubles.
531
0
    if (U_FAILURE(status)) {
532
0
        return appendTo;
533
0
    }
534
0
    double dnum = number.toDouble();
535
0
    format(dnum, appendTo, posIter, status);
536
0
    return appendTo;
537
0
}
538
539
540
541
UnicodeString&
542
NumberFormat::format(const number::impl::DecimalQuantity &number,
543
                     UnicodeString& appendTo,
544
                     FieldPosition& pos,
545
0
                     UErrorCode &status) const {
546
    // DecimalFormat overrides this function, and handles DigitList based big decimals.
547
    // Other subclasses (ChoiceFormat) do not (yet) handle DigitLists,
548
    // so this default implementation falls back to formatting decimal numbers as doubles.
549
0
    if (U_FAILURE(status)) {
550
0
        return appendTo;
551
0
    }
552
0
    double dnum = number.toDouble();
553
0
    format(dnum, appendTo, pos, status);
554
0
    return appendTo;
555
0
}
556
557
UnicodeString&
558
NumberFormat::format(const Formattable& obj,
559
                        UnicodeString& appendTo,
560
                        FieldPosition& pos,
561
                        UErrorCode& status) const
562
0
{
563
0
    if (U_FAILURE(status)) return appendTo;
564
565
0
    ArgExtractor arg(*this, obj, status);
566
0
    const Formattable *n = arg.number();
567
0
    const char16_t *iso = arg.iso();
568
569
0
    if(arg.wasCurrency() && u_strcmp(iso, getCurrency())) {
570
      // trying to format a different currency.
571
      // Right now, we clone.
572
0
      LocalPointer<NumberFormat> cloneFmt(this->clone());
573
0
      cloneFmt->setCurrency(iso, status);
574
      // next line should NOT recurse, because n is numeric whereas obj was a wrapper around currency amount.
575
0
      return cloneFmt->format(*n, appendTo, pos, status);
576
0
    }
577
578
0
    if (n->isNumeric() && n->getDecimalQuantity() != nullptr) {
579
        // Decimal Number.  We will have a DigitList available if the value was
580
        //   set to a decimal number, or if the value originated with a parse.
581
        //
582
        // The default implementation for formatting a DigitList converts it
583
        // to a double, and formats that, allowing formatting classes that don't
584
        // know about DigitList to continue to operate as they had.
585
        //
586
        // DecimalFormat overrides the DigitList formatting functions.
587
0
        format(*n->getDecimalQuantity(), appendTo, pos, status);
588
0
    } else {
589
0
        switch (n->getType()) {
590
0
        case Formattable::kDouble:
591
0
            format(n->getDouble(), appendTo, pos, status);
592
0
            break;
593
0
        case Formattable::kLong:
594
0
            format(n->getLong(), appendTo, pos, status);
595
0
            break;
596
0
        case Formattable::kInt64:
597
0
            format(n->getInt64(), appendTo, pos, status);
598
0
            break;
599
0
        default:
600
0
            status = U_INVALID_FORMAT_ERROR;
601
0
            break;
602
0
        }
603
0
    }
604
605
0
    return appendTo;
606
0
}
607
608
// -------------------------------------x
609
// Formats the number object and save the format
610
// result in the toAppendTo string buffer.
611
612
UnicodeString&
613
NumberFormat::format(const Formattable& obj,
614
                        UnicodeString& appendTo,
615
                        FieldPositionIterator* posIter,
616
                        UErrorCode& status) const
617
0
{
618
0
    if (U_FAILURE(status)) return appendTo;
619
620
0
    ArgExtractor arg(*this, obj, status);
621
0
    const Formattable *n = arg.number();
622
0
    const char16_t *iso = arg.iso();
623
624
0
    if(arg.wasCurrency() && u_strcmp(iso, getCurrency())) {
625
      // trying to format a different currency.
626
      // Right now, we clone.
627
0
      LocalPointer<NumberFormat> cloneFmt(this->clone());
628
0
      cloneFmt->setCurrency(iso, status);
629
      // next line should NOT recurse, because n is numeric whereas obj was a wrapper around currency amount.
630
0
      return cloneFmt->format(*n, appendTo, posIter, status);
631
0
    }
632
633
0
    if (n->isNumeric() && n->getDecimalQuantity() != nullptr) {
634
        // Decimal Number
635
0
        format(*n->getDecimalQuantity(), appendTo, posIter, status);
636
0
    } else {
637
0
        switch (n->getType()) {
638
0
        case Formattable::kDouble:
639
0
            format(n->getDouble(), appendTo, posIter, status);
640
0
            break;
641
0
        case Formattable::kLong:
642
0
            format(n->getLong(), appendTo, posIter, status);
643
0
            break;
644
0
        case Formattable::kInt64:
645
0
            format(n->getInt64(), appendTo, posIter, status);
646
0
            break;
647
0
        default:
648
0
            status = U_INVALID_FORMAT_ERROR;
649
0
            break;
650
0
        }
651
0
    }
652
653
0
    return appendTo;
654
0
}
655
656
// -------------------------------------
657
658
UnicodeString&
659
NumberFormat::format(int64_t number,
660
                     UnicodeString& appendTo,
661
                     FieldPosition& pos) const
662
0
{
663
    // default so we don't introduce a new abstract method
664
0
    return format((int32_t)number, appendTo, pos);
665
0
}
666
667
// -------------------------------------
668
// Parses the string and save the result object as well
669
// as the final parsed position.
670
671
void
672
NumberFormat::parseObject(const UnicodeString& source,
673
                             Formattable& result,
674
                             ParsePosition& parse_pos) const
675
0
{
676
0
    parse(source, result, parse_pos);
677
0
}
678
679
// -------------------------------------
680
// Formats a double number and save the result in a string.
681
682
UnicodeString&
683
NumberFormat::format(double number, UnicodeString& appendTo) const
684
0
{
685
0
    FieldPosition pos(FieldPosition::DONT_CARE);
686
0
    return format(number, appendTo, pos);
687
0
}
688
689
// -------------------------------------
690
// Formats a long number and save the result in a string.
691
692
UnicodeString&
693
NumberFormat::format(int32_t number, UnicodeString& appendTo) const
694
0
{
695
0
    FieldPosition pos(FieldPosition::DONT_CARE);
696
0
    return format(number, appendTo, pos);
697
0
}
698
699
// -------------------------------------
700
// Formats a long number and save the result in a string.
701
702
UnicodeString&
703
NumberFormat::format(int64_t number, UnicodeString& appendTo) const
704
0
{
705
0
    FieldPosition pos(FieldPosition::DONT_CARE);
706
0
    return format(number, appendTo, pos);
707
0
}
708
709
// -------------------------------------
710
// Parses the text and save the result object.  If the returned
711
// parse position is 0, that means the parsing failed, the status
712
// code needs to be set to failure.  Ignores the returned parse
713
// position, otherwise.
714
715
void
716
NumberFormat::parse(const UnicodeString& text,
717
                        Formattable& result,
718
                        UErrorCode& status) const
719
2.93k
{
720
2.93k
    if (U_FAILURE(status)) return;
721
722
2.93k
    ParsePosition parsePosition(0);
723
2.93k
    parse(text, result, parsePosition);
724
2.93k
    if (parsePosition.getIndex() == 0) {
725
807
        status = U_INVALID_FORMAT_ERROR;
726
807
    }
727
2.93k
}
728
729
CurrencyAmount* NumberFormat::parseCurrency(const UnicodeString& text,
730
0
                                            ParsePosition& pos) const {
731
    // Default implementation only -- subclasses should override
732
0
    Formattable parseResult;
733
0
    int32_t start = pos.getIndex();
734
0
    parse(text, parseResult, pos);
735
0
    if (pos.getIndex() != start) {
736
0
        char16_t curr[4];
737
0
        UErrorCode ec = U_ZERO_ERROR;
738
0
        getEffectiveCurrency(curr, ec);
739
0
        if (U_SUCCESS(ec)) {
740
0
            LocalPointer<CurrencyAmount> currAmt(new CurrencyAmount(parseResult, curr, ec), ec);
741
0
            if (U_FAILURE(ec)) {
742
0
                pos.setIndex(start); // indicate failure
743
0
            } else {
744
0
                return currAmt.orphan();
745
0
            }
746
0
        }
747
0
    }
748
0
    return nullptr;
749
0
}
750
751
// -------------------------------------
752
// Sets to only parse integers.
753
754
void
755
NumberFormat::setParseIntegerOnly(UBool value)
756
38.8k
{
757
38.8k
    fParseIntegerOnly = value;
758
38.8k
}
759
760
// -------------------------------------
761
// Sets whether lenient parse is enabled.
762
763
void
764
NumberFormat::setLenient(UBool enable)
765
0
{
766
0
    fLenient = enable;
767
0
}
768
769
// -------------------------------------
770
// Create a number style NumberFormat instance with the default locale.
771
772
NumberFormat* U_EXPORT2
773
NumberFormat::createInstance(UErrorCode& status)
774
0
{
775
0
    return createInstance(Locale::getDefault(), UNUM_DECIMAL, status);
776
0
}
777
778
// -------------------------------------
779
// Create a number style NumberFormat instance with the inLocale locale.
780
781
NumberFormat* U_EXPORT2
782
NumberFormat::createInstance(const Locale& inLocale, UErrorCode& status)
783
41.8k
{
784
41.8k
    return createInstance(inLocale, UNUM_DECIMAL, status);
785
41.8k
}
786
787
// -------------------------------------
788
// Create a currency style NumberFormat instance with the default locale.
789
790
NumberFormat* U_EXPORT2
791
NumberFormat::createCurrencyInstance(UErrorCode& status)
792
0
{
793
0
    return createCurrencyInstance(Locale::getDefault(),  status);
794
0
}
795
796
// -------------------------------------
797
// Create a currency style NumberFormat instance with the inLocale locale.
798
799
NumberFormat* U_EXPORT2
800
NumberFormat::createCurrencyInstance(const Locale& inLocale, UErrorCode& status)
801
0
{
802
0
    return createInstance(inLocale, UNUM_CURRENCY, status);
803
0
}
804
805
// -------------------------------------
806
// Create a percent style NumberFormat instance with the default locale.
807
808
NumberFormat* U_EXPORT2
809
NumberFormat::createPercentInstance(UErrorCode& status)
810
0
{
811
0
    return createInstance(Locale::getDefault(), UNUM_PERCENT, status);
812
0
}
813
814
// -------------------------------------
815
// Create a percent style NumberFormat instance with the inLocale locale.
816
817
NumberFormat* U_EXPORT2
818
NumberFormat::createPercentInstance(const Locale& inLocale, UErrorCode& status)
819
0
{
820
0
    return createInstance(inLocale, UNUM_PERCENT, status);
821
0
}
822
823
// -------------------------------------
824
// Create a scientific style NumberFormat instance with the default locale.
825
826
NumberFormat* U_EXPORT2
827
NumberFormat::createScientificInstance(UErrorCode& status)
828
0
{
829
0
    return createInstance(Locale::getDefault(), UNUM_SCIENTIFIC, status);
830
0
}
831
832
// -------------------------------------
833
// Create a scientific style NumberFormat instance with the inLocale locale.
834
835
NumberFormat* U_EXPORT2
836
NumberFormat::createScientificInstance(const Locale& inLocale, UErrorCode& status)
837
0
{
838
0
    return createInstance(inLocale, UNUM_SCIENTIFIC, status);
839
0
}
840
841
// -------------------------------------
842
843
const Locale* U_EXPORT2
844
NumberFormat::getAvailableLocales(int32_t& count)
845
0
{
846
0
    return Locale::getAvailableLocales(count);
847
0
}
848
849
// ------------------------------------------
850
//
851
// Registration
852
//
853
//-------------------------------------------
854
855
#if !UCONFIG_NO_SERVICE
856
857
// -------------------------------------
858
859
class ICUNumberFormatFactory : public ICUResourceBundleFactory {
860
public:
861
    virtual ~ICUNumberFormatFactory();
862
protected:
863
0
    virtual UObject* handleCreate(const Locale& loc, int32_t kind, const ICUService* /* service */, UErrorCode& status) const override {
864
0
        return NumberFormat::makeInstance(loc, (UNumberFormatStyle)kind, status);
865
0
    }
866
};
867
868
0
ICUNumberFormatFactory::~ICUNumberFormatFactory() {}
869
870
// -------------------------------------
871
872
class NFFactory : public LocaleKeyFactory {
873
private:
874
    NumberFormatFactory* _delegate;
875
    Hashtable* _ids;
876
877
public:
878
    NFFactory(NumberFormatFactory* delegate)
879
        : LocaleKeyFactory(delegate->visible() ? VISIBLE : INVISIBLE)
880
        , _delegate(delegate)
881
        , _ids(nullptr)
882
0
    {
883
0
    }
884
885
    virtual ~NFFactory();
886
887
    virtual UObject* create(const ICUServiceKey& key, const ICUService* service, UErrorCode& status) const override
888
0
    {
889
0
        if (handlesKey(key, status)) {
890
0
            const LocaleKey* lkey = dynamic_cast<const LocaleKey*>(&key);
891
0
            U_ASSERT(lkey != nullptr);
892
0
            Locale loc;
893
0
            lkey->canonicalLocale(loc);
894
0
            int32_t kind = lkey->kind();
895
896
0
            UObject* result = _delegate->createFormat(loc, (UNumberFormatStyle)kind);
897
0
            if (result == nullptr) {
898
0
                result = service->getKey(const_cast<ICUServiceKey&>(key) /* cast away const */, nullptr, this, status);
899
0
            }
900
0
            return result;
901
0
        }
902
0
        return nullptr;
903
0
    }
904
905
protected:
906
    /**
907
     * Return the set of ids that this factory supports (visible or
908
     * otherwise).  This can be called often and might need to be
909
     * cached if it is expensive to create.
910
     */
911
    virtual const Hashtable* getSupportedIDs(UErrorCode& status) const override
912
0
    {
913
0
        if (U_SUCCESS(status)) {
914
0
            if (!_ids) {
915
0
                int32_t count = 0;
916
0
                const UnicodeString * const idlist = _delegate->getSupportedIDs(count, status);
917
0
                ((NFFactory*)this)->_ids = new Hashtable(status); /* cast away const */
918
0
                if (_ids) {
919
0
                    for (int i = 0; i < count; ++i) {
920
0
                        _ids->put(idlist[i], (void*)this, status);
921
0
                    }
922
0
                }
923
0
            }
924
0
            return _ids;
925
0
        }
926
0
        return nullptr;
927
0
    }
928
};
929
930
NFFactory::~NFFactory()
931
0
{
932
0
    delete _delegate;
933
0
    delete _ids;
934
0
}
935
936
class ICUNumberFormatService : public ICULocaleService {
937
public:
938
    ICUNumberFormatService()
939
        : ICULocaleService(UNICODE_STRING_SIMPLE("Number Format"))
940
0
    {
941
0
        UErrorCode status = U_ZERO_ERROR;
942
0
        registerFactory(new ICUNumberFormatFactory(), status);
943
0
    }
944
945
    virtual ~ICUNumberFormatService();
946
947
0
    virtual UObject* cloneInstance(UObject* instance) const override {
948
0
        return ((NumberFormat*)instance)->clone();
949
0
    }
950
951
0
    virtual UObject* handleDefault(const ICUServiceKey& key, UnicodeString* /* actualID */, UErrorCode& status) const override {
952
0
        const LocaleKey* lkey = dynamic_cast<const LocaleKey*>(&key);
953
0
        U_ASSERT(lkey != nullptr);
954
0
        int32_t kind = lkey->kind();
955
0
        Locale loc;
956
0
        lkey->currentLocale(loc);
957
0
        return NumberFormat::makeInstance(loc, (UNumberFormatStyle)kind, status);
958
0
    }
959
960
0
    virtual UBool isDefault() const override {
961
0
        return countFactories() == 1;
962
0
    }
963
};
964
965
0
ICUNumberFormatService::~ICUNumberFormatService() {}
966
967
// -------------------------------------
968
969
0
static void U_CALLCONV initNumberFormatService() {
970
0
    U_ASSERT(gService == nullptr);
971
0
    ucln_i18n_registerCleanup(UCLN_I18N_NUMFMT, numfmt_cleanup);
972
0
    gService = new ICUNumberFormatService();
973
0
}
974
975
static ICULocaleService*
976
getNumberFormatService()
977
0
{
978
0
    umtx_initOnce(gServiceInitOnce, &initNumberFormatService);
979
0
    return gService;
980
0
}
981
982
3.06k
static UBool haveService() {
983
3.06k
    return !gServiceInitOnce.isReset() && (getNumberFormatService() != nullptr);
984
3.06k
}
985
986
// -------------------------------------
987
988
URegistryKey U_EXPORT2
989
NumberFormat::registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status)
990
0
{
991
0
    if (U_FAILURE(status)) {
992
0
        delete toAdopt;
993
0
        return nullptr;
994
0
    }
995
0
    ICULocaleService *service = getNumberFormatService();
996
0
    if (service) {
997
0
        NFFactory *tempnnf = new NFFactory(toAdopt);
998
0
        if (tempnnf != nullptr) {
999
0
            return service->registerFactory(tempnnf, status);
1000
0
        }
1001
0
    }
1002
0
    status = U_MEMORY_ALLOCATION_ERROR;
1003
0
    return nullptr;
1004
0
}
1005
1006
// -------------------------------------
1007
1008
UBool U_EXPORT2
1009
NumberFormat::unregister(URegistryKey key, UErrorCode& status)
1010
0
{
1011
0
    if (U_FAILURE(status)) {
1012
0
        return false;
1013
0
    }
1014
0
    if (haveService()) {
1015
0
        return gService->unregister(key, status);
1016
0
    } else {
1017
0
        status = U_ILLEGAL_ARGUMENT_ERROR;
1018
0
        return false;
1019
0
    }
1020
0
}
1021
1022
// -------------------------------------
1023
StringEnumeration* U_EXPORT2
1024
NumberFormat::getAvailableLocales()
1025
0
{
1026
0
  ICULocaleService *service = getNumberFormatService();
1027
0
  if (service) {
1028
0
      return service->getAvailableLocales();
1029
0
  }
1030
0
  return nullptr; // no way to return error condition
1031
0
}
1032
#endif /* UCONFIG_NO_SERVICE */
1033
// -------------------------------------
1034
1035
enum { kKeyValueLenMax = 32 };
1036
1037
NumberFormat*
1038
3.06k
NumberFormat::internalCreateInstance(const Locale& loc, UNumberFormatStyle kind, UErrorCode& status) {
1039
3.06k
    if (kind == UNUM_CURRENCY) {
1040
0
        char cfKeyValue[kKeyValueLenMax] = {0};
1041
0
        UErrorCode kvStatus = U_ZERO_ERROR;
1042
0
        int32_t kLen = loc.getKeywordValue("cf", cfKeyValue, kKeyValueLenMax, kvStatus);
1043
0
        if (U_SUCCESS(kvStatus) && kLen > 0 && uprv_strcmp(cfKeyValue,"account")==0) {
1044
0
            kind = UNUM_CURRENCY_ACCOUNTING;
1045
0
        }
1046
0
    }
1047
3.06k
#if !UCONFIG_NO_SERVICE
1048
3.06k
    if (haveService()) {
1049
0
        return (NumberFormat*)gService->get(loc, kind, status);
1050
0
    }
1051
3.06k
#endif
1052
3.06k
    return makeInstance(loc, kind, status);
1053
3.06k
}
1054
1055
NumberFormat* U_EXPORT2
1056
41.8k
NumberFormat::createInstance(const Locale& loc, UNumberFormatStyle kind, UErrorCode& status) {
1057
41.8k
    if (kind != UNUM_DECIMAL) {
1058
0
        return internalCreateInstance(loc, kind, status);
1059
0
    }
1060
41.8k
    const SharedNumberFormat *shared = createSharedInstance(loc, kind, status);
1061
41.8k
    if (U_FAILURE(status)) {
1062
0
        return nullptr;
1063
0
    }
1064
41.8k
    NumberFormat *result = (*shared)->clone();
1065
41.8k
    shared->removeRef();
1066
41.8k
    if (result == nullptr) {
1067
0
        status = U_MEMORY_ALLOCATION_ERROR;
1068
0
    }
1069
41.8k
    return result;
1070
41.8k
}
1071
    
1072
1073
// -------------------------------------
1074
// Checks if the thousand/10 thousand grouping is used in the
1075
// NumberFormat instance.
1076
1077
UBool
1078
NumberFormat::isGroupingUsed() const
1079
0
{
1080
0
    return fGroupingUsed;
1081
0
}
1082
1083
// -------------------------------------
1084
// Sets to use the thousand/10 thousand grouping in the
1085
// NumberFormat instance.
1086
1087
void
1088
NumberFormat::setGroupingUsed(UBool newValue)
1089
148k
{
1090
148k
    fGroupingUsed = newValue;
1091
148k
}
1092
1093
// -------------------------------------
1094
// Gets the maximum number of digits for the integral part for
1095
// this NumberFormat instance.
1096
1097
int32_t NumberFormat::getMaximumIntegerDigits() const
1098
0
{
1099
0
    return fMaxIntegerDigits;
1100
0
}
1101
1102
// -------------------------------------
1103
// Sets the maximum number of digits for the integral part for
1104
// this NumberFormat instance.
1105
1106
void
1107
NumberFormat::setMaximumIntegerDigits(int32_t newValue)
1108
121k
{
1109
121k
    fMaxIntegerDigits = uprv_max(0, uprv_min(newValue, gDefaultMaxIntegerDigits));
1110
121k
    if(fMinIntegerDigits > fMaxIntegerDigits)
1111
0
        fMinIntegerDigits = fMaxIntegerDigits;
1112
121k
}
1113
1114
// -------------------------------------
1115
// Gets the minimum number of digits for the integral part for
1116
// this NumberFormat instance.
1117
1118
int32_t
1119
NumberFormat::getMinimumIntegerDigits() const
1120
0
{
1121
0
    return fMinIntegerDigits;
1122
0
}
1123
1124
// -------------------------------------
1125
// Sets the minimum number of digits for the integral part for
1126
// this NumberFormat instance.
1127
1128
void
1129
NumberFormat::setMinimumIntegerDigits(int32_t newValue)
1130
121k
{
1131
121k
    fMinIntegerDigits = uprv_max(0, uprv_min(newValue, gDefaultMinIntegerDigits));
1132
121k
    if(fMinIntegerDigits > fMaxIntegerDigits)
1133
0
        fMaxIntegerDigits = fMinIntegerDigits;
1134
121k
}
1135
1136
// -------------------------------------
1137
// Gets the maximum number of digits for the fractional part for
1138
// this NumberFormat instance.
1139
1140
int32_t
1141
NumberFormat::getMaximumFractionDigits() const
1142
0
{
1143
0
    return fMaxFractionDigits;
1144
0
}
1145
1146
// -------------------------------------
1147
// Sets the maximum number of digits for the fractional part for
1148
// this NumberFormat instance.
1149
1150
void
1151
NumberFormat::setMaximumFractionDigits(int32_t newValue)
1152
121k
{
1153
121k
    fMaxFractionDigits = uprv_max(0, uprv_min(newValue, gDefaultMaxIntegerDigits));
1154
121k
    if(fMaxFractionDigits < fMinFractionDigits)
1155
0
        fMinFractionDigits = fMaxFractionDigits;
1156
121k
}
1157
1158
// -------------------------------------
1159
// Gets the minimum number of digits for the fractional part for
1160
// this NumberFormat instance.
1161
1162
int32_t
1163
NumberFormat::getMinimumFractionDigits() const
1164
0
{
1165
0
    return fMinFractionDigits;
1166
0
}
1167
1168
// -------------------------------------
1169
// Sets the minimum number of digits for the fractional part for
1170
// this NumberFormat instance.
1171
1172
void
1173
NumberFormat::setMinimumFractionDigits(int32_t newValue)
1174
122k
{
1175
122k
    fMinFractionDigits = uprv_max(0, uprv_min(newValue, gDefaultMinIntegerDigits));
1176
122k
    if (fMaxFractionDigits < fMinFractionDigits)
1177
0
        fMaxFractionDigits = fMinFractionDigits;
1178
122k
}
1179
1180
// -------------------------------------
1181
1182
121k
void NumberFormat::setCurrency(const char16_t* theCurrency, UErrorCode& ec) {
1183
121k
    if (U_FAILURE(ec)) {
1184
0
        return;
1185
0
    }
1186
121k
    if (theCurrency) {
1187
121k
        u_strncpy(fCurrency, theCurrency, 3);
1188
121k
        fCurrency[3] = 0;
1189
121k
    } else {
1190
0
        fCurrency[0] = 0;
1191
0
    }
1192
121k
}
1193
1194
0
const char16_t* NumberFormat::getCurrency() const {
1195
0
    return fCurrency;
1196
0
}
1197
1198
0
void NumberFormat::getEffectiveCurrency(char16_t* result, UErrorCode& ec) const {
1199
0
    const char16_t* c = getCurrency();
1200
0
    if (*c != 0) {
1201
0
        u_strncpy(result, c, 3);
1202
0
        result[3] = 0;
1203
0
    } else {
1204
0
        const char* loc = getLocaleID(ULOC_VALID_LOCALE, ec);
1205
0
        if (loc == nullptr) {
1206
0
            loc = uloc_getDefault();
1207
0
        }
1208
0
        ucurr_forLocale(loc, result, 4, &ec);
1209
0
    }
1210
0
}
1211
1212
//----------------------------------------------------------------------
1213
1214
1215
void NumberFormat::setContext(UDisplayContext value, UErrorCode& status)
1216
0
{
1217
0
    if (U_FAILURE(status))
1218
0
        return;
1219
0
    if ( (UDisplayContextType)((uint32_t)value >> 8) == UDISPCTX_TYPE_CAPITALIZATION ) {
1220
0
        fCapitalizationContext = value;
1221
0
    } else {
1222
0
        status = U_ILLEGAL_ARGUMENT_ERROR;
1223
0
   }
1224
0
}
1225
1226
1227
UDisplayContext NumberFormat::getContext(UDisplayContextType type, UErrorCode& status) const
1228
354
{
1229
354
    if (U_FAILURE(status))
1230
0
        return (UDisplayContext)0;
1231
354
    if (type != UDISPCTX_TYPE_CAPITALIZATION) {
1232
0
        status = U_ILLEGAL_ARGUMENT_ERROR;
1233
0
        return (UDisplayContext)0;
1234
0
    }
1235
354
    return fCapitalizationContext;
1236
354
}
1237
1238
1239
// -------------------------------------
1240
// Creates the NumberFormat instance of the specified style (number, currency,
1241
// or percent) for the desired locale.
1242
1243
3
static void U_CALLCONV nscacheInit() {
1244
3
    U_ASSERT(NumberingSystem_cache == nullptr);
1245
3
    ucln_i18n_registerCleanup(UCLN_I18N_NUMFMT, numfmt_cleanup);
1246
3
    UErrorCode status = U_ZERO_ERROR;
1247
3
    NumberingSystem_cache = uhash_open(uhash_hashLong,
1248
3
                                       uhash_compareLong,
1249
3
                                       nullptr,
1250
3
                                       &status);
1251
3
    if (U_FAILURE(status)) {
1252
        // Number Format code will run with no cache if creation fails.
1253
0
        NumberingSystem_cache = nullptr;
1254
0
        return;
1255
0
    }
1256
3
    uhash_setValueDeleter(NumberingSystem_cache, deleteNumberingSystem);
1257
3
}
1258
1259
template<> U_I18N_API
1260
const SharedNumberFormat *LocaleCacheKey<SharedNumberFormat>::createObject(
1261
3.06k
        const void * /*unused*/, UErrorCode &status) const {
1262
3.06k
    const char *localeId = fLoc.getName();
1263
3.06k
    NumberFormat *nf = NumberFormat::internalCreateInstance(
1264
3.06k
            localeId, UNUM_DECIMAL, status);
1265
3.06k
    if (U_FAILURE(status)) {
1266
0
        return nullptr;
1267
0
    }
1268
3.06k
    SharedNumberFormat *result = new SharedNumberFormat(nf);
1269
3.06k
    if (result == nullptr) {
1270
0
        status = U_MEMORY_ALLOCATION_ERROR;
1271
0
        delete nf;
1272
0
        return nullptr;
1273
0
    }
1274
3.06k
    result->addRef();
1275
3.06k
    return result;
1276
3.06k
}
1277
1278
const SharedNumberFormat* U_EXPORT2
1279
44.1k
NumberFormat::createSharedInstance(const Locale& loc, UNumberFormatStyle kind, UErrorCode& status) {
1280
44.1k
    if (U_FAILURE(status)) {
1281
0
        return nullptr;
1282
0
    }
1283
44.1k
    if (kind != UNUM_DECIMAL) {
1284
0
        status = U_UNSUPPORTED_ERROR;
1285
0
        return nullptr;
1286
0
    }
1287
44.1k
    const SharedNumberFormat *result = nullptr;
1288
44.1k
    UnifiedCache::getByLocale(loc, result, status);
1289
44.1k
    return result;
1290
44.1k
}
1291
1292
UBool
1293
3.06k
NumberFormat::isStyleSupported(UNumberFormatStyle style) {
1294
3.06k
    return gLastResortNumberPatterns[style] != nullptr;
1295
3.06k
}
1296
1297
NumberFormat*
1298
NumberFormat::makeInstance(const Locale& desiredLocale,
1299
                           UNumberFormatStyle style,
1300
3.06k
                           UErrorCode& status) {
1301
3.06k
  return makeInstance(desiredLocale, style, false, status);
1302
3.06k
}
1303
1304
NumberFormat*
1305
NumberFormat::makeInstance(const Locale& desiredLocale,
1306
                           UNumberFormatStyle style,
1307
                           UBool mustBeDecimalFormat,
1308
3.06k
                           UErrorCode& status) {
1309
3.06k
    if (U_FAILURE(status)) return nullptr;
1310
1311
3.06k
    if (style < 0 || style >= UNUM_FORMAT_STYLE_COUNT) {
1312
0
        status = U_ILLEGAL_ARGUMENT_ERROR;
1313
0
        return nullptr;
1314
0
    }
1315
    
1316
    // For the purposes of general number formatting, UNUM_NUMBERING_SYSTEM should behave the same
1317
    // was as UNUM_DECIMAL.  In both cases, you get either a DecimalFormat or a RuleBasedNumberFormat
1318
    // depending on the locale's numbering system (either the default one for the locale or a specific
1319
    // one specified by using the "@numbers=" or "-u-nu-" parameter in the locale ID.
1320
3.06k
    if (style == UNUM_NUMBERING_SYSTEM) {
1321
0
        style = UNUM_DECIMAL;
1322
0
    }
1323
1324
    // Some styles are not supported. This is a result of merging
1325
    // the @draft ICU 4.2 NumberFormat::EStyles into the long-existing UNumberFormatStyle.
1326
    // Ticket #8503 is for reviewing/fixing/merging the two relevant implementations:
1327
    // this one and unum_open().
1328
    // The UNUM_PATTERN_ styles are not supported here
1329
    // because this method does not take a pattern string.
1330
3.06k
    if (!isStyleSupported(style)) {
1331
0
        status = U_UNSUPPORTED_ERROR;
1332
0
        return nullptr;
1333
0
    }
1334
1335
#if U_PLATFORM_USES_ONLY_WIN32_API
1336
    if (!mustBeDecimalFormat) {
1337
        char buffer[8];
1338
        int32_t count = desiredLocale.getKeywordValue("compat", buffer, sizeof(buffer), status);
1339
1340
        // if the locale has "@compat=host", create a host-specific NumberFormat
1341
        if (U_SUCCESS(status) && count > 0 && uprv_strcmp(buffer, "host") == 0) {
1342
            UBool curr = true;
1343
1344
            switch (style) {
1345
            case UNUM_DECIMAL:
1346
                curr = false;
1347
                // fall-through
1348
                U_FALLTHROUGH;
1349
1350
            case UNUM_CURRENCY:
1351
            case UNUM_CURRENCY_ISO: // do not support plural formatting here
1352
            case UNUM_CURRENCY_PLURAL:
1353
            case UNUM_CURRENCY_ACCOUNTING:
1354
            case UNUM_CASH_CURRENCY:
1355
            case UNUM_CURRENCY_STANDARD:
1356
            {
1357
                LocalPointer<Win32NumberFormat> f(new Win32NumberFormat(desiredLocale, curr, status), status);
1358
                if (U_SUCCESS(status)) {
1359
                    return f.orphan();
1360
                }
1361
            }
1362
            break;
1363
            default:
1364
                break;
1365
            }
1366
        }
1367
    }
1368
#endif
1369
    // Use numbering system cache hashtable
1370
3.06k
    umtx_initOnce(gNSCacheInitOnce, &nscacheInit);
1371
1372
    // Get cached numbering system
1373
3.06k
    LocalPointer<NumberingSystem> ownedNs;
1374
3.06k
    NumberingSystem *ns = nullptr;
1375
3.06k
    if (NumberingSystem_cache != nullptr) {
1376
        // TODO: Bad hash key usage, see ticket #8504.
1377
3.06k
        int32_t hashKey = desiredLocale.hashCode();
1378
1379
3.06k
        static UMutex nscacheMutex;
1380
3.06k
        Mutex lock(&nscacheMutex);
1381
3.06k
        ns = (NumberingSystem *)uhash_iget(NumberingSystem_cache, hashKey);
1382
3.06k
        if (ns == nullptr) {
1383
1.93k
            ns = NumberingSystem::createInstance(desiredLocale,status);
1384
1.93k
            uhash_iput(NumberingSystem_cache, hashKey, (void*)ns, &status);
1385
1.93k
        }
1386
3.06k
    } else {
1387
0
        ownedNs.adoptInstead(NumberingSystem::createInstance(desiredLocale,status));
1388
0
        ns = ownedNs.getAlias();
1389
0
    }
1390
1391
    // check results of getting a numbering system
1392
3.06k
    if (U_FAILURE(status)) {
1393
0
        return nullptr;
1394
0
    }
1395
1396
3.06k
    if (mustBeDecimalFormat && ns->isAlgorithmic()) {
1397
0
        status = U_UNSUPPORTED_ERROR;
1398
0
        return nullptr;
1399
0
    }
1400
1401
3.06k
    LocalPointer<DecimalFormatSymbols> symbolsToAdopt;
1402
3.06k
    UnicodeString pattern;
1403
3.06k
    LocalUResourceBundlePointer ownedResource(ures_open(nullptr, desiredLocale.getName(), &status));
1404
3.06k
    if (U_FAILURE(status)) {
1405
0
        return nullptr;
1406
0
    }
1407
3.06k
    else {
1408
        // Loads the decimal symbols of the desired locale.
1409
3.06k
        symbolsToAdopt.adoptInsteadAndCheckErrorCode(new DecimalFormatSymbols(desiredLocale, status), status);
1410
3.06k
        if (U_FAILURE(status)) {
1411
0
            return nullptr;
1412
0
        }
1413
1414
        // Load the pattern from data using the common library function
1415
3.06k
        const char16_t* patternPtr = number::impl::utils::getPatternForStyle(
1416
3.06k
                desiredLocale,
1417
3.06k
                ns->getName(),
1418
3.06k
                gFormatCldrStyles[style],
1419
3.06k
                status);
1420
3.06k
        pattern = UnicodeString(true, patternPtr, -1);
1421
3.06k
    }
1422
3.06k
    if (U_FAILURE(status)) {
1423
0
        return nullptr;
1424
0
    }
1425
3.06k
    if(style==UNUM_CURRENCY || style == UNUM_CURRENCY_ISO || style == UNUM_CURRENCY_ACCOUNTING 
1426
3.06k
        || style == UNUM_CASH_CURRENCY || style == UNUM_CURRENCY_STANDARD){
1427
0
        const char16_t* currPattern = symbolsToAdopt->getCurrencyPattern();
1428
0
        if(currPattern!=nullptr){
1429
0
            pattern.setTo(currPattern, u_strlen(currPattern));
1430
0
        }
1431
0
    }
1432
1433
3.06k
    LocalPointer<NumberFormat> f;
1434
3.06k
    if (ns->isAlgorithmic()) {
1435
11
        UnicodeString nsDesc;
1436
11
        UnicodeString nsRuleSetGroup;
1437
11
        UnicodeString nsRuleSetName;
1438
11
        Locale nsLoc;
1439
11
        URBNFRuleSetTag desiredRulesType = URBNF_NUMBERING_SYSTEM;
1440
1441
11
        nsDesc.setTo(ns->getDescription());
1442
11
        int32_t firstSlash = nsDesc.indexOf(gSlash);
1443
11
        int32_t lastSlash = nsDesc.lastIndexOf(gSlash);
1444
11
        if ( lastSlash > firstSlash ) {
1445
0
            CharString nsLocID;
1446
1447
0
            nsLocID.appendInvariantChars(nsDesc.tempSubString(0, firstSlash), status);
1448
0
            nsRuleSetGroup.setTo(nsDesc,firstSlash+1,lastSlash-firstSlash-1);
1449
0
            nsRuleSetName.setTo(nsDesc,lastSlash+1);
1450
1451
0
            nsLoc = Locale::createFromName(nsLocID.data());
1452
1453
0
            UnicodeString SpelloutRules = UNICODE_STRING_SIMPLE("SpelloutRules");
1454
0
            if ( nsRuleSetGroup.compare(SpelloutRules) == 0 ) {
1455
0
                desiredRulesType = URBNF_SPELLOUT;
1456
0
            }
1457
11
        } else {
1458
11
            nsLoc = desiredLocale;
1459
11
            nsRuleSetName.setTo(nsDesc);
1460
11
        }
1461
1462
11
        RuleBasedNumberFormat *r = new RuleBasedNumberFormat(desiredRulesType,nsLoc,status);
1463
11
        if (r == nullptr) {
1464
0
            status = U_MEMORY_ALLOCATION_ERROR;
1465
0
            return nullptr;
1466
0
        }
1467
11
        r->setDefaultRuleSet(nsRuleSetName,status);
1468
11
        f.adoptInstead(r);
1469
3.05k
    } else {
1470
        // replace single currency sign in the pattern with double currency sign
1471
        // if the style is UNUM_CURRENCY_ISO
1472
3.05k
        if (style == UNUM_CURRENCY_ISO) {
1473
0
            pattern.findAndReplace(UnicodeString(true, gSingleCurrencySign, 1),
1474
0
                                   UnicodeString(true, gDoubleCurrencySign, 2));
1475
0
        }
1476
1477
        // "new DecimalFormat()" does not adopt the symbols argument if its memory allocation fails.
1478
        // So we can't use adoptInsteadAndCheckErrorCode as we need to know if the 'new' failed.
1479
3.05k
        DecimalFormatSymbols *syms = symbolsToAdopt.getAlias();
1480
3.05k
        LocalPointer<DecimalFormat> df(new DecimalFormat(pattern, syms, style, status));
1481
1482
3.05k
        if (df.isValid()) {
1483
            // if the DecimalFormat object was successfully new'ed, then it will own symbolsToAdopt, even if the status is a failure.
1484
3.05k
            symbolsToAdopt.orphan();
1485
3.05k
        }
1486
0
        else {
1487
0
            status = U_MEMORY_ALLOCATION_ERROR;
1488
0
        }
1489
1490
3.05k
        if (U_FAILURE(status)) {
1491
0
            return nullptr;
1492
0
        }
1493
1494
        // if it is cash currency style, setCurrencyUsage with usage
1495
3.05k
        if (style == UNUM_CASH_CURRENCY){
1496
0
            df->setCurrencyUsage(UCURR_USAGE_CASH, &status);
1497
0
        }
1498
1499
3.05k
        if (U_FAILURE(status)) {
1500
0
            return nullptr;
1501
0
        }
1502
1503
3.05k
        f.adoptInstead(df.orphan());
1504
3.05k
    }
1505
1506
3.06k
    f->setLocaleIDs(ures_getLocaleByType(ownedResource.getAlias(), ULOC_VALID_LOCALE, &status),
1507
3.06k
                    ures_getLocaleByType(ownedResource.getAlias(), ULOC_ACTUAL_LOCALE, &status));
1508
3.06k
    if (U_FAILURE(status)) {
1509
0
        return nullptr;
1510
0
    }
1511
3.06k
    return f.orphan();
1512
3.06k
}
1513
1514
/**
1515
 * Get the rounding mode.
1516
 * @return A rounding mode
1517
 */
1518
0
NumberFormat::ERoundingMode NumberFormat::getRoundingMode() const {
1519
    // Default value. ICU4J throws an exception and we can't change this API.
1520
0
    return NumberFormat::ERoundingMode::kRoundUnnecessary;
1521
0
}
1522
1523
/**
1524
 * Set the rounding mode.  This has no effect unless the rounding
1525
 * increment is greater than zero.
1526
 * @param roundingMode A rounding mode
1527
 */
1528
0
void NumberFormat::setRoundingMode(NumberFormat::ERoundingMode /*roundingMode*/) {
1529
    // No-op ICU4J throws an exception, and we can't change this API.
1530
0
}
1531
1532
U_NAMESPACE_END
1533
1534
#endif /* #if !UCONFIG_NO_FORMATTING */
1535
1536
//eof