Coverage Report

Created: 2018-09-25 14:53

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