• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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>
debugout(UnicodeString s)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
deleteNumberingSystem(void * obj)172 deleteNumberingSystem(void *obj) {
173     delete (icu::NumberingSystem *)obj;
174 }
175 
numfmt_cleanup(void)176 static UBool U_CALLCONV numfmt_cleanup(void) {
177 #if !UCONFIG_NO_SERVICE
178     gServiceInitOnce.reset();
179     if (gService) {
180         delete gService;
181         gService = NULL;
182     }
183 #endif
184     gNSCacheInitOnce.reset();
185     if (NumberingSystem_cache) {
186         // delete NumberingSystem_cache;
187         uhash_close(NumberingSystem_cache);
188         NumberingSystem_cache = NULL;
189     }
190     return TRUE;
191 }
192 U_CDECL_END
193 
194 // *****************************************************************************
195 // class NumberFormat
196 // *****************************************************************************
197 
198 U_NAMESPACE_BEGIN
199 
UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(NumberFormat)200 UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(NumberFormat)
201 
202 #if !UCONFIG_NO_SERVICE
203 // -------------------------------------
204 // SimpleNumberFormatFactory implementation
205 NumberFormatFactory::~NumberFormatFactory() {}
SimpleNumberFormatFactory(const Locale & locale,UBool visible)206 SimpleNumberFormatFactory::SimpleNumberFormatFactory(const Locale& locale, UBool visible)
207     : _visible(visible)
208 {
209     LocaleUtility::initNameFromLocale(locale, _id);
210 }
211 
~SimpleNumberFormatFactory()212 SimpleNumberFormatFactory::~SimpleNumberFormatFactory() {}
213 
visible(void) const214 UBool SimpleNumberFormatFactory::visible(void) const {
215     return _visible;
216 }
217 
218 const UnicodeString *
getSupportedIDs(int32_t & count,UErrorCode & status) const219 SimpleNumberFormatFactory::getSupportedIDs(int32_t &count, UErrorCode& status) const
220 {
221     if (U_SUCCESS(status)) {
222         count = 1;
223         return &_id;
224     }
225     count = 0;
226     return NULL;
227 }
228 #endif /* #if !UCONFIG_NO_SERVICE */
229 
230 // -------------------------------------
231 // default constructor
NumberFormat()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 {
242     fCurrency[0] = 0;
243 }
244 
245 // -------------------------------------
246 
~NumberFormat()247 NumberFormat::~NumberFormat()
248 {
249 }
250 
~SharedNumberFormat()251 SharedNumberFormat::~SharedNumberFormat() {
252     delete ptr;
253 }
254 
255 // -------------------------------------
256 // copy constructor
257 
NumberFormat(const NumberFormat & source)258 NumberFormat::NumberFormat(const NumberFormat &source)
259 :   Format(source)
260 {
261     *this = source;
262 }
263 
264 // -------------------------------------
265 // assignment operator
266 
267 NumberFormat&
operator =(const NumberFormat & rhs)268 NumberFormat::operator=(const NumberFormat& rhs)
269 {
270     if (this != &rhs)
271     {
272         Format::operator=(rhs);
273         fGroupingUsed = rhs.fGroupingUsed;
274         fMaxIntegerDigits = rhs.fMaxIntegerDigits;
275         fMinIntegerDigits = rhs.fMinIntegerDigits;
276         fMaxFractionDigits = rhs.fMaxFractionDigits;
277         fMinFractionDigits = rhs.fMinFractionDigits;
278         fParseIntegerOnly = rhs.fParseIntegerOnly;
279         u_strncpy(fCurrency, rhs.fCurrency, 3);
280         fCurrency[3] = 0;
281         fLenient = rhs.fLenient;
282         fCapitalizationContext = rhs.fCapitalizationContext;
283     }
284     return *this;
285 }
286 
287 // -------------------------------------
288 
289 UBool
operator ==(const Format & that) const290 NumberFormat::operator==(const Format& that) const
291 {
292     // Format::operator== guarantees this cast is safe
293     NumberFormat* other = (NumberFormat*)&that;
294 
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     return ((this == &that) ||
337             ((Format::operator==(that) &&
338               fMaxIntegerDigits == other->fMaxIntegerDigits &&
339               fMinIntegerDigits == other->fMinIntegerDigits &&
340               fMaxFractionDigits == other->fMaxFractionDigits &&
341               fMinFractionDigits == other->fMinFractionDigits &&
342               fGroupingUsed == other->fGroupingUsed &&
343               fParseIntegerOnly == other->fParseIntegerOnly &&
344               u_strcmp(fCurrency, other->fCurrency) == 0 &&
345               fLenient == other->fLenient &&
346               fCapitalizationContext == other->fCapitalizationContext)));
347 }
348 
349 // -------------------------------------
350 // Default implementation sets unsupported error; subclasses should
351 // override.
352 
353 UnicodeString&
format(double,UnicodeString & toAppendTo,FieldPositionIterator *,UErrorCode & status) const354 NumberFormat::format(double /* unused number */,
355                      UnicodeString& toAppendTo,
356                      FieldPositionIterator* /* unused posIter */,
357                      UErrorCode& status) const
358 {
359     if (!U_FAILURE(status)) {
360         status = U_UNSUPPORTED_ERROR;
361     }
362     return toAppendTo;
363 }
364 
365 // -------------------------------------
366 // Default implementation sets unsupported error; subclasses should
367 // override.
368 
369 UnicodeString&
format(int32_t,UnicodeString & toAppendTo,FieldPositionIterator *,UErrorCode & status) const370 NumberFormat::format(int32_t /* unused number */,
371                      UnicodeString& toAppendTo,
372                      FieldPositionIterator* /* unused posIter */,
373                      UErrorCode& status) const
374 {
375     if (!U_FAILURE(status)) {
376         status = U_UNSUPPORTED_ERROR;
377     }
378     return toAppendTo;
379 }
380 
381 // -------------------------------------
382 // Default implementation sets unsupported error; subclasses should
383 // override.
384 
385 UnicodeString&
format(int64_t,UnicodeString & toAppendTo,FieldPositionIterator *,UErrorCode & status) const386 NumberFormat::format(int64_t /* unused number */,
387                      UnicodeString& toAppendTo,
388                      FieldPositionIterator* /* unused posIter */,
389                      UErrorCode& status) const
390 {
391     if (!U_FAILURE(status)) {
392         status = U_UNSUPPORTED_ERROR;
393     }
394     return toAppendTo;
395 }
396 
397 // ------------------------------------------
398 // These functions add the status code, just fall back to the non-status versions
399 UnicodeString&
format(double number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const400 NumberFormat::format(double number,
401                      UnicodeString& appendTo,
402                      FieldPosition& pos,
403                      UErrorCode &status) const {
404     if(U_SUCCESS(status)) {
405         return format(number,appendTo,pos);
406     } else {
407         return appendTo;
408     }
409 }
410 
411 UnicodeString&
format(int32_t number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const412 NumberFormat::format(int32_t number,
413                      UnicodeString& appendTo,
414                      FieldPosition& pos,
415                      UErrorCode &status) const {
416     if(U_SUCCESS(status)) {
417         return format(number,appendTo,pos);
418     } else {
419         return appendTo;
420     }
421 }
422 
423 UnicodeString&
format(int64_t number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const424 NumberFormat::format(int64_t number,
425                      UnicodeString& appendTo,
426                      FieldPosition& pos,
427                      UErrorCode &status) const {
428     if(U_SUCCESS(status)) {
429         return format(number,appendTo,pos);
430     } else {
431         return appendTo;
432     }
433 }
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&
format(StringPiece decimalNum,UnicodeString & toAppendTo,FieldPositionIterator * fpi,UErrorCode & status) const453 NumberFormat::format(StringPiece decimalNum,
454                      UnicodeString& toAppendTo,
455                      FieldPositionIterator* fpi,
456                      UErrorCode& status) const
457 {
458     Formattable f;
459     f.setDecimalNumber(decimalNum, status);
460     format(f, toAppendTo, fpi, status);
461     return toAppendTo;
462 }
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*
number(void) const491 ArgExtractor::number(void) const {
492   return num;
493 }
494 
495 inline UBool
wasCurrency(void) const496 ArgExtractor::wasCurrency(void) const {
497   return fWasCurrency;
498 }
499 
500 inline const UChar *
iso(void) const501 ArgExtractor::iso(void) const {
502   return save;
503 }
504 
ArgExtractor(const NumberFormat &,const Formattable & obj,UErrorCode &)505 ArgExtractor::ArgExtractor(const NumberFormat& /*nf*/, const Formattable& obj, UErrorCode& /*status*/)
506   : num(&obj), fWasCurrency(FALSE) {
507 
508     const UObject* o = obj.getObject(); // most commonly o==NULL
509     const CurrencyAmount* amt;
510     if (o != NULL && (amt = dynamic_cast<const CurrencyAmount*>(o)) != NULL) {
511         // getISOCurrency() returns a pointer to internal storage, so we
512         // copy it to retain it across the call to setCurrency().
513         //const UChar* curr = amt->getISOCurrency();
514         u_strcpy(save, amt->getISOCurrency());
515         num = &amt->getNumber();
516         fWasCurrency=TRUE;
517     } else {
518       save[0]=0;
519     }
520 }
521 
~ArgExtractor()522 ArgExtractor::~ArgExtractor() {
523 }
524 
format(const number::impl::DecimalQuantity & number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const525 UnicodeString& NumberFormat::format(const number::impl::DecimalQuantity &number,
526                       UnicodeString& appendTo,
527                       FieldPositionIterator* posIter,
528                       UErrorCode& status) const {
529     // DecimalFormat overrides this function, and handles DigitList based big decimals.
530     // Other subclasses (ChoiceFormat) do not (yet) handle DigitLists,
531     // so this default implementation falls back to formatting decimal numbers as doubles.
532     if (U_FAILURE(status)) {
533         return appendTo;
534     }
535     double dnum = number.toDouble();
536     format(dnum, appendTo, posIter, status);
537     return appendTo;
538 }
539 
540 
541 
542 UnicodeString&
format(const number::impl::DecimalQuantity & number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const543 NumberFormat::format(const number::impl::DecimalQuantity &number,
544                      UnicodeString& appendTo,
545                      FieldPosition& pos,
546                      UErrorCode &status) const {
547     // DecimalFormat overrides this function, and handles DigitList based big decimals.
548     // Other subclasses (ChoiceFormat) do not (yet) handle DigitLists,
549     // so this default implementation falls back to formatting decimal numbers as doubles.
550     if (U_FAILURE(status)) {
551         return appendTo;
552     }
553     double dnum = number.toDouble();
554     format(dnum, appendTo, pos, status);
555     return appendTo;
556 }
557 
558 UnicodeString&
format(const Formattable & obj,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const559 NumberFormat::format(const Formattable& obj,
560                         UnicodeString& appendTo,
561                         FieldPosition& pos,
562                         UErrorCode& status) const
563 {
564     if (U_FAILURE(status)) return appendTo;
565 
566     ArgExtractor arg(*this, obj, status);
567     const Formattable *n = arg.number();
568     const UChar *iso = arg.iso();
569 
570     if(arg.wasCurrency() && u_strcmp(iso, getCurrency())) {
571       // trying to format a different currency.
572       // Right now, we clone.
573       LocalPointer<NumberFormat> cloneFmt((NumberFormat*)this->clone());
574       cloneFmt->setCurrency(iso, status);
575       // next line should NOT recurse, because n is numeric whereas obj was a wrapper around currency amount.
576       return cloneFmt->format(*n, appendTo, pos, status);
577     }
578 
579     if (n->isNumeric() && n->getDecimalQuantity() != NULL) {
580         // Decimal Number.  We will have a DigitList available if the value was
581         //   set to a decimal number, or if the value originated with a parse.
582         //
583         // The default implementation for formatting a DigitList converts it
584         // to a double, and formats that, allowing formatting classes that don't
585         // know about DigitList to continue to operate as they had.
586         //
587         // DecimalFormat overrides the DigitList formatting functions.
588         format(*n->getDecimalQuantity(), appendTo, pos, status);
589     } else {
590         switch (n->getType()) {
591         case Formattable::kDouble:
592             format(n->getDouble(), appendTo, pos, status);
593             break;
594         case Formattable::kLong:
595             format(n->getLong(), appendTo, pos, status);
596             break;
597         case Formattable::kInt64:
598             format(n->getInt64(), appendTo, pos, status);
599             break;
600         default:
601             status = U_INVALID_FORMAT_ERROR;
602             break;
603         }
604     }
605 
606     return appendTo;
607 }
608 
609 // -------------------------------------x
610 // Formats the number object and save the format
611 // result in the toAppendTo string buffer.
612 
613 UnicodeString&
format(const Formattable & obj,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const614 NumberFormat::format(const Formattable& obj,
615                         UnicodeString& appendTo,
616                         FieldPositionIterator* posIter,
617                         UErrorCode& status) const
618 {
619     if (U_FAILURE(status)) return appendTo;
620 
621     ArgExtractor arg(*this, obj, status);
622     const Formattable *n = arg.number();
623     const UChar *iso = arg.iso();
624 
625     if(arg.wasCurrency() && u_strcmp(iso, getCurrency())) {
626       // trying to format a different currency.
627       // Right now, we clone.
628       LocalPointer<NumberFormat> cloneFmt((NumberFormat*)this->clone());
629       cloneFmt->setCurrency(iso, status);
630       // next line should NOT recurse, because n is numeric whereas obj was a wrapper around currency amount.
631       return cloneFmt->format(*n, appendTo, posIter, status);
632     }
633 
634     if (n->isNumeric() && n->getDecimalQuantity() != NULL) {
635         // Decimal Number
636         format(*n->getDecimalQuantity(), appendTo, posIter, status);
637     } else {
638         switch (n->getType()) {
639         case Formattable::kDouble:
640             format(n->getDouble(), appendTo, posIter, status);
641             break;
642         case Formattable::kLong:
643             format(n->getLong(), appendTo, posIter, status);
644             break;
645         case Formattable::kInt64:
646             format(n->getInt64(), appendTo, posIter, status);
647             break;
648         default:
649             status = U_INVALID_FORMAT_ERROR;
650             break;
651         }
652     }
653 
654     return appendTo;
655 }
656 
657 // -------------------------------------
658 
659 UnicodeString&
format(int64_t number,UnicodeString & appendTo,FieldPosition & pos) const660 NumberFormat::format(int64_t number,
661                      UnicodeString& appendTo,
662                      FieldPosition& pos) const
663 {
664     // default so we don't introduce a new abstract method
665     return format((int32_t)number, appendTo, pos);
666 }
667 
668 // -------------------------------------
669 // Parses the string and save the result object as well
670 // as the final parsed position.
671 
672 void
parseObject(const UnicodeString & source,Formattable & result,ParsePosition & parse_pos) const673 NumberFormat::parseObject(const UnicodeString& source,
674                              Formattable& result,
675                              ParsePosition& parse_pos) const
676 {
677     parse(source, result, parse_pos);
678 }
679 
680 // -------------------------------------
681 // Formats a double number and save the result in a string.
682 
683 UnicodeString&
format(double number,UnicodeString & appendTo) const684 NumberFormat::format(double number, UnicodeString& appendTo) const
685 {
686     FieldPosition pos(FieldPosition::DONT_CARE);
687     return format(number, appendTo, pos);
688 }
689 
690 // -------------------------------------
691 // Formats a long number and save the result in a string.
692 
693 UnicodeString&
format(int32_t number,UnicodeString & appendTo) const694 NumberFormat::format(int32_t number, UnicodeString& appendTo) const
695 {
696     FieldPosition pos(FieldPosition::DONT_CARE);
697     return format(number, appendTo, pos);
698 }
699 
700 // -------------------------------------
701 // Formats a long number and save the result in a string.
702 
703 UnicodeString&
format(int64_t number,UnicodeString & appendTo) const704 NumberFormat::format(int64_t number, UnicodeString& appendTo) const
705 {
706     FieldPosition pos(FieldPosition::DONT_CARE);
707     return format(number, appendTo, pos);
708 }
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
parse(const UnicodeString & text,Formattable & result,UErrorCode & status) const717 NumberFormat::parse(const UnicodeString& text,
718                         Formattable& result,
719                         UErrorCode& status) const
720 {
721     if (U_FAILURE(status)) return;
722 
723     ParsePosition parsePosition(0);
724     parse(text, result, parsePosition);
725     if (parsePosition.getIndex() == 0) {
726         status = U_INVALID_FORMAT_ERROR;
727     }
728 }
729 
parseCurrency(const UnicodeString & text,ParsePosition & pos) const730 CurrencyAmount* NumberFormat::parseCurrency(const UnicodeString& text,
731                                             ParsePosition& pos) const {
732     // Default implementation only -- subclasses should override
733     Formattable parseResult;
734     int32_t start = pos.getIndex();
735     parse(text, parseResult, pos);
736     if (pos.getIndex() != start) {
737         UChar curr[4];
738         UErrorCode ec = U_ZERO_ERROR;
739         getEffectiveCurrency(curr, ec);
740         if (U_SUCCESS(ec)) {
741             LocalPointer<CurrencyAmount> currAmt(new CurrencyAmount(parseResult, curr, ec), ec);
742             if (U_FAILURE(ec)) {
743                 pos.setIndex(start); // indicate failure
744             } else {
745                 return currAmt.orphan();
746             }
747         }
748     }
749     return NULL;
750 }
751 
752 // -------------------------------------
753 // Sets to only parse integers.
754 
755 void
setParseIntegerOnly(UBool value)756 NumberFormat::setParseIntegerOnly(UBool value)
757 {
758     fParseIntegerOnly = value;
759 }
760 
761 // -------------------------------------
762 // Sets whether lenient parse is enabled.
763 
764 void
setLenient(UBool enable)765 NumberFormat::setLenient(UBool enable)
766 {
767     fLenient = enable;
768 }
769 
770 // -------------------------------------
771 // Create a number style NumberFormat instance with the default locale.
772 
773 NumberFormat* U_EXPORT2
createInstance(UErrorCode & status)774 NumberFormat::createInstance(UErrorCode& status)
775 {
776     return createInstance(Locale::getDefault(), UNUM_DECIMAL, status);
777 }
778 
779 // -------------------------------------
780 // Create a number style NumberFormat instance with the inLocale locale.
781 
782 NumberFormat* U_EXPORT2
createInstance(const Locale & inLocale,UErrorCode & status)783 NumberFormat::createInstance(const Locale& inLocale, UErrorCode& status)
784 {
785     return createInstance(inLocale, UNUM_DECIMAL, status);
786 }
787 
788 // -------------------------------------
789 // Create a currency style NumberFormat instance with the default locale.
790 
791 NumberFormat* U_EXPORT2
createCurrencyInstance(UErrorCode & status)792 NumberFormat::createCurrencyInstance(UErrorCode& status)
793 {
794     return createCurrencyInstance(Locale::getDefault(),  status);
795 }
796 
797 // -------------------------------------
798 // Create a currency style NumberFormat instance with the inLocale locale.
799 
800 NumberFormat* U_EXPORT2
createCurrencyInstance(const Locale & inLocale,UErrorCode & status)801 NumberFormat::createCurrencyInstance(const Locale& inLocale, UErrorCode& status)
802 {
803     return createInstance(inLocale, UNUM_CURRENCY, status);
804 }
805 
806 // -------------------------------------
807 // Create a percent style NumberFormat instance with the default locale.
808 
809 NumberFormat* U_EXPORT2
createPercentInstance(UErrorCode & status)810 NumberFormat::createPercentInstance(UErrorCode& status)
811 {
812     return createInstance(Locale::getDefault(), UNUM_PERCENT, status);
813 }
814 
815 // -------------------------------------
816 // Create a percent style NumberFormat instance with the inLocale locale.
817 
818 NumberFormat* U_EXPORT2
createPercentInstance(const Locale & inLocale,UErrorCode & status)819 NumberFormat::createPercentInstance(const Locale& inLocale, UErrorCode& status)
820 {
821     return createInstance(inLocale, UNUM_PERCENT, status);
822 }
823 
824 // -------------------------------------
825 // Create a scientific style NumberFormat instance with the default locale.
826 
827 NumberFormat* U_EXPORT2
createScientificInstance(UErrorCode & status)828 NumberFormat::createScientificInstance(UErrorCode& status)
829 {
830     return createInstance(Locale::getDefault(), UNUM_SCIENTIFIC, status);
831 }
832 
833 // -------------------------------------
834 // Create a scientific style NumberFormat instance with the inLocale locale.
835 
836 NumberFormat* U_EXPORT2
createScientificInstance(const Locale & inLocale,UErrorCode & status)837 NumberFormat::createScientificInstance(const Locale& inLocale, UErrorCode& status)
838 {
839     return createInstance(inLocale, UNUM_SCIENTIFIC, status);
840 }
841 
842 // -------------------------------------
843 
844 const Locale* U_EXPORT2
getAvailableLocales(int32_t & count)845 NumberFormat::getAvailableLocales(int32_t& count)
846 {
847     return Locale::getAvailableLocales(count);
848 }
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:
handleCreate(const Locale & loc,int32_t kind,const ICUService *,UErrorCode & status) const864     virtual UObject* handleCreate(const Locale& loc, int32_t kind, const ICUService* /* service */, UErrorCode& status) const {
865         return NumberFormat::makeInstance(loc, (UNumberFormatStyle)kind, status);
866     }
867 };
868 
~ICUNumberFormatFactory()869 ICUNumberFormatFactory::~ICUNumberFormatFactory() {}
870 
871 // -------------------------------------
872 
873 class NFFactory : public LocaleKeyFactory {
874 private:
875     NumberFormatFactory* _delegate;
876     Hashtable* _ids;
877 
878 public:
NFFactory(NumberFormatFactory * delegate)879     NFFactory(NumberFormatFactory* delegate)
880         : LocaleKeyFactory(delegate->visible() ? VISIBLE : INVISIBLE)
881         , _delegate(delegate)
882         , _ids(NULL)
883     {
884     }
885 
886     virtual ~NFFactory();
887 
create(const ICUServiceKey & key,const ICUService * service,UErrorCode & status) const888     virtual UObject* create(const ICUServiceKey& key, const ICUService* service, UErrorCode& status) const
889     {
890         if (handlesKey(key, status)) {
891             const LocaleKey& lkey = (const LocaleKey&)key;
892             Locale loc;
893             lkey.canonicalLocale(loc);
894             int32_t kind = lkey.kind();
895 
896             UObject* result = _delegate->createFormat(loc, (UNumberFormatStyle)kind);
897             if (result == NULL) {
898                 result = service->getKey((ICUServiceKey&)key /* cast away const */, NULL, this, status);
899             }
900             return result;
901         }
902         return NULL;
903     }
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      */
getSupportedIDs(UErrorCode & status) const911     virtual const Hashtable* getSupportedIDs(UErrorCode& status) const
912     {
913         if (U_SUCCESS(status)) {
914             if (!_ids) {
915                 int32_t count = 0;
916                 const UnicodeString * const idlist = _delegate->getSupportedIDs(count, status);
917                 ((NFFactory*)this)->_ids = new Hashtable(status); /* cast away const */
918                 if (_ids) {
919                     for (int i = 0; i < count; ++i) {
920                         _ids->put(idlist[i], (void*)this, status);
921                     }
922                 }
923             }
924             return _ids;
925         }
926         return NULL;
927     }
928 };
929 
~NFFactory()930 NFFactory::~NFFactory()
931 {
932     delete _delegate;
933     delete _ids;
934 }
935 
936 class ICUNumberFormatService : public ICULocaleService {
937 public:
ICUNumberFormatService()938     ICUNumberFormatService()
939         : ICULocaleService(UNICODE_STRING_SIMPLE("Number Format"))
940     {
941         UErrorCode status = U_ZERO_ERROR;
942         registerFactory(new ICUNumberFormatFactory(), status);
943     }
944 
945     virtual ~ICUNumberFormatService();
946 
cloneInstance(UObject * instance) const947     virtual UObject* cloneInstance(UObject* instance) const {
948         return ((NumberFormat*)instance)->clone();
949     }
950 
handleDefault(const ICUServiceKey & key,UnicodeString *,UErrorCode & status) const951     virtual UObject* handleDefault(const ICUServiceKey& key, UnicodeString* /* actualID */, UErrorCode& status) const {
952         LocaleKey& lkey = (LocaleKey&)key;
953         int32_t kind = lkey.kind();
954         Locale loc;
955         lkey.currentLocale(loc);
956         return NumberFormat::makeInstance(loc, (UNumberFormatStyle)kind, status);
957     }
958 
isDefault() const959     virtual UBool isDefault() const {
960         return countFactories() == 1;
961     }
962 };
963 
~ICUNumberFormatService()964 ICUNumberFormatService::~ICUNumberFormatService() {}
965 
966 // -------------------------------------
967 
initNumberFormatService()968 static void U_CALLCONV initNumberFormatService() {
969     U_ASSERT(gService == NULL);
970     ucln_i18n_registerCleanup(UCLN_I18N_NUMFMT, numfmt_cleanup);
971     gService = new ICUNumberFormatService();
972 }
973 
974 static ICULocaleService*
getNumberFormatService(void)975 getNumberFormatService(void)
976 {
977     umtx_initOnce(gServiceInitOnce, &initNumberFormatService);
978     return gService;
979 }
980 
haveService()981 static UBool haveService() {
982     return !gServiceInitOnce.isReset() && (getNumberFormatService() != NULL);
983 }
984 
985 // -------------------------------------
986 
987 URegistryKey U_EXPORT2
registerFactory(NumberFormatFactory * toAdopt,UErrorCode & status)988 NumberFormat::registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status)
989 {
990   ICULocaleService *service = getNumberFormatService();
991   if (service) {
992 	  NFFactory *tempnnf = new NFFactory(toAdopt);
993 	  if (tempnnf != NULL) {
994 		  return service->registerFactory(tempnnf, status);
995 	  }
996   }
997   status = U_MEMORY_ALLOCATION_ERROR;
998   return NULL;
999 }
1000 
1001 // -------------------------------------
1002 
1003 UBool U_EXPORT2
unregister(URegistryKey key,UErrorCode & status)1004 NumberFormat::unregister(URegistryKey key, UErrorCode& status)
1005 {
1006     if (U_FAILURE(status)) {
1007         return FALSE;
1008     }
1009     if (haveService()) {
1010         return gService->unregister(key, status);
1011     } else {
1012         status = U_ILLEGAL_ARGUMENT_ERROR;
1013         return FALSE;
1014     }
1015 }
1016 
1017 // -------------------------------------
1018 StringEnumeration* U_EXPORT2
getAvailableLocales(void)1019 NumberFormat::getAvailableLocales(void)
1020 {
1021   ICULocaleService *service = getNumberFormatService();
1022   if (service) {
1023       return service->getAvailableLocales();
1024   }
1025   return NULL; // no way to return error condition
1026 }
1027 #endif /* UCONFIG_NO_SERVICE */
1028 // -------------------------------------
1029 
1030 enum { kKeyValueLenMax = 32 };
1031 
1032 NumberFormat*
internalCreateInstance(const Locale & loc,UNumberFormatStyle kind,UErrorCode & status)1033 NumberFormat::internalCreateInstance(const Locale& loc, UNumberFormatStyle kind, UErrorCode& status) {
1034     if (kind == UNUM_CURRENCY) {
1035         char cfKeyValue[kKeyValueLenMax] = {0};
1036         UErrorCode kvStatus = U_ZERO_ERROR;
1037         int32_t kLen = loc.getKeywordValue("cf", cfKeyValue, kKeyValueLenMax, kvStatus);
1038         if (U_SUCCESS(kvStatus) && kLen > 0 && uprv_strcmp(cfKeyValue,"account")==0) {
1039             kind = UNUM_CURRENCY_ACCOUNTING;
1040         }
1041     }
1042 #if !UCONFIG_NO_SERVICE
1043     if (haveService()) {
1044         return (NumberFormat*)gService->get(loc, kind, status);
1045     }
1046 #endif
1047     return makeInstance(loc, kind, status);
1048 }
1049 
1050 NumberFormat* U_EXPORT2
createInstance(const Locale & loc,UNumberFormatStyle kind,UErrorCode & status)1051 NumberFormat::createInstance(const Locale& loc, UNumberFormatStyle kind, UErrorCode& status) {
1052     if (kind != UNUM_DECIMAL) {
1053         return internalCreateInstance(loc, kind, status);
1054     }
1055     const SharedNumberFormat *shared = createSharedInstance(loc, kind, status);
1056     if (U_FAILURE(status)) {
1057         return NULL;
1058     }
1059     NumberFormat *result = static_cast<NumberFormat *>((*shared)->clone());
1060     shared->removeRef();
1061     if (result == NULL) {
1062         status = U_MEMORY_ALLOCATION_ERROR;
1063     }
1064     return result;
1065 }
1066 
1067 
1068 // -------------------------------------
1069 // Checks if the thousand/10 thousand grouping is used in the
1070 // NumberFormat instance.
1071 
1072 UBool
isGroupingUsed() const1073 NumberFormat::isGroupingUsed() const
1074 {
1075     return fGroupingUsed;
1076 }
1077 
1078 // -------------------------------------
1079 // Sets to use the thousand/10 thousand grouping in the
1080 // NumberFormat instance.
1081 
1082 void
setGroupingUsed(UBool newValue)1083 NumberFormat::setGroupingUsed(UBool newValue)
1084 {
1085     fGroupingUsed = newValue;
1086 }
1087 
1088 // -------------------------------------
1089 // Gets the maximum number of digits for the integral part for
1090 // this NumberFormat instance.
1091 
getMaximumIntegerDigits() const1092 int32_t NumberFormat::getMaximumIntegerDigits() const
1093 {
1094     return fMaxIntegerDigits;
1095 }
1096 
1097 // -------------------------------------
1098 // Sets the maximum number of digits for the integral part for
1099 // this NumberFormat instance.
1100 
1101 void
setMaximumIntegerDigits(int32_t newValue)1102 NumberFormat::setMaximumIntegerDigits(int32_t newValue)
1103 {
1104     fMaxIntegerDigits = uprv_max(0, uprv_min(newValue, gDefaultMaxIntegerDigits));
1105     if(fMinIntegerDigits > fMaxIntegerDigits)
1106         fMinIntegerDigits = fMaxIntegerDigits;
1107 }
1108 
1109 // -------------------------------------
1110 // Gets the minimum number of digits for the integral part for
1111 // this NumberFormat instance.
1112 
1113 int32_t
getMinimumIntegerDigits() const1114 NumberFormat::getMinimumIntegerDigits() const
1115 {
1116     return fMinIntegerDigits;
1117 }
1118 
1119 // -------------------------------------
1120 // Sets the minimum number of digits for the integral part for
1121 // this NumberFormat instance.
1122 
1123 void
setMinimumIntegerDigits(int32_t newValue)1124 NumberFormat::setMinimumIntegerDigits(int32_t newValue)
1125 {
1126     fMinIntegerDigits = uprv_max(0, uprv_min(newValue, gDefaultMinIntegerDigits));
1127     if(fMinIntegerDigits > fMaxIntegerDigits)
1128         fMaxIntegerDigits = fMinIntegerDigits;
1129 }
1130 
1131 // -------------------------------------
1132 // Gets the maximum number of digits for the fractional part for
1133 // this NumberFormat instance.
1134 
1135 int32_t
getMaximumFractionDigits() const1136 NumberFormat::getMaximumFractionDigits() const
1137 {
1138     return fMaxFractionDigits;
1139 }
1140 
1141 // -------------------------------------
1142 // Sets the maximum number of digits for the fractional part for
1143 // this NumberFormat instance.
1144 
1145 void
setMaximumFractionDigits(int32_t newValue)1146 NumberFormat::setMaximumFractionDigits(int32_t newValue)
1147 {
1148     fMaxFractionDigits = uprv_max(0, uprv_min(newValue, gDefaultMaxIntegerDigits));
1149     if(fMaxFractionDigits < fMinFractionDigits)
1150         fMinFractionDigits = fMaxFractionDigits;
1151 }
1152 
1153 // -------------------------------------
1154 // Gets the minimum number of digits for the fractional part for
1155 // this NumberFormat instance.
1156 
1157 int32_t
getMinimumFractionDigits() const1158 NumberFormat::getMinimumFractionDigits() const
1159 {
1160     return fMinFractionDigits;
1161 }
1162 
1163 // -------------------------------------
1164 // Sets the minimum number of digits for the fractional part for
1165 // this NumberFormat instance.
1166 
1167 void
setMinimumFractionDigits(int32_t newValue)1168 NumberFormat::setMinimumFractionDigits(int32_t newValue)
1169 {
1170     fMinFractionDigits = uprv_max(0, uprv_min(newValue, gDefaultMinIntegerDigits));
1171     if (fMaxFractionDigits < fMinFractionDigits)
1172         fMaxFractionDigits = fMinFractionDigits;
1173 }
1174 
1175 // -------------------------------------
1176 
setCurrency(const UChar * theCurrency,UErrorCode & ec)1177 void NumberFormat::setCurrency(const UChar* theCurrency, UErrorCode& ec) {
1178     if (U_FAILURE(ec)) {
1179         return;
1180     }
1181     if (theCurrency) {
1182         u_strncpy(fCurrency, theCurrency, 3);
1183         fCurrency[3] = 0;
1184     } else {
1185         fCurrency[0] = 0;
1186     }
1187 }
1188 
getCurrency() const1189 const char16_t* NumberFormat::getCurrency() const {
1190     return fCurrency;
1191 }
1192 
getEffectiveCurrency(UChar * result,UErrorCode & ec) const1193 void NumberFormat::getEffectiveCurrency(UChar* result, UErrorCode& ec) const {
1194     const UChar* c = getCurrency();
1195     if (*c != 0) {
1196         u_strncpy(result, c, 3);
1197         result[3] = 0;
1198     } else {
1199         const char* loc = getLocaleID(ULOC_VALID_LOCALE, ec);
1200         if (loc == NULL) {
1201             loc = uloc_getDefault();
1202         }
1203         ucurr_forLocale(loc, result, 4, &ec);
1204     }
1205 }
1206 
1207 //----------------------------------------------------------------------
1208 
1209 
setContext(UDisplayContext value,UErrorCode & status)1210 void NumberFormat::setContext(UDisplayContext value, UErrorCode& status)
1211 {
1212     if (U_FAILURE(status))
1213         return;
1214     if ( (UDisplayContextType)((uint32_t)value >> 8) == UDISPCTX_TYPE_CAPITALIZATION ) {
1215         fCapitalizationContext = value;
1216     } else {
1217         status = U_ILLEGAL_ARGUMENT_ERROR;
1218    }
1219 }
1220 
1221 
getContext(UDisplayContextType type,UErrorCode & status) const1222 UDisplayContext NumberFormat::getContext(UDisplayContextType type, UErrorCode& status) const
1223 {
1224     if (U_FAILURE(status))
1225         return (UDisplayContext)0;
1226     if (type != UDISPCTX_TYPE_CAPITALIZATION) {
1227         status = U_ILLEGAL_ARGUMENT_ERROR;
1228         return (UDisplayContext)0;
1229     }
1230     return fCapitalizationContext;
1231 }
1232 
1233 
1234 // -------------------------------------
1235 // Creates the NumberFormat instance of the specified style (number, currency,
1236 // or percent) for the desired locale.
1237 
nscacheInit()1238 static void U_CALLCONV nscacheInit() {
1239     U_ASSERT(NumberingSystem_cache == NULL);
1240     ucln_i18n_registerCleanup(UCLN_I18N_NUMFMT, numfmt_cleanup);
1241     UErrorCode status = U_ZERO_ERROR;
1242     NumberingSystem_cache = uhash_open(uhash_hashLong,
1243                                        uhash_compareLong,
1244                                        NULL,
1245                                        &status);
1246     if (U_FAILURE(status)) {
1247         // Number Format code will run with no cache if creation fails.
1248         NumberingSystem_cache = NULL;
1249         return;
1250     }
1251     uhash_setValueDeleter(NumberingSystem_cache, deleteNumberingSystem);
1252 }
1253 
1254 template<> U_I18N_API
createObject(const void *,UErrorCode & status) const1255 const SharedNumberFormat *LocaleCacheKey<SharedNumberFormat>::createObject(
1256         const void * /*unused*/, UErrorCode &status) const {
1257     const char *localeId = fLoc.getName();
1258     NumberFormat *nf = NumberFormat::internalCreateInstance(
1259             localeId, UNUM_DECIMAL, status);
1260     if (U_FAILURE(status)) {
1261         return NULL;
1262     }
1263     SharedNumberFormat *result = new SharedNumberFormat(nf);
1264     if (result == NULL) {
1265         status = U_MEMORY_ALLOCATION_ERROR;
1266         delete nf;
1267         return NULL;
1268     }
1269     result->addRef();
1270     return result;
1271 }
1272 
1273 const SharedNumberFormat* U_EXPORT2
createSharedInstance(const Locale & loc,UNumberFormatStyle kind,UErrorCode & status)1274 NumberFormat::createSharedInstance(const Locale& loc, UNumberFormatStyle kind, UErrorCode& status) {
1275     if (U_FAILURE(status)) {
1276         return NULL;
1277     }
1278     if (kind != UNUM_DECIMAL) {
1279         status = U_UNSUPPORTED_ERROR;
1280         return NULL;
1281     }
1282     const SharedNumberFormat *result = NULL;
1283     UnifiedCache::getByLocale(loc, result, status);
1284     return result;
1285 }
1286 
1287 UBool
isStyleSupported(UNumberFormatStyle style)1288 NumberFormat::isStyleSupported(UNumberFormatStyle style) {
1289     return gLastResortNumberPatterns[style] != NULL;
1290 }
1291 
1292 NumberFormat*
makeInstance(const Locale & desiredLocale,UNumberFormatStyle style,UErrorCode & status)1293 NumberFormat::makeInstance(const Locale& desiredLocale,
1294                            UNumberFormatStyle style,
1295                            UErrorCode& status) {
1296   return makeInstance(desiredLocale, style, false, status);
1297 }
1298 
1299 NumberFormat*
makeInstance(const Locale & desiredLocale,UNumberFormatStyle style,UBool mustBeDecimalFormat,UErrorCode & status)1300 NumberFormat::makeInstance(const Locale& desiredLocale,
1301                            UNumberFormatStyle style,
1302                            UBool mustBeDecimalFormat,
1303                            UErrorCode& status) {
1304     if (U_FAILURE(status)) return NULL;
1305 
1306     if (style < 0 || style >= UNUM_FORMAT_STYLE_COUNT) {
1307         status = U_ILLEGAL_ARGUMENT_ERROR;
1308         return NULL;
1309     }
1310 
1311     // Some styles are not supported. This is a result of merging
1312     // the @draft ICU 4.2 NumberFormat::EStyles into the long-existing UNumberFormatStyle.
1313     // Ticket #8503 is for reviewing/fixing/merging the two relevant implementations:
1314     // this one and unum_open().
1315     // The UNUM_PATTERN_ styles are not supported here
1316     // because this method does not take a pattern string.
1317     if (!isStyleSupported(style)) {
1318         status = U_UNSUPPORTED_ERROR;
1319         return NULL;
1320     }
1321 
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             UBool curr = TRUE;
1330 
1331             switch (style) {
1332             case UNUM_DECIMAL:
1333                 curr = FALSE;
1334                 // fall-through
1335                 U_FALLTHROUGH;
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             {
1344                 LocalPointer<Win32NumberFormat> f(new Win32NumberFormat(desiredLocale, curr, status), status);
1345                 if (U_SUCCESS(status)) {
1346                     return f.orphan();
1347                 }
1348             }
1349             break;
1350             default:
1351                 break;
1352             }
1353         }
1354     }
1355 #endif
1356     // Use numbering system cache hashtable
1357     umtx_initOnce(gNSCacheInitOnce, &nscacheInit);
1358 
1359     // Get cached numbering system
1360     LocalPointer<NumberingSystem> ownedNs;
1361     NumberingSystem *ns = NULL;
1362     if (NumberingSystem_cache != NULL) {
1363         // TODO: Bad hash key usage, see ticket #8504.
1364         int32_t hashKey = desiredLocale.hashCode();
1365 
1366         Mutex lock(&nscacheMutex);
1367         ns = (NumberingSystem *)uhash_iget(NumberingSystem_cache, hashKey);
1368         if (ns == NULL) {
1369             ns = NumberingSystem::createInstance(desiredLocale,status);
1370             uhash_iput(NumberingSystem_cache, hashKey, (void*)ns, &status);
1371         }
1372     } else {
1373         ownedNs.adoptInstead(NumberingSystem::createInstance(desiredLocale,status));
1374         ns = ownedNs.getAlias();
1375     }
1376 
1377     // check results of getting a numbering system
1378     if (U_FAILURE(status)) {
1379         return NULL;
1380     }
1381 
1382     if (mustBeDecimalFormat && ns->isAlgorithmic()) {
1383         status = U_UNSUPPORTED_ERROR;
1384         return NULL;
1385     }
1386 
1387     LocalPointer<DecimalFormatSymbols> symbolsToAdopt;
1388     UnicodeString pattern;
1389     LocalUResourceBundlePointer ownedResource(ures_open(NULL, desiredLocale.getName(), &status));
1390     if (U_FAILURE(status)) {
1391         return NULL;
1392     }
1393     else {
1394         // Loads the decimal symbols of the desired locale.
1395         symbolsToAdopt.adoptInsteadAndCheckErrorCode(new DecimalFormatSymbols(desiredLocale, status), status);
1396         if (U_FAILURE(status)) {
1397             return NULL;
1398         }
1399 
1400         // Load the pattern from data using the common library function
1401         const char16_t* patternPtr = number::impl::utils::getPatternForStyle(
1402                 desiredLocale,
1403                 ns->getName(),
1404                 gFormatCldrStyles[style],
1405                 status);
1406         pattern = UnicodeString(TRUE, patternPtr, -1);
1407     }
1408     if (U_FAILURE(status)) {
1409         return NULL;
1410     }
1411     if(style==UNUM_CURRENCY || style == UNUM_CURRENCY_ISO || style == UNUM_CURRENCY_ACCOUNTING
1412         || style == UNUM_CASH_CURRENCY || style == UNUM_CURRENCY_STANDARD){
1413         const UChar* currPattern = symbolsToAdopt->getCurrencyPattern();
1414         if(currPattern!=NULL){
1415             pattern.setTo(currPattern, u_strlen(currPattern));
1416         }
1417     }
1418 
1419     LocalPointer<NumberFormat> f;
1420     if (ns->isAlgorithmic()) {
1421         UnicodeString nsDesc;
1422         UnicodeString nsRuleSetGroup;
1423         UnicodeString nsRuleSetName;
1424         Locale nsLoc;
1425         URBNFRuleSetTag desiredRulesType = URBNF_NUMBERING_SYSTEM;
1426 
1427         nsDesc.setTo(ns->getDescription());
1428         int32_t firstSlash = nsDesc.indexOf(gSlash);
1429         int32_t lastSlash = nsDesc.lastIndexOf(gSlash);
1430         if ( lastSlash > firstSlash ) {
1431             CharString nsLocID;
1432 
1433             nsLocID.appendInvariantChars(nsDesc.tempSubString(0, firstSlash), status);
1434             nsRuleSetGroup.setTo(nsDesc,firstSlash+1,lastSlash-firstSlash-1);
1435             nsRuleSetName.setTo(nsDesc,lastSlash+1);
1436 
1437             nsLoc = Locale::createFromName(nsLocID.data());
1438 
1439             UnicodeString SpelloutRules = UNICODE_STRING_SIMPLE("SpelloutRules");
1440             if ( nsRuleSetGroup.compare(SpelloutRules) == 0 ) {
1441                 desiredRulesType = URBNF_SPELLOUT;
1442             }
1443         } else {
1444             nsLoc = desiredLocale;
1445             nsRuleSetName.setTo(nsDesc);
1446         }
1447 
1448         RuleBasedNumberFormat *r = new RuleBasedNumberFormat(desiredRulesType,nsLoc,status);
1449         if (r == NULL) {
1450             status = U_MEMORY_ALLOCATION_ERROR;
1451             return NULL;
1452         }
1453         r->setDefaultRuleSet(nsRuleSetName,status);
1454         f.adoptInstead(r);
1455     } else {
1456         // replace single currency sign in the pattern with double currency sign
1457         // if the style is UNUM_CURRENCY_ISO
1458         if (style == UNUM_CURRENCY_ISO) {
1459             pattern.findAndReplace(UnicodeString(TRUE, gSingleCurrencySign, 1),
1460                                    UnicodeString(TRUE, gDoubleCurrencySign, 2));
1461         }
1462 
1463         // "new DecimalFormat()" does not adopt the symbols argument if its memory allocation fails.
1464         // So we can't use adoptInsteadAndCheckErrorCode as we need to know if the 'new' failed.
1465         DecimalFormatSymbols *syms = symbolsToAdopt.getAlias();
1466         LocalPointer<DecimalFormat> df(new DecimalFormat(pattern, syms, style, status));
1467 
1468         if (df.isValid()) {
1469             // if the DecimalFormat object was successfully new'ed, then it will own symbolsToAdopt, even if the status is a failure.
1470             symbolsToAdopt.orphan();
1471         }
1472         else {
1473             status = U_MEMORY_ALLOCATION_ERROR;
1474         }
1475 
1476         if (U_FAILURE(status)) {
1477             return nullptr;
1478         }
1479 
1480         // if it is cash currency style, setCurrencyUsage with usage
1481         if (style == UNUM_CASH_CURRENCY){
1482             df->setCurrencyUsage(UCURR_USAGE_CASH, &status);
1483         }
1484 
1485         if (U_FAILURE(status)) {
1486             return nullptr;
1487         }
1488 
1489         f.adoptInstead(df.orphan());
1490     }
1491 
1492     f->setLocaleIDs(ures_getLocaleByType(ownedResource.getAlias(), ULOC_VALID_LOCALE, &status),
1493                     ures_getLocaleByType(ownedResource.getAlias(), ULOC_ACTUAL_LOCALE, &status));
1494     if (U_FAILURE(status)) {
1495         return NULL;
1496     }
1497     return f.orphan();
1498 }
1499 
1500 /**
1501  * Get the rounding mode.
1502  * @return A rounding mode
1503  */
getRoundingMode() const1504 NumberFormat::ERoundingMode NumberFormat::getRoundingMode() const {
1505     // Default value. ICU4J throws an exception and we can't change this API.
1506     return NumberFormat::ERoundingMode::kRoundUnnecessary;
1507 }
1508 
1509 /**
1510  * Set the rounding mode.  This has no effect unless the rounding
1511  * increment is greater than zero.
1512  * @param roundingMode A rounding mode
1513  */
setRoundingMode(NumberFormat::ERoundingMode)1514 void NumberFormat::setRoundingMode(NumberFormat::ERoundingMode /*roundingMode*/) {
1515     // No-op ICU4J throws an exception, and we can't change this API.
1516 }
1517 
1518 U_NAMESPACE_END
1519 
1520 #endif /* #if !UCONFIG_NO_FORMATTING */
1521 
1522 //eof
1523