• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 *******************************************************************************
3 * Copyright (C) 1997-2010, International Business Machines Corporation and    *
4 * others. All Rights Reserved.                                                *
5 *******************************************************************************
6 *
7 * File DECIMFMT.CPP
8 *
9 * Modification History:
10 *
11 *   Date        Name        Description
12 *   02/19/97    aliu        Converted from java.
13 *   03/20/97    clhuang     Implemented with new APIs.
14 *   03/31/97    aliu        Moved isLONG_MIN to DigitList, and fixed it.
15 *   04/3/97     aliu        Rewrote parsing and formatting completely, and
16 *                           cleaned up and debugged.  Actually works now.
17 *                           Implemented NAN and INF handling, for both parsing
18 *                           and formatting.  Extensive testing & debugging.
19 *   04/10/97    aliu        Modified to compile on AIX.
20 *   04/16/97    aliu        Rewrote to use DigitList, which has been resurrected.
21 *                           Changed DigitCount to int per code review.
22 *   07/09/97    helena      Made ParsePosition into a class.
23 *   08/26/97    aliu        Extensive changes to applyPattern; completely
24 *                           rewritten from the Java.
25 *   09/09/97    aliu        Ported over support for exponential formats.
26 *   07/20/98    stephen     JDK 1.2 sync up.
27 *                             Various instances of '0' replaced with 'NULL'
28 *                             Check for grouping size in subFormat()
29 *                             Brought subParse() in line with Java 1.2
30 *                             Added method appendAffix()
31 *   08/24/1998  srl         Removed Mutex calls. This is not a thread safe class!
32 *   02/22/99    stephen     Removed character literals for EBCDIC safety
33 *   06/24/99    helena      Integrated Alan's NF enhancements and Java2 bug fixes
34 *   06/28/99    stephen     Fixed bugs in toPattern().
35 *   06/29/99    stephen     Fixed operator= to copy fFormatWidth, fPad,
36 *                             fPadPosition
37 ********************************************************************************
38 */
39 
40 #include "unicode/utypes.h"
41 
42 #if !UCONFIG_NO_FORMATTING
43 
44 #include "fphdlimp.h"
45 #include "unicode/decimfmt.h"
46 #include "unicode/choicfmt.h"
47 #include "unicode/ucurr.h"
48 #include "unicode/ustring.h"
49 #include "unicode/dcfmtsym.h"
50 #include "unicode/ures.h"
51 #include "unicode/uchar.h"
52 #include "unicode/curramt.h"
53 #include "unicode/currpinf.h"
54 #include "unicode/plurrule.h"
55 #include "ucurrimp.h"
56 #include "cmemory.h"
57 #include "util.h"
58 #include "digitlst.h"
59 #include "cstring.h"
60 #include "umutex.h"
61 #include "uassert.h"
62 #include "putilimp.h"
63 #include <math.h>
64 #include "hash.h"
65 #include "decnumstr.h"
66 
67 
68 U_NAMESPACE_BEGIN
69 
70 /* For currency parsing purose,
71  * Need to remember all prefix patterns and suffix patterns of
72  * every currency format pattern,
73  * including the pattern of default currecny style
74  * and plural currency style. And the patterns are set through applyPattern.
75  */
76 struct AffixPatternsForCurrency : public UMemory {
77 	// negative prefix pattern
78 	UnicodeString negPrefixPatternForCurrency;
79 	// negative suffix pattern
80 	UnicodeString negSuffixPatternForCurrency;
81 	// positive prefix pattern
82 	UnicodeString posPrefixPatternForCurrency;
83 	// positive suffix pattern
84 	UnicodeString posSuffixPatternForCurrency;
85 	int8_t patternType;
86 
AffixPatternsForCurrencyAffixPatternsForCurrency87 	AffixPatternsForCurrency(const UnicodeString& negPrefix,
88 							 const UnicodeString& negSuffix,
89 							 const UnicodeString& posPrefix,
90 							 const UnicodeString& posSuffix,
91 							 int8_t type) {
92 		negPrefixPatternForCurrency = negPrefix;
93 		negSuffixPatternForCurrency = negSuffix;
94 		posPrefixPatternForCurrency = posPrefix;
95 		posSuffixPatternForCurrency = posSuffix;
96 		patternType = type;
97 	}
98 };
99 
100 /* affix for currency formatting when the currency sign in the pattern
101  * equals to 3, such as the pattern contains 3 currency sign or
102  * the formatter style is currency plural format style.
103  */
104 struct AffixesForCurrency : public UMemory {
105 	// negative prefix
106 	UnicodeString negPrefixForCurrency;
107 	// negative suffix
108 	UnicodeString negSuffixForCurrency;
109 	// positive prefix
110 	UnicodeString posPrefixForCurrency;
111 	// positive suffix
112 	UnicodeString posSuffixForCurrency;
113 
114 	int32_t formatWidth;
115 
AffixesForCurrencyAffixesForCurrency116 	AffixesForCurrency(const UnicodeString& negPrefix,
117 					   const UnicodeString& negSuffix,
118 					   const UnicodeString& posPrefix,
119 					   const UnicodeString& posSuffix) {
120 		negPrefixForCurrency = negPrefix;
121 		negSuffixForCurrency = negSuffix;
122 		posPrefixForCurrency = posPrefix;
123 		posSuffixForCurrency = posSuffix;
124 	}
125 };
126 
127 U_CDECL_BEGIN
128 
129 /**
130  * @internal ICU 4.2
131  */
132 static UBool U_CALLCONV decimfmtAffixValueComparator(UHashTok val1, UHashTok val2);
133 
134 /**
135  * @internal ICU 4.2
136  */
137 static UBool U_CALLCONV decimfmtAffixPatternValueComparator(UHashTok val1, UHashTok val2);
138 
139 
140 static UBool
decimfmtAffixValueComparator(UHashTok val1,UHashTok val2)141 U_CALLCONV decimfmtAffixValueComparator(UHashTok val1, UHashTok val2) {
142     const AffixesForCurrency* affix_1 =
143         (AffixesForCurrency*)val1.pointer;
144     const AffixesForCurrency* affix_2 =
145         (AffixesForCurrency*)val2.pointer;
146     return affix_1->negPrefixForCurrency == affix_2->negPrefixForCurrency &&
147            affix_1->negSuffixForCurrency == affix_2->negSuffixForCurrency &&
148            affix_1->posPrefixForCurrency == affix_2->posPrefixForCurrency &&
149            affix_1->posSuffixForCurrency == affix_2->posSuffixForCurrency;
150 }
151 
152 
153 static UBool
decimfmtAffixPatternValueComparator(UHashTok val1,UHashTok val2)154 U_CALLCONV decimfmtAffixPatternValueComparator(UHashTok val1, UHashTok val2) {
155     const AffixPatternsForCurrency* affix_1 =
156         (AffixPatternsForCurrency*)val1.pointer;
157     const AffixPatternsForCurrency* affix_2 =
158         (AffixPatternsForCurrency*)val2.pointer;
159     return affix_1->negPrefixPatternForCurrency ==
160            affix_2->negPrefixPatternForCurrency &&
161            affix_1->negSuffixPatternForCurrency ==
162            affix_2->negSuffixPatternForCurrency &&
163            affix_1->posPrefixPatternForCurrency ==
164            affix_2->posPrefixPatternForCurrency &&
165            affix_1->posSuffixPatternForCurrency ==
166            affix_2->posSuffixPatternForCurrency &&
167            affix_1->patternType == affix_2->patternType;
168 }
169 
170 U_CDECL_END
171 
172 
173 //#define FMT_DEBUG
174 
175 #ifdef FMT_DEBUG
176 #include <stdio.h>
debugout(UnicodeString s)177 static void debugout(UnicodeString s) {
178     char buf[2000];
179     s.extract((int32_t) 0, s.length(), buf);
180     printf("%s\n", buf);
181 }
182 #define debug(x) printf("%s\n", x);
183 #else
184 #define debugout(x)
185 #define debug(x)
186 #endif
187 
188 
189 
190 // *****************************************************************************
191 // class DecimalFormat
192 // *****************************************************************************
193 
194 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DecimalFormat)
195 
196 // Constants for characters used in programmatic (unlocalized) patterns.
197 #define kPatternZeroDigit            ((UChar)0x0030) /*'0'*/
198 #define kPatternSignificantDigit     ((UChar)0x0040) /*'@'*/
199 #define kPatternGroupingSeparator    ((UChar)0x002C) /*','*/
200 #define kPatternDecimalSeparator     ((UChar)0x002E) /*'.'*/
201 #define kPatternPerMill              ((UChar)0x2030)
202 #define kPatternPercent              ((UChar)0x0025) /*'%'*/
203 #define kPatternDigit                ((UChar)0x0023) /*'#'*/
204 #define kPatternSeparator            ((UChar)0x003B) /*';'*/
205 #define kPatternExponent             ((UChar)0x0045) /*'E'*/
206 #define kPatternPlus                 ((UChar)0x002B) /*'+'*/
207 #define kPatternMinus                ((UChar)0x002D) /*'-'*/
208 #define kPatternPadEscape            ((UChar)0x002A) /*'*'*/
209 #define kQuote                       ((UChar)0x0027) /*'\''*/
210 /**
211  * The CURRENCY_SIGN is the standard Unicode symbol for currency.  It
212  * is used in patterns and substitued with either the currency symbol,
213  * or if it is doubled, with the international currency symbol.  If the
214  * CURRENCY_SIGN is seen in a pattern, then the decimal separator is
215  * replaced with the monetary decimal separator.
216  */
217 #define kCurrencySign                ((UChar)0x00A4)
218 #define kDefaultPad                  ((UChar)0x0020) /* */
219 
220 const int32_t DecimalFormat::kDoubleIntegerDigits  = 309;
221 const int32_t DecimalFormat::kDoubleFractionDigits = 340;
222 
223 const int32_t DecimalFormat::kMaxScientificIntegerDigits = 8;
224 
225 /**
226  * These are the tags we expect to see in normal resource bundle files associated
227  * with a locale.
228  */
229 const char DecimalFormat::fgNumberPatterns[]="NumberPatterns";
230 static const UChar fgTripleCurrencySign[] = {0xA4, 0xA4, 0xA4, 0};
231 
_min(int32_t a,int32_t b)232 inline int32_t _min(int32_t a, int32_t b) { return (a<b) ? a : b; }
_max(int32_t a,int32_t b)233 inline int32_t _max(int32_t a, int32_t b) { return (a<b) ? b : a; }
234 
235 //------------------------------------------------------------------------------
236 // Constructs a DecimalFormat instance in the default locale.
237 
DecimalFormat(UErrorCode & status)238 DecimalFormat::DecimalFormat(UErrorCode& status) {
239     init();
240     UParseError parseError;
241     construct(status, parseError);
242 }
243 
244 //------------------------------------------------------------------------------
245 // Constructs a DecimalFormat instance with the specified number format
246 // pattern in the default locale.
247 
DecimalFormat(const UnicodeString & pattern,UErrorCode & status)248 DecimalFormat::DecimalFormat(const UnicodeString& pattern,
249                              UErrorCode& status) {
250     init();
251     UParseError parseError;
252     construct(status, parseError, &pattern);
253 }
254 
255 //------------------------------------------------------------------------------
256 // Constructs a DecimalFormat instance with the specified number format
257 // pattern and the number format symbols in the default locale.  The
258 // created instance owns the symbols.
259 
DecimalFormat(const UnicodeString & pattern,DecimalFormatSymbols * symbolsToAdopt,UErrorCode & status)260 DecimalFormat::DecimalFormat(const UnicodeString& pattern,
261                              DecimalFormatSymbols* symbolsToAdopt,
262                              UErrorCode& status) {
263     init();
264     UParseError parseError;
265     if (symbolsToAdopt == NULL)
266         status = U_ILLEGAL_ARGUMENT_ERROR;
267     construct(status, parseError, &pattern, symbolsToAdopt);
268 }
269 
DecimalFormat(const UnicodeString & pattern,DecimalFormatSymbols * symbolsToAdopt,UParseError & parseErr,UErrorCode & status)270 DecimalFormat::DecimalFormat(  const UnicodeString& pattern,
271                     DecimalFormatSymbols* symbolsToAdopt,
272                     UParseError& parseErr,
273                     UErrorCode& status) {
274     init();
275     if (symbolsToAdopt == NULL)
276         status = U_ILLEGAL_ARGUMENT_ERROR;
277     construct(status,parseErr, &pattern, symbolsToAdopt);
278 }
279 
280 //------------------------------------------------------------------------------
281 // Constructs a DecimalFormat instance with the specified number format
282 // pattern and the number format symbols in the default locale.  The
283 // created instance owns the clone of the symbols.
284 
DecimalFormat(const UnicodeString & pattern,const DecimalFormatSymbols & symbols,UErrorCode & status)285 DecimalFormat::DecimalFormat(const UnicodeString& pattern,
286                              const DecimalFormatSymbols& symbols,
287                              UErrorCode& status) {
288     init();
289     UParseError parseError;
290     construct(status, parseError, &pattern, new DecimalFormatSymbols(symbols));
291 }
292 
293 //------------------------------------------------------------------------------
294 // Constructs a DecimalFormat instance with the specified number format
295 // pattern, the number format symbols, and the number format style.
296 // The created instance owns the clone of the symbols.
297 
DecimalFormat(const UnicodeString & pattern,DecimalFormatSymbols * symbolsToAdopt,NumberFormat::EStyles style,UErrorCode & status)298 DecimalFormat::DecimalFormat(const UnicodeString& pattern,
299                              DecimalFormatSymbols* symbolsToAdopt,
300                              NumberFormat::EStyles style,
301                              UErrorCode& status) {
302     init();
303     fStyle = style;
304     UParseError parseError;
305     construct(status, parseError, &pattern, symbolsToAdopt);
306 }
307 
308 //-----------------------------------------------------------------------------
309 // Common DecimalFormat initialization.
310 //    Put all fields of an uninitialized object into a known state.
311 //    Common code, shared by all constructors.
312 void
init()313 DecimalFormat::init() {
314     fPosPrefixPattern = 0;
315     fPosSuffixPattern = 0;
316     fNegPrefixPattern = 0;
317     fNegSuffixPattern = 0;
318     fCurrencyChoice = 0;
319     fMultiplier = NULL;
320     fGroupingSize = 0;
321     fGroupingSize2 = 0;
322     fDecimalSeparatorAlwaysShown = FALSE;
323     fSymbols = NULL;
324     fUseSignificantDigits = FALSE;
325     fMinSignificantDigits = 1;
326     fMaxSignificantDigits = 6;
327     fUseExponentialNotation = FALSE;
328     fMinExponentDigits = 0;
329     fExponentSignAlwaysShown = FALSE;
330     fRoundingIncrement = 0;
331     fRoundingMode = kRoundHalfEven;
332     fPad = 0;
333     fFormatWidth = 0;
334     fPadPosition = kPadBeforePrefix;
335     fStyle = NumberFormat::kNumberStyle;
336     fCurrencySignCount = 0;
337     fAffixPatternsForCurrency = NULL;
338     fAffixesForCurrency = NULL;
339     fPluralAffixesForCurrency = NULL;
340     fCurrencyPluralInfo = NULL;
341 }
342 
343 //------------------------------------------------------------------------------
344 // Constructs a DecimalFormat instance with the specified number format
345 // pattern and the number format symbols in the desired locale.  The
346 // created instance owns the symbols.
347 
348 void
construct(UErrorCode & status,UParseError & parseErr,const UnicodeString * pattern,DecimalFormatSymbols * symbolsToAdopt)349 DecimalFormat::construct(UErrorCode&             status,
350                          UParseError&           parseErr,
351                          const UnicodeString*   pattern,
352                          DecimalFormatSymbols*  symbolsToAdopt)
353 {
354     fSymbols = symbolsToAdopt; // Do this BEFORE aborting on status failure!!!
355     fRoundingIncrement = NULL;
356     fRoundingMode = kRoundHalfEven;
357     fPad = kPatternPadEscape;
358     fPadPosition = kPadBeforePrefix;
359     if (U_FAILURE(status))
360         return;
361 
362     fPosPrefixPattern = fPosSuffixPattern = NULL;
363     fNegPrefixPattern = fNegSuffixPattern = NULL;
364     setMultiplier(1);
365     fGroupingSize = 3;
366     fGroupingSize2 = 0;
367     fDecimalSeparatorAlwaysShown = FALSE;
368     fUseExponentialNotation = FALSE;
369     fMinExponentDigits = 0;
370 
371     if (fSymbols == NULL)
372     {
373         fSymbols = new DecimalFormatSymbols(Locale::getDefault(), status);
374         /* test for NULL */
375         if (fSymbols == 0) {
376             status = U_MEMORY_ALLOCATION_ERROR;
377             return;
378         }
379     }
380 
381     UnicodeString str;
382     // Uses the default locale's number format pattern if there isn't
383     // one specified.
384     if (pattern == NULL)
385     {
386         int32_t len = 0;
387         UResourceBundle *resource = ures_open(NULL, Locale::getDefault().getName(), &status);
388 
389         resource = ures_getByKey(resource, fgNumberPatterns, resource, &status);
390         const UChar *resStr = ures_getStringByIndex(resource, (int32_t)0, &len, &status);
391         str.setTo(TRUE, resStr, len);
392         pattern = &str;
393         ures_close(resource);
394     }
395 
396     if (U_FAILURE(status))
397     {
398         return;
399     }
400 
401     if (pattern->indexOf((UChar)kCurrencySign) >= 0) {
402         // If it looks like we are going to use a currency pattern
403         // then do the time consuming lookup.
404         setCurrencyForSymbols();
405     } else {
406         setCurrencyInternally(NULL, status);
407     }
408 
409     const UnicodeString* patternUsed;
410     UnicodeString currencyPluralPatternForOther;
411     // apply pattern
412     if (fStyle == NumberFormat::kPluralCurrencyStyle) {
413         fCurrencyPluralInfo = new CurrencyPluralInfo(fSymbols->getLocale(), status);
414         if (U_FAILURE(status)) {
415             return;
416         }
417 
418         // the pattern used in format is not fixed until formatting,
419         // in which, the number is known and
420         // will be used to pick the right pattern based on plural count.
421         // Here, set the pattern as the pattern of plural count == "other".
422         // For most locale, the patterns are probably the same for all
423         // plural count. If not, the right pattern need to be re-applied
424         // during format.
425         fCurrencyPluralInfo->getCurrencyPluralPattern("other", currencyPluralPatternForOther);
426         patternUsed = &currencyPluralPatternForOther;
427         // TODO: not needed?
428         setCurrencyForSymbols();
429 
430     } else {
431         patternUsed = pattern;
432     }
433 
434     if (patternUsed->indexOf(kCurrencySign) != -1) {
435         // initialize for currency, not only for plural format,
436         // but also for mix parsing
437         if (fCurrencyPluralInfo == NULL) {
438            fCurrencyPluralInfo = new CurrencyPluralInfo(fSymbols->getLocale(), status);
439            if (U_FAILURE(status)) {
440                return;
441            }
442         }
443         // need it for mix parsing
444         setupCurrencyAffixPatterns(status);
445         // expanded affixes for plural names
446         if (patternUsed->indexOf(fgTripleCurrencySign) != -1) {
447             setupCurrencyAffixes(*patternUsed, TRUE, TRUE, status);
448         }
449     }
450 
451     applyPatternWithoutExpandAffix(*patternUsed,FALSE, parseErr, status);
452 
453     // expand affixes
454     if (fCurrencySignCount != fgCurrencySignCountInPluralFormat) {
455         expandAffixAdjustWidth(NULL);
456     }
457 
458     // If it was a currency format, apply the appropriate rounding by
459     // resetting the currency. NOTE: this copies fCurrency on top of itself.
460     if (fCurrencySignCount > fgCurrencySignCountZero) {
461         setCurrencyInternally(getCurrency(), status);
462     }
463 }
464 
465 
466 void
setupCurrencyAffixPatterns(UErrorCode & status)467 DecimalFormat::setupCurrencyAffixPatterns(UErrorCode& status) {
468     if (U_FAILURE(status)) {
469         return;
470     }
471     UParseError parseErr;
472     fAffixPatternsForCurrency = initHashForAffixPattern(status);
473     if (U_FAILURE(status)) {
474         return;
475     }
476 
477     // Save the default currency patterns of this locale.
478     // Here, chose onlyApplyPatternWithoutExpandAffix without
479     // expanding the affix patterns into affixes.
480     UnicodeString currencyPattern;
481     UErrorCode error = U_ZERO_ERROR;
482     UResourceBundle *resource = ures_open((char *)0, fSymbols->getLocale().getName(), &error);
483     UResourceBundle *numberPatterns = ures_getByKey(resource, fgNumberPatterns, NULL, &error);
484     int32_t patLen = 0;
485     const UChar *patResStr = ures_getStringByIndex(numberPatterns, kCurrencyStyle,  &patLen, &error);
486     ures_close(numberPatterns);
487     ures_close(resource);
488 
489     if (U_SUCCESS(error)) {
490         applyPatternWithoutExpandAffix(UnicodeString(patResStr, patLen), false,
491                                        parseErr, status);
492         AffixPatternsForCurrency* affixPtn = new AffixPatternsForCurrency(
493                                                     *fNegPrefixPattern,
494                                                     *fNegSuffixPattern,
495                                                     *fPosPrefixPattern,
496                                                     *fPosSuffixPattern,
497                                                     UCURR_SYMBOL_NAME);
498         fAffixPatternsForCurrency->put("default", affixPtn, status);
499     }
500 
501     // save the unique currency plural patterns of this locale.
502     Hashtable* pluralPtn = fCurrencyPluralInfo->fPluralCountToCurrencyUnitPattern;
503     const UHashElement* element = NULL;
504     int32_t pos = -1;
505     Hashtable pluralPatternSet;
506     while ((element = pluralPtn->nextElement(pos)) != NULL) {
507         const UHashTok valueTok = element->value;
508         const UnicodeString* value = (UnicodeString*)valueTok.pointer;
509         const UHashTok keyTok = element->key;
510         const UnicodeString* key = (UnicodeString*)keyTok.pointer;
511         if (pluralPatternSet.geti(*value) != 1) {
512             pluralPatternSet.puti(*value, 1, status);
513             applyPatternWithoutExpandAffix(*value, false, parseErr, status);
514             AffixPatternsForCurrency* affixPtn = new AffixPatternsForCurrency(
515                                                     *fNegPrefixPattern,
516                                                     *fNegSuffixPattern,
517                                                     *fPosPrefixPattern,
518                                                     *fPosSuffixPattern,
519                                                     UCURR_LONG_NAME);
520             fAffixPatternsForCurrency->put(*key, affixPtn, status);
521         }
522     }
523 }
524 
525 
526 void
setupCurrencyAffixes(const UnicodeString & pattern,UBool setupForCurrentPattern,UBool setupForPluralPattern,UErrorCode & status)527 DecimalFormat::setupCurrencyAffixes(const UnicodeString& pattern,
528                                     UBool setupForCurrentPattern,
529                                     UBool setupForPluralPattern,
530                                     UErrorCode& status) {
531     if (U_FAILURE(status)) {
532         return;
533     }
534     UParseError parseErr;
535     if (setupForCurrentPattern) {
536         if (fAffixesForCurrency) {
537             deleteHashForAffix(fAffixesForCurrency);
538         }
539         fAffixesForCurrency = initHashForAffix(status);
540         if (U_SUCCESS(status)) {
541             applyPatternWithoutExpandAffix(pattern, false, parseErr, status);
542             const PluralRules* pluralRules = fCurrencyPluralInfo->getPluralRules();
543             StringEnumeration* keywords = pluralRules->getKeywords(status);
544             if (U_SUCCESS(status)) {
545                 const char* pluralCountCh;
546                 while ((pluralCountCh = keywords->next(NULL, status)) != NULL) {
547                     if ( U_SUCCESS(status) ) {
548                         UnicodeString pluralCount = UnicodeString(pluralCountCh);
549                         expandAffixAdjustWidth(&pluralCount);
550                         AffixesForCurrency* affix = new AffixesForCurrency(
551                             fNegativePrefix, fNegativeSuffix, fPositivePrefix, fPositiveSuffix);
552                         fAffixesForCurrency->put(pluralCount, affix, status);
553                     }
554                 }
555             }
556             delete keywords;
557         }
558     }
559 
560     if (U_FAILURE(status)) {
561         return;
562     }
563 
564     if (setupForPluralPattern) {
565         if (fPluralAffixesForCurrency) {
566             deleteHashForAffix(fPluralAffixesForCurrency);
567         }
568         fPluralAffixesForCurrency = initHashForAffix(status);
569         if (U_SUCCESS(status)) {
570             const PluralRules* pluralRules = fCurrencyPluralInfo->getPluralRules();
571             StringEnumeration* keywords = pluralRules->getKeywords(status);
572             if (U_SUCCESS(status)) {
573                 const char* pluralCountCh;
574                 while ((pluralCountCh = keywords->next(NULL, status)) != NULL) {
575                     if ( U_SUCCESS(status) ) {
576                         UnicodeString pluralCount = UnicodeString(pluralCountCh);
577                         UnicodeString ptn;
578                         fCurrencyPluralInfo->getCurrencyPluralPattern(pluralCount, ptn);
579                         applyPatternInternally(pluralCount, ptn, false, parseErr, status);
580                         AffixesForCurrency* affix = new AffixesForCurrency(
581                             fNegativePrefix, fNegativeSuffix, fPositivePrefix, fPositiveSuffix);
582                         fPluralAffixesForCurrency->put(pluralCount, affix, status);
583                     }
584                 }
585             }
586             delete keywords;
587         }
588     }
589 }
590 
591 
592 //------------------------------------------------------------------------------
593 
~DecimalFormat()594 DecimalFormat::~DecimalFormat()
595 {
596     delete fPosPrefixPattern;
597     delete fPosSuffixPattern;
598     delete fNegPrefixPattern;
599     delete fNegSuffixPattern;
600     delete fCurrencyChoice;
601     delete fMultiplier;
602     delete fSymbols;
603     delete fRoundingIncrement;
604     deleteHashForAffixPattern();
605     deleteHashForAffix(fAffixesForCurrency);
606     deleteHashForAffix(fPluralAffixesForCurrency);
607     delete fCurrencyPluralInfo;
608 }
609 
610 //------------------------------------------------------------------------------
611 // copy constructor
612 
DecimalFormat(const DecimalFormat & source)613 DecimalFormat::DecimalFormat(const DecimalFormat &source) :
614     NumberFormat(source) {
615     init();
616     *this = source;
617 }
618 
619 //------------------------------------------------------------------------------
620 // assignment operator
621 
_copy_us_ptr(UnicodeString ** pdest,const UnicodeString * source)622 static void _copy_us_ptr(UnicodeString** pdest, const UnicodeString* source) {
623     if (source == NULL) {
624         delete *pdest;
625         *pdest = NULL;
626     } else if (*pdest == NULL) {
627         *pdest = new UnicodeString(*source);
628     } else {
629         **pdest  = *source;
630     }
631 }
632 
633 DecimalFormat&
operator =(const DecimalFormat & rhs)634 DecimalFormat::operator=(const DecimalFormat& rhs)
635 {
636     if(this != &rhs) {
637         NumberFormat::operator=(rhs);
638         fPositivePrefix = rhs.fPositivePrefix;
639         fPositiveSuffix = rhs.fPositiveSuffix;
640         fNegativePrefix = rhs.fNegativePrefix;
641         fNegativeSuffix = rhs.fNegativeSuffix;
642         _copy_us_ptr(&fPosPrefixPattern, rhs.fPosPrefixPattern);
643         _copy_us_ptr(&fPosSuffixPattern, rhs.fPosSuffixPattern);
644         _copy_us_ptr(&fNegPrefixPattern, rhs.fNegPrefixPattern);
645         _copy_us_ptr(&fNegSuffixPattern, rhs.fNegSuffixPattern);
646         if (rhs.fCurrencyChoice == 0) {
647             delete fCurrencyChoice;
648             fCurrencyChoice = 0;
649         } else {
650             fCurrencyChoice = (ChoiceFormat*) rhs.fCurrencyChoice->clone();
651         }
652         setRoundingIncrement(rhs.getRoundingIncrement());
653         fRoundingMode = rhs.fRoundingMode;
654         setMultiplier(rhs.getMultiplier());
655         fGroupingSize = rhs.fGroupingSize;
656         fGroupingSize2 = rhs.fGroupingSize2;
657         fDecimalSeparatorAlwaysShown = rhs.fDecimalSeparatorAlwaysShown;
658         if(fSymbols == NULL) {
659             fSymbols = new DecimalFormatSymbols(*rhs.fSymbols);
660         } else {
661             *fSymbols = *rhs.fSymbols;
662         }
663         fUseExponentialNotation = rhs.fUseExponentialNotation;
664         fExponentSignAlwaysShown = rhs.fExponentSignAlwaysShown;
665         /*Bertrand A. D. Update 98.03.17*/
666         fCurrencySignCount = rhs.fCurrencySignCount;
667         /*end of Update*/
668         fMinExponentDigits = rhs.fMinExponentDigits;
669 
670         /* sfb 990629 */
671         fFormatWidth = rhs.fFormatWidth;
672         fPad = rhs.fPad;
673         fPadPosition = rhs.fPadPosition;
674         /* end sfb */
675         fMinSignificantDigits = rhs.fMinSignificantDigits;
676         fMaxSignificantDigits = rhs.fMaxSignificantDigits;
677         fUseSignificantDigits = rhs.fUseSignificantDigits;
678         fFormatPattern = rhs.fFormatPattern;
679         fStyle = rhs.fStyle;
680         fCurrencySignCount = rhs.fCurrencySignCount;
681         if (rhs.fCurrencyPluralInfo) {
682             delete fCurrencyPluralInfo;
683             fCurrencyPluralInfo = rhs.fCurrencyPluralInfo->clone();
684         }
685         if (rhs.fAffixPatternsForCurrency) {
686             UErrorCode status = U_ZERO_ERROR;
687             deleteHashForAffixPattern();
688             fAffixPatternsForCurrency = initHashForAffixPattern(status);
689             copyHashForAffixPattern(rhs.fAffixPatternsForCurrency,
690                                     fAffixPatternsForCurrency, status);
691         }
692         if (rhs.fAffixesForCurrency) {
693             UErrorCode status = U_ZERO_ERROR;
694             deleteHashForAffix(fAffixesForCurrency);
695             fAffixesForCurrency = initHashForAffixPattern(status);
696             copyHashForAffix(rhs.fAffixesForCurrency, fAffixesForCurrency, status);
697         }
698         if (rhs.fPluralAffixesForCurrency) {
699             UErrorCode status = U_ZERO_ERROR;
700             deleteHashForAffix(fPluralAffixesForCurrency);
701             fPluralAffixesForCurrency = initHashForAffixPattern(status);
702             copyHashForAffix(rhs.fPluralAffixesForCurrency, fPluralAffixesForCurrency, status);
703         }
704     }
705     return *this;
706 }
707 
708 //------------------------------------------------------------------------------
709 
710 UBool
operator ==(const Format & that) const711 DecimalFormat::operator==(const Format& that) const
712 {
713     if (this == &that)
714         return TRUE;
715 
716     // NumberFormat::operator== guarantees this cast is safe
717     const DecimalFormat* other = (DecimalFormat*)&that;
718 
719 #ifdef FMT_DEBUG
720     // This code makes it easy to determine why two format objects that should
721     // be equal aren't.
722     UBool first = TRUE;
723     if (!NumberFormat::operator==(that)) {
724         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
725         debug("NumberFormat::!=");
726     } else {
727     if (!((fPosPrefixPattern == other->fPosPrefixPattern && // both null
728               fPositivePrefix == other->fPositivePrefix)
729            || (fPosPrefixPattern != 0 && other->fPosPrefixPattern != 0 &&
730                *fPosPrefixPattern  == *other->fPosPrefixPattern))) {
731         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
732         debug("Pos Prefix !=");
733     }
734     if (!((fPosSuffixPattern == other->fPosSuffixPattern && // both null
735            fPositiveSuffix == other->fPositiveSuffix)
736           || (fPosSuffixPattern != 0 && other->fPosSuffixPattern != 0 &&
737               *fPosSuffixPattern  == *other->fPosSuffixPattern))) {
738         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
739         debug("Pos Suffix !=");
740     }
741     if (!((fNegPrefixPattern == other->fNegPrefixPattern && // both null
742            fNegativePrefix == other->fNegativePrefix)
743           || (fNegPrefixPattern != 0 && other->fNegPrefixPattern != 0 &&
744               *fNegPrefixPattern  == *other->fNegPrefixPattern))) {
745         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
746         debug("Neg Prefix ");
747         if (fNegPrefixPattern == NULL) {
748             debug("NULL(");
749             debugout(fNegativePrefix);
750             debug(")");
751         } else {
752             debugout(*fNegPrefixPattern);
753         }
754         debug(" != ");
755         if (other->fNegPrefixPattern == NULL) {
756             debug("NULL(");
757             debugout(other->fNegativePrefix);
758             debug(")");
759         } else {
760             debugout(*other->fNegPrefixPattern);
761         }
762     }
763     if (!((fNegSuffixPattern == other->fNegSuffixPattern && // both null
764            fNegativeSuffix == other->fNegativeSuffix)
765           || (fNegSuffixPattern != 0 && other->fNegSuffixPattern != 0 &&
766               *fNegSuffixPattern  == *other->fNegSuffixPattern))) {
767         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
768         debug("Neg Suffix ");
769         if (fNegSuffixPattern == NULL) {
770             debug("NULL(");
771             debugout(fNegativeSuffix);
772             debug(")");
773         } else {
774             debugout(*fNegSuffixPattern);
775         }
776         debug(" != ");
777         if (other->fNegSuffixPattern == NULL) {
778             debug("NULL(");
779             debugout(other->fNegativeSuffix);
780             debug(")");
781         } else {
782             debugout(*other->fNegSuffixPattern);
783         }
784     }
785     if (!((fRoundingIncrement == other->fRoundingIncrement) // both null
786           || (fRoundingIncrement != NULL &&
787               other->fRoundingIncrement != NULL &&
788               *fRoundingIncrement == *other->fRoundingIncrement))) {
789         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
790         debug("Rounding Increment !=");
791               }
792     if (getMultiplier() != other->getMultiplier()) {
793         if (first) { printf("[ "); first = FALSE; }
794         printf("Multiplier %ld != %ld", getMultiplier(), other->getMultiplier());
795     }
796     if (fGroupingSize != other->fGroupingSize) {
797         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
798         printf("Grouping Size %ld != %ld", fGroupingSize, other->fGroupingSize);
799     }
800     if (fGroupingSize2 != other->fGroupingSize2) {
801         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
802         printf("Secondary Grouping Size %ld != %ld", fGroupingSize2, other->fGroupingSize2);
803     }
804     if (fDecimalSeparatorAlwaysShown != other->fDecimalSeparatorAlwaysShown) {
805         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
806         printf("Dec Sep Always %d != %d", fDecimalSeparatorAlwaysShown, other->fDecimalSeparatorAlwaysShown);
807     }
808     if (fUseExponentialNotation != other->fUseExponentialNotation) {
809         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
810         debug("Use Exp !=");
811     }
812     if (!(!fUseExponentialNotation ||
813           fMinExponentDigits != other->fMinExponentDigits)) {
814         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
815         debug("Exp Digits !=");
816     }
817     if (*fSymbols != *(other->fSymbols)) {
818         if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
819         debug("Symbols !=");
820     }
821     // TODO Add debug stuff for significant digits here
822     if (fUseSignificantDigits != other->fUseSignificantDigits) {
823         debug("fUseSignificantDigits !=");
824     }
825     if (fUseSignificantDigits &&
826         fMinSignificantDigits != other->fMinSignificantDigits) {
827         debug("fMinSignificantDigits !=");
828     }
829     if (fUseSignificantDigits &&
830         fMaxSignificantDigits != other->fMaxSignificantDigits) {
831         debug("fMaxSignificantDigits !=");
832     }
833 
834     if (!first) { printf(" ]"); }
835     if (fCurrencySignCount != other->fCurrencySignCount) {
836         debug("fCurrencySignCount !=");
837     }
838     if (fCurrencyPluralInfo == other->fCurrencyPluralInfo) {
839         debug("fCurrencyPluralInfo == ");
840         if (fCurrencyPluralInfo == NULL) {
841             debug("fCurrencyPluralInfo == NULL");
842         }
843     }
844     if (fCurrencyPluralInfo != NULL && other->fCurrencyPluralInfo != NULL &&
845          *fCurrencyPluralInfo != *(other->fCurrencyPluralInfo)) {
846         debug("fCurrencyPluralInfo !=");
847     }
848     if (fCurrencyPluralInfo != NULL && other->fCurrencyPluralInfo == NULL ||
849         fCurrencyPluralInfo == NULL && other->fCurrencyPluralInfo != NULL) {
850         debug("fCurrencyPluralInfo one NULL, the other not");
851     }
852     if (fCurrencyPluralInfo == NULL && other->fCurrencyPluralInfo == NULL) {
853         debug("fCurrencyPluralInfo == ");
854     }
855     }
856 #endif
857 
858     return (NumberFormat::operator==(that) &&
859             ((fCurrencySignCount == fgCurrencySignCountInPluralFormat) ?
860             (fAffixPatternsForCurrency->equals(*other->fAffixPatternsForCurrency)) :
861             (((fPosPrefixPattern == other->fPosPrefixPattern && // both null
862               fPositivePrefix == other->fPositivePrefix)
863              || (fPosPrefixPattern != 0 && other->fPosPrefixPattern != 0 &&
864                  *fPosPrefixPattern  == *other->fPosPrefixPattern)) &&
865             ((fPosSuffixPattern == other->fPosSuffixPattern && // both null
866               fPositiveSuffix == other->fPositiveSuffix)
867              || (fPosSuffixPattern != 0 && other->fPosSuffixPattern != 0 &&
868                  *fPosSuffixPattern  == *other->fPosSuffixPattern)) &&
869             ((fNegPrefixPattern == other->fNegPrefixPattern && // both null
870               fNegativePrefix == other->fNegativePrefix)
871              || (fNegPrefixPattern != 0 && other->fNegPrefixPattern != 0 &&
872                  *fNegPrefixPattern  == *other->fNegPrefixPattern)) &&
873             ((fNegSuffixPattern == other->fNegSuffixPattern && // both null
874               fNegativeSuffix == other->fNegativeSuffix)
875              || (fNegSuffixPattern != 0 && other->fNegSuffixPattern != 0 &&
876                  *fNegSuffixPattern  == *other->fNegSuffixPattern)))) &&
877             ((fRoundingIncrement == other->fRoundingIncrement) // both null
878              || (fRoundingIncrement != NULL &&
879                  other->fRoundingIncrement != NULL &&
880                  *fRoundingIncrement == *other->fRoundingIncrement)) &&
881         getMultiplier() == other->getMultiplier() &&
882         fGroupingSize == other->fGroupingSize &&
883         fGroupingSize2 == other->fGroupingSize2 &&
884         fDecimalSeparatorAlwaysShown == other->fDecimalSeparatorAlwaysShown &&
885         fUseExponentialNotation == other->fUseExponentialNotation &&
886         (!fUseExponentialNotation ||
887          fMinExponentDigits == other->fMinExponentDigits) &&
888         *fSymbols == *(other->fSymbols) &&
889         fUseSignificantDigits == other->fUseSignificantDigits &&
890         (!fUseSignificantDigits ||
891          (fMinSignificantDigits == other->fMinSignificantDigits &&
892           fMaxSignificantDigits == other->fMaxSignificantDigits)) &&
893         fCurrencySignCount == other->fCurrencySignCount &&
894         ((fCurrencyPluralInfo == other->fCurrencyPluralInfo &&
895           fCurrencyPluralInfo == NULL) ||
896          (fCurrencyPluralInfo != NULL && other->fCurrencyPluralInfo != NULL &&
897          *fCurrencyPluralInfo == *(other->fCurrencyPluralInfo))));
898 }
899 
900 //------------------------------------------------------------------------------
901 
902 Format*
clone() const903 DecimalFormat::clone() const
904 {
905     return new DecimalFormat(*this);
906 }
907 
908 //------------------------------------------------------------------------------
909 
910 UnicodeString&
format(int32_t number,UnicodeString & appendTo,FieldPosition & fieldPosition) const911 DecimalFormat::format(int32_t number,
912                       UnicodeString& appendTo,
913                       FieldPosition& fieldPosition) const
914 {
915     return format((int64_t)number, appendTo, fieldPosition);
916 }
917 
918 UnicodeString&
format(int32_t number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const919 DecimalFormat::format(int32_t number,
920                       UnicodeString& appendTo,
921                       FieldPositionIterator* posIter,
922                       UErrorCode& status) const
923 {
924     return format((int64_t)number, appendTo, posIter, status);
925 }
926 
927 //------------------------------------------------------------------------------
928 
929 UnicodeString&
format(int64_t number,UnicodeString & appendTo,FieldPosition & fieldPosition) const930 DecimalFormat::format(int64_t number,
931                       UnicodeString& appendTo,
932                       FieldPosition& fieldPosition) const
933 {
934     FieldPositionOnlyHandler handler(fieldPosition);
935     return _format(number, appendTo, handler);
936 }
937 
938 UnicodeString&
format(int64_t number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const939 DecimalFormat::format(int64_t number,
940                       UnicodeString& appendTo,
941                       FieldPositionIterator* posIter,
942                       UErrorCode& status) const
943 {
944     FieldPositionIteratorHandler handler(posIter, status);
945     return _format(number, appendTo, handler);
946 }
947 
948 UnicodeString&
_format(int64_t number,UnicodeString & appendTo,FieldPositionHandler & handler) const949 DecimalFormat::_format(int64_t number,
950                        UnicodeString& appendTo,
951                        FieldPositionHandler& handler) const
952 {
953     UErrorCode status = U_ZERO_ERROR;
954     DigitList digits;
955     digits.set(number);
956     return _format(digits, appendTo, handler, status);
957 }
958 
959 //------------------------------------------------------------------------------
960 
961 UnicodeString&
format(double number,UnicodeString & appendTo,FieldPosition & fieldPosition) const962 DecimalFormat::format(  double number,
963                         UnicodeString& appendTo,
964                         FieldPosition& fieldPosition) const
965 {
966     FieldPositionOnlyHandler handler(fieldPosition);
967     return _format(number, appendTo, handler);
968 }
969 
970 UnicodeString&
format(double number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const971 DecimalFormat::format(  double number,
972                         UnicodeString& appendTo,
973                         FieldPositionIterator* posIter,
974                         UErrorCode& status) const
975 {
976   FieldPositionIteratorHandler handler(posIter, status);
977   return _format(number, appendTo, handler);
978 }
979 
980 UnicodeString&
_format(double number,UnicodeString & appendTo,FieldPositionHandler & handler) const981 DecimalFormat::_format( double number,
982                         UnicodeString& appendTo,
983                         FieldPositionHandler& handler) const
984 {
985     // Special case for NaN, sets the begin and end index to be the
986     // the string length of localized name of NaN.
987     // TODO:  let NaNs go through DigitList.
988     if (uprv_isNaN(number))
989     {
990         int begin = appendTo.length();
991         appendTo += getConstSymbol(DecimalFormatSymbols::kNaNSymbol);
992 
993         handler.addAttribute(kIntegerField, begin, appendTo.length());
994 
995         addPadding(appendTo, handler, 0, 0);
996         return appendTo;
997     }
998 
999     UErrorCode status = U_ZERO_ERROR;
1000     DigitList digits;
1001     digits.set(number);
1002     _format(digits, appendTo, handler, status);
1003     // No way to return status from here.
1004     return appendTo;
1005 }
1006 
1007 //------------------------------------------------------------------------------
1008 
1009 
1010 UnicodeString&
format(const StringPiece & number,UnicodeString & toAppendTo,FieldPositionIterator * posIter,UErrorCode & status) const1011 DecimalFormat::format(const StringPiece &number,
1012                       UnicodeString &toAppendTo,
1013                       FieldPositionIterator *posIter,
1014                       UErrorCode &status) const
1015 {
1016     DigitList   dnum;
1017     dnum.set(number, status);
1018     if (U_FAILURE(status)) {
1019         return toAppendTo;
1020     }
1021     FieldPositionIteratorHandler handler(posIter, status);
1022     _format(dnum, toAppendTo, handler, status);
1023     return toAppendTo;
1024 }
1025 
1026 
1027 UnicodeString&
format(const DigitList & number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const1028 DecimalFormat::format(const DigitList &number,
1029                       UnicodeString &appendTo,
1030                       FieldPositionIterator *posIter,
1031                       UErrorCode &status) const {
1032     FieldPositionIteratorHandler handler(posIter, status);
1033     _format(number, appendTo, handler, status);
1034     return appendTo;
1035 }
1036 
1037 
1038 
1039 UnicodeString&
format(const DigitList & number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const1040 DecimalFormat::format(const DigitList &number,
1041                      UnicodeString& appendTo,
1042                      FieldPosition& pos,
1043                      UErrorCode &status) const {
1044     FieldPositionOnlyHandler handler(pos);
1045     _format(number, appendTo, handler, status);
1046     return appendTo;
1047 }
1048 
1049 
1050 
1051 UnicodeString&
_format(const DigitList & number,UnicodeString & appendTo,FieldPositionHandler & handler,UErrorCode & status) const1052 DecimalFormat::_format(const DigitList &number,
1053                         UnicodeString& appendTo,
1054                         FieldPositionHandler& handler,
1055                         UErrorCode &status) const
1056 {
1057     // Special case for NaN, sets the begin and end index to be the
1058     // the string length of localized name of NaN.
1059     if (number.isNaN())
1060     {
1061         int begin = appendTo.length();
1062         appendTo += getConstSymbol(DecimalFormatSymbols::kNaNSymbol);
1063 
1064         handler.addAttribute(kIntegerField, begin, appendTo.length());
1065 
1066         addPadding(appendTo, handler, 0, 0);
1067         return appendTo;
1068     }
1069 
1070     // Do this BEFORE checking to see if value is infinite or negative! Sets the
1071     // begin and end index to be length of the string composed of
1072     // localized name of Infinite and the positive/negative localized
1073     // signs.
1074 
1075     DigitList adjustedNum(number);  // Copy, so we do not alter the original.
1076     adjustedNum.setRoundingMode(fRoundingMode);
1077     if (fMultiplier != NULL) {
1078         adjustedNum.mult(*fMultiplier, status);
1079     }
1080 
1081     /*
1082      * Note: sign is important for zero as well as non-zero numbers.
1083      * Proper detection of -0.0 is needed to deal with the
1084      * issues raised by bugs 4106658, 4106667, and 4147706.  Liu 7/6/98.
1085      */
1086     UBool isNegative = !adjustedNum.isPositive();
1087 
1088     // Apply rounding after multiplier
1089     if (fRoundingIncrement != NULL) {
1090         adjustedNum.div(*fRoundingIncrement, status);
1091         adjustedNum.toIntegralValue();
1092         adjustedNum.mult(*fRoundingIncrement, status);
1093         adjustedNum.trim();
1094     }
1095 
1096     // Special case for INFINITE,
1097     if (adjustedNum.isInfinite()) {
1098         int32_t prefixLen = appendAffix(appendTo, adjustedNum.getDouble(), handler, isNegative, TRUE);
1099 
1100         int begin = appendTo.length();
1101         appendTo += getConstSymbol(DecimalFormatSymbols::kInfinitySymbol);
1102 
1103         handler.addAttribute(kIntegerField, begin, appendTo.length());
1104 
1105         int32_t suffixLen = appendAffix(appendTo, adjustedNum.getDouble(), handler, isNegative, FALSE);
1106 
1107         addPadding(appendTo, handler, prefixLen, suffixLen);
1108         return appendTo;
1109     }
1110 
1111     if (fRoundingIncrement == NULL) {
1112         if (fUseExponentialNotation || areSignificantDigitsUsed()) {
1113             int32_t sigDigits = precision();
1114             if (sigDigits > 0) {
1115                 adjustedNum.round(sigDigits);
1116             }
1117         } else {
1118             // Fixed point format.  Round to a set number of fraction digits.
1119             int32_t numFractionDigits = precision();
1120             adjustedNum.roundFixedPoint(numFractionDigits);
1121         }
1122     }
1123 
1124     return subformat(appendTo, handler, adjustedNum, FALSE);
1125 }
1126 
1127 
1128 UnicodeString&
format(const Formattable & obj,UnicodeString & appendTo,FieldPosition & fieldPosition,UErrorCode & status) const1129 DecimalFormat::format(  const Formattable& obj,
1130                         UnicodeString& appendTo,
1131                         FieldPosition& fieldPosition,
1132                         UErrorCode& status) const
1133 {
1134     return NumberFormat::format(obj, appendTo, fieldPosition, status);
1135 }
1136 
1137 /**
1138  * Return true if a grouping separator belongs at the given
1139  * position, based on whether grouping is in use and the values of
1140  * the primary and secondary grouping interval.
1141  * @param pos the number of integer digits to the right of
1142  * the current position.  Zero indicates the position after the
1143  * rightmost integer digit.
1144  * @return true if a grouping character belongs at the current
1145  * position.
1146  */
isGroupingPosition(int32_t pos) const1147 UBool DecimalFormat::isGroupingPosition(int32_t pos) const {
1148     UBool result = FALSE;
1149     if (isGroupingUsed() && (pos > 0) && (fGroupingSize > 0)) {
1150         if ((fGroupingSize2 > 0) && (pos > fGroupingSize)) {
1151             result = ((pos - fGroupingSize) % fGroupingSize2) == 0;
1152         } else {
1153             result = pos % fGroupingSize == 0;
1154         }
1155     }
1156     return result;
1157 }
1158 
1159 //------------------------------------------------------------------------------
1160 
1161 /**
1162  * Complete the formatting of a finite number.  On entry, the DigitList must
1163  * be filled in with the correct digits.
1164  */
1165 UnicodeString&
subformat(UnicodeString & appendTo,FieldPositionHandler & handler,DigitList & digits,UBool isInteger) const1166 DecimalFormat::subformat(UnicodeString& appendTo,
1167                          FieldPositionHandler& handler,
1168                          DigitList&     digits,
1169                          UBool          isInteger) const
1170 {
1171     // Gets the localized zero Unicode character.
1172     UChar32 zero = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
1173     int32_t zeroDelta = zero - '0'; // '0' is the DigitList representation of zero
1174     const UnicodeString *grouping ;
1175     if(fCurrencySignCount > fgCurrencySignCountZero) {
1176         grouping = &getConstSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol);
1177     }else{
1178         grouping = &getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
1179     }
1180     const UnicodeString *decimal;
1181     if(fCurrencySignCount > fgCurrencySignCountZero) {
1182         decimal = &getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol);
1183     } else {
1184         decimal = &getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
1185     }
1186     UBool useSigDig = areSignificantDigitsUsed();
1187     int32_t maxIntDig = getMaximumIntegerDigits();
1188     int32_t minIntDig = getMinimumIntegerDigits();
1189 
1190     // Appends the prefix.
1191     double doubleValue = digits.getDouble();
1192     int32_t prefixLen = appendAffix(appendTo, doubleValue, handler, !digits.isPositive(), TRUE);
1193 
1194     if (fUseExponentialNotation)
1195     {
1196         int currentLength = appendTo.length();
1197         int intBegin = currentLength;
1198         int intEnd = -1;
1199         int fracBegin = -1;
1200 
1201         int32_t minFracDig = 0;
1202         if (useSigDig) {
1203             maxIntDig = minIntDig = 1;
1204             minFracDig = getMinimumSignificantDigits() - 1;
1205         } else {
1206             minFracDig = getMinimumFractionDigits();
1207             if (maxIntDig > kMaxScientificIntegerDigits) {
1208                 maxIntDig = 1;
1209                 if (maxIntDig < minIntDig) {
1210                     maxIntDig = minIntDig;
1211                 }
1212             }
1213             if (maxIntDig > minIntDig) {
1214                 minIntDig = 1;
1215             }
1216         }
1217 
1218         // Minimum integer digits are handled in exponential format by
1219         // adjusting the exponent.  For example, 0.01234 with 3 minimum
1220         // integer digits is "123.4E-4".
1221 
1222         // Maximum integer digits are interpreted as indicating the
1223         // repeating range.  This is useful for engineering notation, in
1224         // which the exponent is restricted to a multiple of 3.  For
1225         // example, 0.01234 with 3 maximum integer digits is "12.34e-3".
1226         // If maximum integer digits are defined and are larger than
1227         // minimum integer digits, then minimum integer digits are
1228         // ignored.
1229         digits.reduce();   // Removes trailing zero digits.
1230         int32_t exponent = digits.getDecimalAt();
1231         if (maxIntDig > 1 && maxIntDig != minIntDig) {
1232             // A exponent increment is defined; adjust to it.
1233             exponent = (exponent > 0) ? (exponent - 1) / maxIntDig
1234                                       : (exponent / maxIntDig) - 1;
1235             exponent *= maxIntDig;
1236         } else {
1237             // No exponent increment is defined; use minimum integer digits.
1238             // If none is specified, as in "#E0", generate 1 integer digit.
1239             exponent -= (minIntDig > 0 || minFracDig > 0)
1240                         ? minIntDig : 1;
1241         }
1242 
1243         // We now output a minimum number of digits, and more if there
1244         // are more digits, up to the maximum number of digits.  We
1245         // place the decimal point after the "integer" digits, which
1246         // are the first (decimalAt - exponent) digits.
1247         int32_t minimumDigits =  minIntDig + minFracDig;
1248         // The number of integer digits is handled specially if the number
1249         // is zero, since then there may be no digits.
1250         int32_t integerDigits = digits.isZero() ? minIntDig :
1251             digits.getDecimalAt() - exponent;
1252         int32_t totalDigits = digits.getCount();
1253         if (minimumDigits > totalDigits)
1254             totalDigits = minimumDigits;
1255         if (integerDigits > totalDigits)
1256             totalDigits = integerDigits;
1257 
1258         // totalDigits records total number of digits needs to be processed
1259         int32_t i;
1260         for (i=0; i<totalDigits; ++i)
1261         {
1262             if (i == integerDigits)
1263             {
1264                 intEnd = appendTo.length();
1265                 handler.addAttribute(kIntegerField, intBegin, intEnd);
1266 
1267                 appendTo += *decimal;
1268 
1269                 fracBegin = appendTo.length();
1270                 handler.addAttribute(kDecimalSeparatorField, fracBegin - 1, fracBegin);
1271             }
1272             // Restores the digit character or pads the buffer with zeros.
1273             UChar32 c = (UChar32)((i < digits.getCount()) ?
1274                           (digits.getDigit(i) + zeroDelta) :
1275                           zero);
1276             appendTo += c;
1277         }
1278 
1279         currentLength = appendTo.length();
1280 
1281         if (intEnd < 0) {
1282             handler.addAttribute(kIntegerField, intBegin, currentLength);
1283         }
1284         if (fracBegin > 0) {
1285             handler.addAttribute(kFractionField, fracBegin, currentLength);
1286         }
1287 
1288         // The exponent is output using the pattern-specified minimum
1289         // exponent digits.  There is no maximum limit to the exponent
1290         // digits, since truncating the exponent would appendTo in an
1291         // unacceptable inaccuracy.
1292         appendTo += getConstSymbol(DecimalFormatSymbols::kExponentialSymbol);
1293 
1294         handler.addAttribute(kExponentSymbolField, currentLength, appendTo.length());
1295         currentLength = appendTo.length();
1296 
1297         // For zero values, we force the exponent to zero.  We
1298         // must do this here, and not earlier, because the value
1299         // is used to determine integer digit count above.
1300         if (digits.isZero())
1301             exponent = 0;
1302 
1303         if (exponent < 0) {
1304             appendTo += getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
1305             handler.addAttribute(kExponentSignField, currentLength, appendTo.length());
1306         } else if (fExponentSignAlwaysShown) {
1307             appendTo += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
1308             handler.addAttribute(kExponentSignField, currentLength, appendTo.length());
1309         }
1310 
1311         currentLength = appendTo.length();
1312 
1313         DigitList expDigits;
1314         expDigits.set(exponent);
1315         {
1316             int expDig = fMinExponentDigits;
1317             if (fUseExponentialNotation && expDig < 1) {
1318                 expDig = 1;
1319             }
1320             for (i=expDigits.getDecimalAt(); i<expDig; ++i)
1321                 appendTo += (zero);
1322         }
1323         for (i=0; i<expDigits.getDecimalAt(); ++i)
1324         {
1325             UChar32 c = (UChar32)((i < expDigits.getCount()) ?
1326                           (expDigits.getDigit(i) + zeroDelta) : zero);
1327             appendTo += c;
1328         }
1329 
1330         handler.addAttribute(kExponentField, currentLength, appendTo.length());
1331     }
1332     else  // Not using exponential notation
1333     {
1334         int currentLength = appendTo.length();
1335         int intBegin = currentLength;
1336 
1337         int32_t sigCount = 0;
1338         int32_t minSigDig = getMinimumSignificantDigits();
1339         int32_t maxSigDig = getMaximumSignificantDigits();
1340         if (!useSigDig) {
1341             minSigDig = 0;
1342             maxSigDig = INT32_MAX;
1343         }
1344 
1345         // Output the integer portion.  Here 'count' is the total
1346         // number of integer digits we will display, including both
1347         // leading zeros required to satisfy getMinimumIntegerDigits,
1348         // and actual digits present in the number.
1349         int32_t count = useSigDig ?
1350             _max(1, digits.getDecimalAt()) : minIntDig;
1351         if (digits.getDecimalAt() > 0 && count < digits.getDecimalAt()) {
1352             count = digits.getDecimalAt();
1353         }
1354 
1355         // Handle the case where getMaximumIntegerDigits() is smaller
1356         // than the real number of integer digits.  If this is so, we
1357         // output the least significant max integer digits.  For example,
1358         // the value 1997 printed with 2 max integer digits is just "97".
1359 
1360         int32_t digitIndex = 0; // Index into digitList.fDigits[]
1361         if (count > maxIntDig && maxIntDig >= 0) {
1362             count = maxIntDig;
1363             digitIndex = digits.getDecimalAt() - count;
1364         }
1365 
1366         int32_t sizeBeforeIntegerPart = appendTo.length();
1367 
1368         int32_t i;
1369         for (i=count-1; i>=0; --i)
1370         {
1371             if (i < digits.getDecimalAt() && digitIndex < digits.getCount() &&
1372                 sigCount < maxSigDig) {
1373                 // Output a real digit
1374                 appendTo += ((UChar32)(digits.getDigit(digitIndex++) + zeroDelta));
1375                 ++sigCount;
1376             }
1377             else
1378             {
1379                 // Output a zero (leading or trailing)
1380                 appendTo += (zero);
1381                 if (sigCount > 0) {
1382                     ++sigCount;
1383                 }
1384             }
1385 
1386             // Output grouping separator if necessary.
1387             if (isGroupingPosition(i)) {
1388                 currentLength = appendTo.length();
1389                 appendTo.append(*grouping);
1390                 handler.addAttribute(kGroupingSeparatorField, currentLength, appendTo.length());
1391             }
1392         }
1393 
1394         // TODO(dlf): this looks like it was a bug, we marked the int field as ending
1395         // before the zero was generated.
1396         // Record field information for caller.
1397         // if (fieldPosition.getField() == NumberFormat::kIntegerField)
1398         //     fieldPosition.setEndIndex(appendTo.length());
1399 
1400         // Determine whether or not there are any printable fractional
1401         // digits.  If we've used up the digits we know there aren't.
1402         UBool fractionPresent = (!isInteger && digitIndex < digits.getCount()) ||
1403             (useSigDig ? (sigCount < minSigDig) : (getMinimumFractionDigits() > 0));
1404 
1405         // If there is no fraction present, and we haven't printed any
1406         // integer digits, then print a zero.  Otherwise we won't print
1407         // _any_ digits, and we won't be able to parse this string.
1408         if (!fractionPresent && appendTo.length() == sizeBeforeIntegerPart)
1409             appendTo += (zero);
1410 
1411         currentLength = appendTo.length();
1412         handler.addAttribute(kIntegerField, intBegin, currentLength);
1413 
1414         // Output the decimal separator if we always do so.
1415         if (fDecimalSeparatorAlwaysShown || fractionPresent) {
1416             appendTo += *decimal;
1417             handler.addAttribute(kDecimalSeparatorField, currentLength, appendTo.length());
1418             currentLength = appendTo.length();
1419         }
1420 
1421         int fracBegin = currentLength;
1422 
1423         count = useSigDig ? INT32_MAX : getMaximumFractionDigits();
1424         if (useSigDig && (sigCount == maxSigDig ||
1425                           (sigCount >= minSigDig && digitIndex == digits.getCount()))) {
1426             count = 0;
1427         }
1428 
1429         for (i=0; i < count; ++i) {
1430             // Here is where we escape from the loop.  We escape
1431             // if we've output the maximum fraction digits
1432             // (specified in the for expression above).  We also
1433             // stop when we've output the minimum digits and
1434             // either: we have an integer, so there is no
1435             // fractional stuff to display, or we're out of
1436             // significant digits.
1437             if (!useSigDig && i >= getMinimumFractionDigits() &&
1438                 (isInteger || digitIndex >= digits.getCount())) {
1439                 break;
1440             }
1441 
1442             // Output leading fractional zeros.  These are zeros
1443             // that come after the decimal but before any
1444             // significant digits.  These are only output if
1445             // abs(number being formatted) < 1.0.
1446             if (-1-i > (digits.getDecimalAt()-1)) {
1447                 appendTo += zero;
1448                 continue;
1449             }
1450 
1451             // Output a digit, if we have any precision left, or a
1452             // zero if we don't.  We don't want to output noise digits.
1453             if (!isInteger && digitIndex < digits.getCount()) {
1454                 appendTo += ((UChar32)(digits.getDigit(digitIndex++) + zeroDelta));
1455             } else {
1456                 appendTo += zero;
1457             }
1458 
1459             // If we reach the maximum number of significant
1460             // digits, or if we output all the real digits and
1461             // reach the minimum, then we are done.
1462             ++sigCount;
1463             if (useSigDig &&
1464                 (sigCount == maxSigDig ||
1465                  (digitIndex == digits.getCount() && sigCount >= minSigDig))) {
1466                 break;
1467             }
1468         }
1469 
1470         handler.addAttribute(kFractionField, fracBegin, appendTo.length());
1471     }
1472 
1473     int32_t suffixLen = appendAffix(appendTo, doubleValue, handler, !digits.isPositive(), FALSE);
1474 
1475     addPadding(appendTo, handler, prefixLen, suffixLen);
1476     return appendTo;
1477 }
1478 
1479 /**
1480  * Inserts the character fPad as needed to expand result to fFormatWidth.
1481  * @param result the string to be padded
1482  */
addPadding(UnicodeString & appendTo,FieldPositionHandler & handler,int32_t prefixLen,int32_t suffixLen) const1483 void DecimalFormat::addPadding(UnicodeString& appendTo,
1484                                FieldPositionHandler& handler,
1485                                int32_t prefixLen,
1486                                int32_t suffixLen) const
1487 {
1488     if (fFormatWidth > 0) {
1489         int32_t len = fFormatWidth - appendTo.length();
1490         if (len > 0) {
1491             UnicodeString padding;
1492             for (int32_t i=0; i<len; ++i) {
1493                 padding += fPad;
1494             }
1495             switch (fPadPosition) {
1496             case kPadAfterPrefix:
1497                 appendTo.insert(prefixLen, padding);
1498                 break;
1499             case kPadBeforePrefix:
1500                 appendTo.insert(0, padding);
1501                 break;
1502             case kPadBeforeSuffix:
1503                 appendTo.insert(appendTo.length() - suffixLen, padding);
1504                 break;
1505             case kPadAfterSuffix:
1506                 appendTo += padding;
1507                 break;
1508             }
1509             if (fPadPosition == kPadBeforePrefix || fPadPosition == kPadAfterPrefix) {
1510                 handler.shiftLast(len);
1511             }
1512         }
1513     }
1514 }
1515 
1516 //------------------------------------------------------------------------------
1517 
1518 void
parse(const UnicodeString & text,Formattable & result,UErrorCode & status) const1519 DecimalFormat::parse(const UnicodeString& text,
1520                      Formattable& result,
1521                      UErrorCode& status) const
1522 {
1523     NumberFormat::parse(text, result, status);
1524 }
1525 
1526 void
parse(const UnicodeString & text,Formattable & result,ParsePosition & parsePosition) const1527 DecimalFormat::parse(const UnicodeString& text,
1528                      Formattable& result,
1529                      ParsePosition& parsePosition) const {
1530     parse(text, result, parsePosition, FALSE);
1531 }
1532 
parseCurrency(const UnicodeString & text,Formattable & result,ParsePosition & pos) const1533 Formattable& DecimalFormat::parseCurrency(const UnicodeString& text,
1534                                           Formattable& result,
1535                                           ParsePosition& pos) const {
1536     parse(text, result, pos, TRUE);
1537     return result;
1538 }
1539 
1540 /**
1541  * Parses the given text as either a number or a currency amount.
1542  * @param text the string to parse
1543  * @param result output parameter for the result
1544  * @param parsePosition input-output position; on input, the
1545  * position within text to match; must have 0 <= pos.getIndex() <
1546  * text.length(); on output, the position after the last matched
1547  * character. If the parse fails, the position in unchanged upon
1548  * output.
1549  * @param parseCurrency if true, a currency amount is parsed;
1550  * otherwise a Number is parsed
1551  */
parse(const UnicodeString & text,Formattable & result,ParsePosition & parsePosition,UBool parseCurrency) const1552 void DecimalFormat::parse(const UnicodeString& text,
1553                           Formattable& result,
1554                           ParsePosition& parsePosition,
1555                           UBool parseCurrency) const {
1556     int32_t backup;
1557     int32_t i = backup = parsePosition.getIndex();
1558 
1559     // clear any old contents in the result.  In particular, clears any DigitList
1560     //   that it may be holding.
1561     result.setLong(0);
1562 
1563     // Handle NaN as a special case:
1564 
1565     // Skip padding characters, if around prefix
1566     if (fFormatWidth > 0 && (fPadPosition == kPadBeforePrefix ||
1567                              fPadPosition == kPadAfterPrefix)) {
1568         i = skipPadding(text, i);
1569     }
1570     // If the text is composed of the representation of NaN, returns NaN.length
1571     const UnicodeString *nan = &getConstSymbol(DecimalFormatSymbols::kNaNSymbol);
1572     int32_t nanLen = (text.compare(i, nan->length(), *nan)
1573                       ? 0 : nan->length());
1574     if (nanLen) {
1575         i += nanLen;
1576         if (fFormatWidth > 0 && (fPadPosition == kPadBeforeSuffix ||
1577                                  fPadPosition == kPadAfterSuffix)) {
1578             i = skipPadding(text, i);
1579         }
1580         parsePosition.setIndex(i);
1581         result.setDouble(uprv_getNaN());
1582         return;
1583     }
1584 
1585     // NaN parse failed; start over
1586     i = backup;
1587 
1588     // status is used to record whether a number is infinite.
1589     UBool status[fgStatusLength];
1590     UChar curbuf[4];
1591     UChar* currency = parseCurrency ? curbuf : NULL;
1592     DigitList *digits = new DigitList;
1593     if (digits == NULL) {
1594         return;    // no way to report error from here.
1595     }
1596 
1597     if (fCurrencySignCount > fgCurrencySignCountZero) {
1598         if (!parseForCurrency(text, parsePosition, *digits,
1599                               status, currency)) {
1600             delete digits;
1601             return;
1602         }
1603     } else {
1604         if (!subparse(text,
1605                       fNegPrefixPattern, fNegSuffixPattern,
1606                       fPosPrefixPattern, fPosSuffixPattern,
1607                       FALSE, UCURR_SYMBOL_NAME,
1608                       parsePosition, *digits, status, currency)) {
1609             parsePosition.setIndex(backup);
1610             delete digits;
1611             return;
1612         }
1613     }
1614 
1615     // Handle infinity
1616     if (status[fgStatusInfinite]) {
1617         double inf = uprv_getInfinity();
1618         result.setDouble(digits->isPositive() ? inf : -inf);
1619         delete digits;    // TODO:  set the dl to infinity, and let it fall into the code below.
1620     }
1621 
1622     else {
1623 
1624         if (fMultiplier != NULL) {
1625             UErrorCode ec = U_ZERO_ERROR;
1626             digits->div(*fMultiplier, ec);
1627         }
1628 
1629         // Negative zero special case:
1630         //    if parsing integerOnly, change to +0, which goes into an int32 in a Formattable.
1631         //    if not parsing integerOnly, leave as -0, which a double can represent.
1632         if (digits->isZero() && !digits->isPositive() && isParseIntegerOnly()) {
1633             digits->setPositive(TRUE);
1634         }
1635         result.adoptDigitList(digits);
1636     }
1637 
1638     if (parseCurrency) {
1639         UErrorCode ec = U_ZERO_ERROR;
1640         Formattable n(result);
1641         result.adoptObject(new CurrencyAmount(n, curbuf, ec));
1642         U_ASSERT(U_SUCCESS(ec)); // should always succeed
1643     }
1644 }
1645 
1646 
1647 
1648 UBool
parseForCurrency(const UnicodeString & text,ParsePosition & parsePosition,DigitList & digits,UBool * status,UChar * currency) const1649 DecimalFormat::parseForCurrency(const UnicodeString& text,
1650                                 ParsePosition& parsePosition,
1651                                 DigitList& digits,
1652                                 UBool* status,
1653                                 UChar* currency) const {
1654     int origPos = parsePosition.getIndex();
1655     int maxPosIndex = origPos;
1656     int maxErrorPos = -1;
1657     // First, parse against current pattern.
1658     // Since current pattern could be set by applyPattern(),
1659     // it could be an arbitrary pattern, and it may not be the one
1660     // defined in current locale.
1661     UBool tmpStatus[fgStatusLength];
1662     ParsePosition tmpPos(origPos);
1663     DigitList tmpDigitList;
1664     UBool found;
1665     if (fStyle == NumberFormat::kPluralCurrencyStyle) {
1666         found = subparse(text,
1667                          fNegPrefixPattern, fNegSuffixPattern,
1668                          fPosPrefixPattern, fPosSuffixPattern,
1669                          TRUE, UCURR_LONG_NAME,
1670                          tmpPos, tmpDigitList, tmpStatus, currency);
1671     } else {
1672         found = subparse(text,
1673                          fNegPrefixPattern, fNegSuffixPattern,
1674                          fPosPrefixPattern, fPosSuffixPattern,
1675                          TRUE, UCURR_SYMBOL_NAME,
1676                          tmpPos, tmpDigitList, tmpStatus, currency);
1677     }
1678     if (found) {
1679         if (tmpPos.getIndex() > maxPosIndex) {
1680             maxPosIndex = tmpPos.getIndex();
1681             for (int32_t i = 0; i < fgStatusLength; ++i) {
1682                 status[i] = tmpStatus[i];
1683             }
1684             digits = tmpDigitList;
1685         }
1686     } else {
1687         maxErrorPos = tmpPos.getErrorIndex();
1688     }
1689     // Then, parse against affix patterns.
1690     // Those are currency patterns and currency plural patterns.
1691     int32_t pos = -1;
1692     const UHashElement* element = NULL;
1693     while ( (element = fAffixPatternsForCurrency->nextElement(pos)) != NULL ) {
1694         const UHashTok keyTok = element->key;
1695         const UHashTok valueTok = element->value;
1696         const AffixPatternsForCurrency* affixPtn = (AffixPatternsForCurrency*)valueTok.pointer;
1697         UBool tmpStatus[fgStatusLength];
1698         ParsePosition tmpPos(origPos);
1699         DigitList tmpDigitList;
1700         UBool result = subparse(text,
1701                                 &affixPtn->negPrefixPatternForCurrency,
1702                                 &affixPtn->negSuffixPatternForCurrency,
1703                                 &affixPtn->posPrefixPatternForCurrency,
1704                                 &affixPtn->posSuffixPatternForCurrency,
1705                                 TRUE, affixPtn->patternType,
1706                                 tmpPos, tmpDigitList, tmpStatus, currency);
1707         if (result) {
1708             found = true;
1709             if (tmpPos.getIndex() > maxPosIndex) {
1710                 maxPosIndex = tmpPos.getIndex();
1711                 for (int32_t i = 0; i < fgStatusLength; ++i) {
1712                     status[i] = tmpStatus[i];
1713                 }
1714                 digits = tmpDigitList;
1715             }
1716         } else {
1717             maxErrorPos = (tmpPos.getErrorIndex() > maxErrorPos) ?
1718                           tmpPos.getErrorIndex() : maxErrorPos;
1719         }
1720     }
1721     // Finally, parse against simple affix to find the match.
1722     // For example, in TestMonster suite,
1723     // if the to-be-parsed text is "-\u00A40,00".
1724     // complexAffixCompare will not find match,
1725     // since there is no ISO code matches "\u00A4",
1726     // and the parse stops at "\u00A4".
1727     // We will just use simple affix comparison (look for exact match)
1728     // to pass it.
1729     UBool tmpStatus_2[fgStatusLength];
1730     ParsePosition tmpPos_2(origPos);
1731     DigitList tmpDigitList_2;
1732     // set currencySignCount to 0 so that compareAffix function will
1733     // fall to compareSimpleAffix path, not compareComplexAffix path.
1734     // ?? TODO: is it right? need "false"?
1735     UBool result = subparse(text,
1736                             &fNegativePrefix, &fNegativeSuffix,
1737                             &fPositivePrefix, &fPositiveSuffix,
1738                             FALSE, UCURR_SYMBOL_NAME,
1739                             tmpPos_2, tmpDigitList_2, tmpStatus_2,
1740                             currency);
1741     if (result) {
1742         if (tmpPos_2.getIndex() > maxPosIndex) {
1743             maxPosIndex = tmpPos_2.getIndex();
1744             for (int32_t i = 0; i < fgStatusLength; ++i) {
1745                 status[i] = tmpStatus_2[i];
1746             }
1747             digits = tmpDigitList_2;
1748         }
1749         found = true;
1750     } else {
1751             maxErrorPos = (tmpPos_2.getErrorIndex() > maxErrorPos) ?
1752                           tmpPos_2.getErrorIndex() : maxErrorPos;
1753     }
1754 
1755     if (!found) {
1756         //parsePosition.setIndex(origPos);
1757         parsePosition.setErrorIndex(maxErrorPos);
1758     } else {
1759         parsePosition.setIndex(maxPosIndex);
1760         parsePosition.setErrorIndex(-1);
1761     }
1762     return found;
1763 }
1764 
1765 
1766 /**
1767  * Parse the given text into a number.  The text is parsed beginning at
1768  * parsePosition, until an unparseable character is seen.
1769  * @param text the string to parse.
1770  * @param negPrefix negative prefix.
1771  * @param negSuffix negative suffix.
1772  * @param posPrefix positive prefix.
1773  * @param posSuffix positive suffix.
1774  * @param currencyParsing whether it is currency parsing or not.
1775  * @param type the currency type to parse against, LONG_NAME only or not.
1776  * @param parsePosition The position at which to being parsing.  Upon
1777  * return, the first unparsed character.
1778  * @param digits the DigitList to set to the parsed value.
1779  * @param status output param containing boolean status flags indicating
1780  * whether the value was infinite and whether it was positive.
1781  * @param currency return value for parsed currency, for generic
1782  * currency parsing mode, or NULL for normal parsing. In generic
1783  * currency parsing mode, any currency is parsed, not just the
1784  * currency that this formatter is set to.
1785  */
subparse(const UnicodeString & text,const UnicodeString * negPrefix,const UnicodeString * negSuffix,const UnicodeString * posPrefix,const UnicodeString * posSuffix,UBool currencyParsing,int8_t type,ParsePosition & parsePosition,DigitList & digits,UBool * status,UChar * currency) const1786 UBool DecimalFormat::subparse(const UnicodeString& text,
1787                               const UnicodeString* negPrefix,
1788                               const UnicodeString* negSuffix,
1789                               const UnicodeString* posPrefix,
1790                               const UnicodeString* posSuffix,
1791                               UBool currencyParsing,
1792                               int8_t type,
1793                               ParsePosition& parsePosition,
1794                               DigitList& digits, UBool* status,
1795                               UChar* currency) const
1796 {
1797     //  The parsing process builds up the number as char string, in the neutral format that
1798     //  will be acceptable to the decNumber library, then at the end passes that string
1799     //  off for conversion to a decNumber.
1800     UErrorCode err = U_ZERO_ERROR;
1801     DecimalNumberString  parsedNum;
1802     digits.setToZero();
1803 
1804     int32_t position = parsePosition.getIndex();
1805     int32_t oldStart = position;
1806 
1807     // Match padding before prefix
1808     if (fFormatWidth > 0 && fPadPosition == kPadBeforePrefix) {
1809         position = skipPadding(text, position);
1810     }
1811 
1812     // Match positive and negative prefixes; prefer longest match.
1813     int32_t posMatch = compareAffix(text, position, FALSE, TRUE, posPrefix, currencyParsing, type, currency);
1814     int32_t negMatch = compareAffix(text, position, TRUE, TRUE, negPrefix,currencyParsing,  type, currency);
1815     if (posMatch >= 0 && negMatch >= 0) {
1816         if (posMatch > negMatch) {
1817             negMatch = -1;
1818         } else if (negMatch > posMatch) {
1819             posMatch = -1;
1820         }
1821     }
1822     if (posMatch >= 0) {
1823         position += posMatch;
1824         parsedNum.append('+', err);
1825     } else if (negMatch >= 0) {
1826         position += negMatch;
1827         parsedNum.append('-', err);
1828     } else {
1829         parsePosition.setErrorIndex(position);
1830         return FALSE;
1831     }
1832 
1833     // Match padding before prefix
1834     if (fFormatWidth > 0 && fPadPosition == kPadAfterPrefix) {
1835         position = skipPadding(text, position);
1836     }
1837 
1838     // process digits or Inf, find decimal position
1839     const UnicodeString *inf = &getConstSymbol(DecimalFormatSymbols::kInfinitySymbol);
1840     int32_t infLen = (text.compare(position, inf->length(), *inf)
1841         ? 0 : inf->length());
1842     position += infLen; // infLen is non-zero when it does equal to infinity
1843     status[fgStatusInfinite] = (UBool)infLen;
1844     if (infLen) {
1845         parsedNum.append("Infinity", err);
1846     } else {
1847         // We now have a string of digits, possibly with grouping symbols,
1848         // and decimal points.  We want to process these into a DigitList.
1849         // We don't want to put a bunch of leading zeros into the DigitList
1850         // though, so we keep track of the location of the decimal point,
1851         // put only significant digits into the DigitList, and adjust the
1852         // exponent as needed.
1853 
1854         UChar32 zero = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
1855 
1856         const UnicodeString *decimal;
1857         if(fCurrencySignCount > fgCurrencySignCountZero) {
1858             decimal = &getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol);
1859         } else {
1860             decimal = &getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
1861         }
1862         const UnicodeString *grouping = &getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
1863         UBool sawDecimal = FALSE;
1864         UBool sawDigit = FALSE;
1865         int32_t backup = -1;
1866         int32_t digit;
1867         int32_t textLength = text.length(); // One less pointer to follow
1868         int32_t groupingLen = grouping->length();
1869         int32_t decimalLen = decimal->length();
1870 
1871         // We have to track digitCount ourselves, because digits.fCount will
1872         // pin when the maximum allowable digits is reached.
1873         int32_t digitCount = 0;
1874 
1875         for (; position < textLength; )
1876         {
1877             UChar32 ch = text.char32At(position);
1878 
1879             /* We recognize all digit ranges, not only the Latin digit range
1880              * '0'..'9'.  We do so by using the Character.digit() method,
1881              * which converts a valid Unicode digit to the range 0..9.
1882              *
1883              * The character 'ch' may be a digit.  If so, place its value
1884              * from 0 to 9 in 'digit'.  First try using the locale digit,
1885              * which may or MAY NOT be a standard Unicode digit range.  If
1886              * this fails, try using the standard Unicode digit ranges by
1887              * calling Character.digit().  If this also fails, digit will
1888              * have a value outside the range 0..9.
1889              */
1890             digit = ch - zero;
1891             if (digit < 0 || digit > 9)
1892             {
1893                 digit = u_charDigitValue(ch);
1894             }
1895 
1896             if (digit >= 0 && digit <= 9)
1897             {
1898                 // Cancel out backup setting (see grouping handler below)
1899                 backup = -1;
1900 
1901                 sawDigit = TRUE;
1902                 // output a regular non-zero digit.
1903                 ++digitCount;
1904                 parsedNum.append(digit + '0', err);
1905                 position += U16_LENGTH(ch);
1906             }
1907             else if (groupingLen > 0 && !text.compare(position, groupingLen, *grouping) && isGroupingUsed())
1908             {
1909                 // Ignore grouping characters, if we are using them, but require
1910                 // that they be followed by a digit.  Otherwise we backup and
1911                 // reprocess them.
1912                 backup = position;
1913                 position += groupingLen;
1914             }
1915             else if (!text.compare(position, decimalLen, *decimal) && !isParseIntegerOnly() && !sawDecimal)
1916             {
1917                 // If we're only parsing integers, or if we ALREADY saw the
1918                 // decimal, then don't parse this one.
1919 
1920                 parsedNum.append('.', err);
1921                 sawDecimal = TRUE;
1922                 position += decimalLen;
1923             }
1924             else {
1925                 const UnicodeString *tmp;
1926                 tmp = &getConstSymbol(DecimalFormatSymbols::kExponentialSymbol);
1927                 if (!text.caseCompare(position, tmp->length(), *tmp, U_FOLD_CASE_DEFAULT))    // error code is set below if !sawDigit
1928                 {
1929                     // Parse sign, if present
1930                     int32_t pos = position + tmp->length();
1931                     char exponentSign = '+';
1932 
1933                     if (pos < textLength)
1934                     {
1935                         tmp = &getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
1936                         if (!text.compare(pos, tmp->length(), *tmp))
1937                         {
1938                             pos += tmp->length();
1939                         }
1940                         else {
1941                             tmp = &getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
1942                             if (!text.compare(pos, tmp->length(), *tmp))
1943                             {
1944                                 exponentSign = '-';
1945                                 pos += tmp->length();
1946                             }
1947                         }
1948                     }
1949 
1950                     UBool sawExponentDigit = FALSE;
1951                     while (pos < textLength) {
1952                         ch = text[(int32_t)pos];
1953                         digit = ch - zero;
1954 
1955                         if (digit < 0 || digit > 9) {
1956                             digit = u_charDigitValue(ch);
1957                         }
1958                         if (0 <= digit && digit <= 9) {
1959                             if (!sawExponentDigit) {
1960                                 parsedNum.append('E', err);
1961                                 parsedNum.append(exponentSign, err);
1962                                 sawExponentDigit = TRUE;
1963                             }
1964                             ++pos;
1965                             parsedNum.append((char)(digit + '0'), err);
1966                         } else {
1967                             break;
1968                         }
1969                     }
1970 
1971                     if (sawExponentDigit) {
1972                         position = pos; // Advance past the exponent
1973                     }
1974 
1975                     break; // Whether we fail or succeed, we exit this loop
1976                 }
1977                 else {
1978                     break;
1979                 }
1980             }
1981         }
1982 
1983         if (backup != -1)
1984         {
1985             position = backup;
1986         }
1987 
1988         // If there was no decimal point we have an integer
1989 
1990         // If none of the text string was recognized.  For example, parse
1991         // "x" with pattern "#0.00" (return index and error index both 0)
1992         // parse "$" with pattern "$#0.00". (return index 0 and error index
1993         // 1).
1994         if (!sawDigit && digitCount == 0) {
1995             parsePosition.setIndex(oldStart);
1996             parsePosition.setErrorIndex(oldStart);
1997             return FALSE;
1998         }
1999     }
2000 
2001     // Match padding before suffix
2002     if (fFormatWidth > 0 && fPadPosition == kPadBeforeSuffix) {
2003         position = skipPadding(text, position);
2004     }
2005 
2006     // Match positive and negative suffixes; prefer longest match.
2007     if (posMatch >= 0) {
2008         posMatch = compareAffix(text, position, FALSE, FALSE, posSuffix, currencyParsing, type, currency);
2009     }
2010     if (negMatch >= 0) {
2011         negMatch = compareAffix(text, position, TRUE, FALSE, negSuffix, currencyParsing, type, currency);
2012     }
2013     if (posMatch >= 0 && negMatch >= 0) {
2014         if (posMatch > negMatch) {
2015             negMatch = -1;
2016         } else if (negMatch > posMatch) {
2017             posMatch = -1;
2018         }
2019     }
2020 
2021     // Fail if neither or both
2022     if ((posMatch >= 0) == (negMatch >= 0)) {
2023         parsePosition.setErrorIndex(position);
2024         return FALSE;
2025     }
2026 
2027     position += (posMatch>=0 ? posMatch : negMatch);
2028 
2029     // Match padding before suffix
2030     if (fFormatWidth > 0 && fPadPosition == kPadAfterSuffix) {
2031         position = skipPadding(text, position);
2032     }
2033 
2034     parsePosition.setIndex(position);
2035 
2036     parsedNum[0] = (posMatch >= 0) ? '+' : '-';
2037 
2038     if(parsePosition.getIndex() == oldStart)
2039     {
2040         parsePosition.setErrorIndex(position);
2041         return FALSE;
2042     }
2043     digits.set(parsedNum, err);
2044 
2045     if (U_FAILURE(err)) {
2046         parsePosition.setErrorIndex(position);
2047         return FALSE;
2048     }
2049     return TRUE;
2050 }
2051 
2052 /**
2053  * Starting at position, advance past a run of pad characters, if any.
2054  * Return the index of the first character after position that is not a pad
2055  * character.  Result is >= position.
2056  */
skipPadding(const UnicodeString & text,int32_t position) const2057 int32_t DecimalFormat::skipPadding(const UnicodeString& text, int32_t position) const {
2058     int32_t padLen = U16_LENGTH(fPad);
2059     while (position < text.length() &&
2060            text.char32At(position) == fPad) {
2061         position += padLen;
2062     }
2063     return position;
2064 }
2065 
2066 /**
2067  * Return the length matched by the given affix, or -1 if none.
2068  * Runs of white space in the affix, match runs of white space in
2069  * the input.  Pattern white space and input white space are
2070  * determined differently; see code.
2071  * @param text input text
2072  * @param pos offset into input at which to begin matching
2073  * @param isNegative
2074  * @param isPrefix
2075  * @param affixPat affix pattern used for currency affix comparison.
2076  * @param currencyParsing whether it is currency parsing or not
2077  * @param type the currency type to parse against, LONG_NAME only or not.
2078  * @param currency return value for parsed currency, for generic
2079  * currency parsing mode, or null for normal parsing. In generic
2080  * currency parsing mode, any currency is parsed, not just the
2081  * currency that this formatter is set to.
2082  * @return length of input that matches, or -1 if match failure
2083  */
compareAffix(const UnicodeString & text,int32_t pos,UBool isNegative,UBool isPrefix,const UnicodeString * affixPat,UBool currencyParsing,int8_t type,UChar * currency) const2084 int32_t DecimalFormat::compareAffix(const UnicodeString& text,
2085                                     int32_t pos,
2086                                     UBool isNegative,
2087                                     UBool isPrefix,
2088                                     const UnicodeString* affixPat,
2089                                     UBool currencyParsing,
2090                                     int8_t type,
2091                                     UChar* currency) const
2092 {
2093     const UnicodeString *patternToCompare;
2094     if (fCurrencyChoice != NULL || currency != NULL ||
2095         (fCurrencySignCount > fgCurrencySignCountZero && currencyParsing)) {
2096 
2097         if (affixPat != NULL) {
2098             return compareComplexAffix(*affixPat, text, pos, type, currency);
2099         }
2100     }
2101 
2102     if (isNegative) {
2103         if (isPrefix) {
2104             patternToCompare = &fNegativePrefix;
2105         }
2106         else {
2107             patternToCompare = &fNegativeSuffix;
2108         }
2109     }
2110     else {
2111         if (isPrefix) {
2112             patternToCompare = &fPositivePrefix;
2113         }
2114         else {
2115             patternToCompare = &fPositiveSuffix;
2116         }
2117     }
2118     return compareSimpleAffix(*patternToCompare, text, pos);
2119 }
2120 
2121 /**
2122  * Return the length matched by the given affix, or -1 if none.
2123  * Runs of white space in the affix, match runs of white space in
2124  * the input.  Pattern white space and input white space are
2125  * determined differently; see code.
2126  * @param affix pattern string, taken as a literal
2127  * @param input input text
2128  * @param pos offset into input at which to begin matching
2129  * @return length of input that matches, or -1 if match failure
2130  */
compareSimpleAffix(const UnicodeString & affix,const UnicodeString & input,int32_t pos)2131 int32_t DecimalFormat::compareSimpleAffix(const UnicodeString& affix,
2132                                           const UnicodeString& input,
2133                                           int32_t pos) {
2134     int32_t start = pos;
2135     for (int32_t i=0; i<affix.length(); ) {
2136         UChar32 c = affix.char32At(i);
2137         int32_t len = U16_LENGTH(c);
2138         if (uprv_isRuleWhiteSpace(c)) {
2139             // We may have a pattern like: \u200F \u0020
2140             //        and input text like: \u200F \u0020
2141             // Note that U+200F and U+0020 are RuleWhiteSpace but only
2142             // U+0020 is UWhiteSpace.  So we have to first do a direct
2143             // match of the run of RULE whitespace in the pattern,
2144             // then match any extra characters.
2145             UBool literalMatch = FALSE;
2146             while (pos < input.length() &&
2147                    input.char32At(pos) == c) {
2148                 literalMatch = TRUE;
2149                 i += len;
2150                 pos += len;
2151                 if (i == affix.length()) {
2152                     break;
2153                 }
2154                 c = affix.char32At(i);
2155                 len = U16_LENGTH(c);
2156                 if (!uprv_isRuleWhiteSpace(c)) {
2157                     break;
2158                 }
2159             }
2160 
2161             // Advance over run in pattern
2162             i = skipRuleWhiteSpace(affix, i);
2163 
2164             // Advance over run in input text
2165             // Must see at least one white space char in input,
2166             // unless we've already matched some characters literally.
2167             int32_t s = pos;
2168             pos = skipUWhiteSpace(input, pos);
2169             if (pos == s && !literalMatch) {
2170                 return -1;
2171             }
2172 
2173             // If we skip UWhiteSpace in the input text, we need to skip it in the pattern.
2174             // Otherwise, the previous lines may have skipped over text (such as U+00A0) that
2175             // is also in the affix.
2176             i = skipUWhiteSpace(affix, i);
2177         } else {
2178             if (pos < input.length() &&
2179                 input.char32At(pos) == c) {
2180                 i += len;
2181                 pos += len;
2182             } else {
2183                 return -1;
2184             }
2185         }
2186     }
2187     return pos - start;
2188 }
2189 
2190 /**
2191  * Skip over a run of zero or more isRuleWhiteSpace() characters at
2192  * pos in text.
2193  */
skipRuleWhiteSpace(const UnicodeString & text,int32_t pos)2194 int32_t DecimalFormat::skipRuleWhiteSpace(const UnicodeString& text, int32_t pos) {
2195     while (pos < text.length()) {
2196         UChar32 c = text.char32At(pos);
2197         if (!uprv_isRuleWhiteSpace(c)) {
2198             break;
2199         }
2200         pos += U16_LENGTH(c);
2201     }
2202     return pos;
2203 }
2204 
2205 /**
2206  * Skip over a run of zero or more isUWhiteSpace() characters at pos
2207  * in text.
2208  */
skipUWhiteSpace(const UnicodeString & text,int32_t pos)2209 int32_t DecimalFormat::skipUWhiteSpace(const UnicodeString& text, int32_t pos) {
2210     while (pos < text.length()) {
2211         UChar32 c = text.char32At(pos);
2212         if (!u_isUWhiteSpace(c)) {
2213             break;
2214         }
2215         pos += U16_LENGTH(c);
2216     }
2217     return pos;
2218 }
2219 
2220 /**
2221  * Return the length matched by the given affix, or -1 if none.
2222  * @param affixPat pattern string
2223  * @param input input text
2224  * @param pos offset into input at which to begin matching
2225  * @param type the currency type to parse against, LONG_NAME only or not.
2226  * @param currency return value for parsed currency, for generic
2227  * currency parsing mode, or null for normal parsing. In generic
2228  * currency parsing mode, any currency is parsed, not just the
2229  * currency that this formatter is set to.
2230  * @return length of input that matches, or -1 if match failure
2231  */
compareComplexAffix(const UnicodeString & affixPat,const UnicodeString & text,int32_t pos,int8_t type,UChar * currency) const2232 int32_t DecimalFormat::compareComplexAffix(const UnicodeString& affixPat,
2233                                            const UnicodeString& text,
2234                                            int32_t pos,
2235                                            int8_t type,
2236                                            UChar* currency) const
2237 {
2238     int32_t start = pos;
2239     U_ASSERT(currency != NULL ||
2240              (fCurrencyChoice != NULL && *getCurrency() != 0) ||
2241              fCurrencySignCount > fgCurrencySignCountZero);
2242 
2243     for (int32_t i=0;
2244          i<affixPat.length() && pos >= 0; ) {
2245         UChar32 c = affixPat.char32At(i);
2246         i += U16_LENGTH(c);
2247 
2248         if (c == kQuote) {
2249             U_ASSERT(i <= affixPat.length());
2250             c = affixPat.char32At(i);
2251             i += U16_LENGTH(c);
2252 
2253             const UnicodeString* affix = NULL;
2254 
2255             switch (c) {
2256             case kCurrencySign: {
2257                 // since the currency names in choice format is saved
2258                 // the same way as other currency names,
2259                 // do not need to do currency choice parsing here.
2260                 // the general currency parsing parse against all names,
2261                 // including names in choice format.
2262                 UBool intl = i<affixPat.length() &&
2263                     affixPat.char32At(i) == kCurrencySign;
2264                 if (intl) {
2265                     ++i;
2266                 }
2267                 UBool plural = i<affixPat.length() &&
2268                     affixPat.char32At(i) == kCurrencySign;
2269                 if (plural) {
2270                     ++i;
2271                     intl = FALSE;
2272                 }
2273                 // Parse generic currency -- anything for which we
2274                 // have a display name, or any 3-letter ISO code.
2275                 // Try to parse display name for our locale; first
2276                 // determine our locale.
2277                 const char* loc = fCurrencyPluralInfo->getLocale().getName();
2278                 ParsePosition ppos(pos);
2279                 UChar curr[4];
2280                 UErrorCode ec = U_ZERO_ERROR;
2281                 // Delegate parse of display name => ISO code to Currency
2282                 uprv_parseCurrency(loc, text, ppos, type, curr, ec);
2283 
2284                 // If parse succeeds, populate currency[0]
2285                 if (U_SUCCESS(ec) && ppos.getIndex() != pos) {
2286                     if (currency) {
2287                         u_strcpy(currency, curr);
2288                     }
2289                     pos = ppos.getIndex();
2290                 } else {
2291                     pos = -1;
2292                 }
2293                 continue;
2294             }
2295             case kPatternPercent:
2296                 affix = &getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
2297                 break;
2298             case kPatternPerMill:
2299                 affix = &getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
2300                 break;
2301             case kPatternPlus:
2302                 affix = &getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
2303                 break;
2304             case kPatternMinus:
2305                 affix = &getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
2306                 break;
2307             default:
2308                 // fall through to affix!=0 test, which will fail
2309                 break;
2310             }
2311 
2312             if (affix != NULL) {
2313                 pos = match(text, pos, *affix);
2314                 continue;
2315             }
2316         }
2317 
2318         pos = match(text, pos, c);
2319         if (uprv_isRuleWhiteSpace(c)) {
2320             i = skipRuleWhiteSpace(affixPat, i);
2321         }
2322     }
2323     return pos - start;
2324 }
2325 
2326 /**
2327  * Match a single character at text[pos] and return the index of the
2328  * next character upon success.  Return -1 on failure.  If
2329  * isRuleWhiteSpace(ch) then match a run of white space in text.
2330  */
match(const UnicodeString & text,int32_t pos,UChar32 ch)2331 int32_t DecimalFormat::match(const UnicodeString& text, int32_t pos, UChar32 ch) {
2332     if (uprv_isRuleWhiteSpace(ch)) {
2333         // Advance over run of white space in input text
2334         // Must see at least one white space char in input
2335         int32_t s = pos;
2336         pos = skipRuleWhiteSpace(text, pos);
2337         if (pos == s) {
2338             return -1;
2339         }
2340         return pos;
2341     }
2342     return (pos >= 0 && text.char32At(pos) == ch) ?
2343         (pos + U16_LENGTH(ch)) : -1;
2344 }
2345 
2346 /**
2347  * Match a string at text[pos] and return the index of the next
2348  * character upon success.  Return -1 on failure.  Match a run of
2349  * white space in str with a run of white space in text.
2350  */
match(const UnicodeString & text,int32_t pos,const UnicodeString & str)2351 int32_t DecimalFormat::match(const UnicodeString& text, int32_t pos, const UnicodeString& str) {
2352     for (int32_t i=0; i<str.length() && pos >= 0; ) {
2353         UChar32 ch = str.char32At(i);
2354         i += U16_LENGTH(ch);
2355         if (uprv_isRuleWhiteSpace(ch)) {
2356             i = skipRuleWhiteSpace(str, i);
2357         }
2358         pos = match(text, pos, ch);
2359     }
2360     return pos;
2361 }
2362 
2363 //------------------------------------------------------------------------------
2364 // Gets the pointer to the localized decimal format symbols
2365 
2366 const DecimalFormatSymbols*
getDecimalFormatSymbols() const2367 DecimalFormat::getDecimalFormatSymbols() const
2368 {
2369     return fSymbols;
2370 }
2371 
2372 //------------------------------------------------------------------------------
2373 // De-owning the current localized symbols and adopt the new symbols.
2374 
2375 void
adoptDecimalFormatSymbols(DecimalFormatSymbols * symbolsToAdopt)2376 DecimalFormat::adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt)
2377 {
2378     if (symbolsToAdopt == NULL) {
2379         return; // do not allow caller to set fSymbols to NULL
2380     }
2381 
2382     UBool sameSymbols = FALSE;
2383     if (fSymbols != NULL) {
2384         sameSymbols = (UBool)(getConstSymbol(DecimalFormatSymbols::kCurrencySymbol) ==
2385             symbolsToAdopt->getConstSymbol(DecimalFormatSymbols::kCurrencySymbol) &&
2386             getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol) ==
2387             symbolsToAdopt->getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol));
2388         delete fSymbols;
2389     }
2390 
2391     fSymbols = symbolsToAdopt;
2392     if (!sameSymbols) {
2393         // If the currency symbols are the same, there is no need to recalculate.
2394         setCurrencyForSymbols();
2395     }
2396     expandAffixes(NULL);
2397 }
2398 //------------------------------------------------------------------------------
2399 // Setting the symbols is equlivalent to adopting a newly created localized
2400 // symbols.
2401 
2402 void
setDecimalFormatSymbols(const DecimalFormatSymbols & symbols)2403 DecimalFormat::setDecimalFormatSymbols(const DecimalFormatSymbols& symbols)
2404 {
2405     adoptDecimalFormatSymbols(new DecimalFormatSymbols(symbols));
2406 }
2407 
2408 
2409 const CurrencyPluralInfo*
getCurrencyPluralInfo(void) const2410 DecimalFormat::getCurrencyPluralInfo(void) const
2411 {
2412     return fCurrencyPluralInfo;
2413 }
2414 
2415 
2416 void
adoptCurrencyPluralInfo(CurrencyPluralInfo * toAdopt)2417 DecimalFormat::adoptCurrencyPluralInfo(CurrencyPluralInfo* toAdopt)
2418 {
2419     if (toAdopt != NULL) {
2420         delete fCurrencyPluralInfo;
2421         fCurrencyPluralInfo = toAdopt;
2422         // re-set currency affix patterns and currency affixes.
2423         if (fCurrencySignCount > fgCurrencySignCountZero) {
2424             UErrorCode status = U_ZERO_ERROR;
2425             if (fAffixPatternsForCurrency) {
2426                 deleteHashForAffixPattern();
2427             }
2428             setupCurrencyAffixPatterns(status);
2429             if (fCurrencySignCount == fgCurrencySignCountInPluralFormat) {
2430                 // only setup the affixes of the plural pattern.
2431                 setupCurrencyAffixes(fFormatPattern, FALSE, TRUE, status);
2432             }
2433         }
2434     }
2435 }
2436 
2437 void
setCurrencyPluralInfo(const CurrencyPluralInfo & info)2438 DecimalFormat::setCurrencyPluralInfo(const CurrencyPluralInfo& info)
2439 {
2440     adoptCurrencyPluralInfo(info.clone());
2441 }
2442 
2443 
2444 /**
2445  * Update the currency object to match the symbols.  This method
2446  * is used only when the caller has passed in a symbols object
2447  * that may not be the default object for its locale.
2448  */
2449 void
setCurrencyForSymbols()2450 DecimalFormat::setCurrencyForSymbols() {
2451     /*Bug 4212072
2452       Update the affix strings accroding to symbols in order to keep
2453       the affix strings up to date.
2454       [Richard/GCL]
2455     */
2456 
2457     // With the introduction of the Currency object, the currency
2458     // symbols in the DFS object are ignored.  For backward
2459     // compatibility, we check any explicitly set DFS object.  If it
2460     // is a default symbols object for its locale, we change the
2461     // currency object to one for that locale.  If it is custom,
2462     // we set the currency to null.
2463     UErrorCode ec = U_ZERO_ERROR;
2464     const UChar* c = NULL;
2465     const char* loc = fSymbols->getLocale().getName();
2466     UChar intlCurrencySymbol[4];
2467     ucurr_forLocale(loc, intlCurrencySymbol, 4, &ec);
2468     UnicodeString currencySymbol;
2469 
2470     uprv_getStaticCurrencyName(intlCurrencySymbol, loc, currencySymbol, ec);
2471     if (U_SUCCESS(ec)
2472         && getConstSymbol(DecimalFormatSymbols::kCurrencySymbol) == currencySymbol
2473         && getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol) == intlCurrencySymbol)
2474     {
2475         // Trap an error in mapping locale to currency.  If we can't
2476         // map, then don't fail and set the currency to "".
2477         c = intlCurrencySymbol;
2478     }
2479     ec = U_ZERO_ERROR; // reset local error code!
2480     setCurrencyInternally(c, ec);
2481 }
2482 
2483 
2484 //------------------------------------------------------------------------------
2485 // Gets the positive prefix of the number pattern.
2486 
2487 UnicodeString&
getPositivePrefix(UnicodeString & result) const2488 DecimalFormat::getPositivePrefix(UnicodeString& result) const
2489 {
2490     result = fPositivePrefix;
2491     return result;
2492 }
2493 
2494 //------------------------------------------------------------------------------
2495 // Sets the positive prefix of the number pattern.
2496 
2497 void
setPositivePrefix(const UnicodeString & newValue)2498 DecimalFormat::setPositivePrefix(const UnicodeString& newValue)
2499 {
2500     fPositivePrefix = newValue;
2501     delete fPosPrefixPattern;
2502     fPosPrefixPattern = 0;
2503 }
2504 
2505 //------------------------------------------------------------------------------
2506 // Gets the negative prefix  of the number pattern.
2507 
2508 UnicodeString&
getNegativePrefix(UnicodeString & result) const2509 DecimalFormat::getNegativePrefix(UnicodeString& result) const
2510 {
2511     result = fNegativePrefix;
2512     return result;
2513 }
2514 
2515 //------------------------------------------------------------------------------
2516 // Gets the negative prefix  of the number pattern.
2517 
2518 void
setNegativePrefix(const UnicodeString & newValue)2519 DecimalFormat::setNegativePrefix(const UnicodeString& newValue)
2520 {
2521     fNegativePrefix = newValue;
2522     delete fNegPrefixPattern;
2523     fNegPrefixPattern = 0;
2524 }
2525 
2526 //------------------------------------------------------------------------------
2527 // Gets the positive suffix of the number pattern.
2528 
2529 UnicodeString&
getPositiveSuffix(UnicodeString & result) const2530 DecimalFormat::getPositiveSuffix(UnicodeString& result) const
2531 {
2532     result = fPositiveSuffix;
2533     return result;
2534 }
2535 
2536 //------------------------------------------------------------------------------
2537 // Sets the positive suffix of the number pattern.
2538 
2539 void
setPositiveSuffix(const UnicodeString & newValue)2540 DecimalFormat::setPositiveSuffix(const UnicodeString& newValue)
2541 {
2542     fPositiveSuffix = newValue;
2543     delete fPosSuffixPattern;
2544     fPosSuffixPattern = 0;
2545 }
2546 
2547 //------------------------------------------------------------------------------
2548 // Gets the negative suffix of the number pattern.
2549 
2550 UnicodeString&
getNegativeSuffix(UnicodeString & result) const2551 DecimalFormat::getNegativeSuffix(UnicodeString& result) const
2552 {
2553     result = fNegativeSuffix;
2554     return result;
2555 }
2556 
2557 //------------------------------------------------------------------------------
2558 // Sets the negative suffix of the number pattern.
2559 
2560 void
setNegativeSuffix(const UnicodeString & newValue)2561 DecimalFormat::setNegativeSuffix(const UnicodeString& newValue)
2562 {
2563     fNegativeSuffix = newValue;
2564     delete fNegSuffixPattern;
2565     fNegSuffixPattern = 0;
2566 }
2567 
2568 //------------------------------------------------------------------------------
2569 // Gets the multiplier of the number pattern.
2570 //   Multipliers are stored as decimal numbers (DigitLists) because that
2571 //      is the most convenient for muliplying or dividing the numbers to be formatted.
2572 //   A NULL multiplier implies one, and the scaling operations are skipped.
2573 
2574 int32_t
getMultiplier() const2575 DecimalFormat::getMultiplier() const
2576 {
2577     if (fMultiplier == NULL) {
2578         return 1;
2579     } else {
2580         return fMultiplier->getLong();
2581     }
2582 }
2583 
2584 //------------------------------------------------------------------------------
2585 // Sets the multiplier of the number pattern.
2586 void
setMultiplier(int32_t newValue)2587 DecimalFormat::setMultiplier(int32_t newValue)
2588 {
2589 //  if (newValue == 0) {
2590 //      throw new IllegalArgumentException("Bad multiplier: " + newValue);
2591 //  }
2592     if (newValue == 0) {
2593         newValue = 1;     // one being the benign default value for a multiplier.
2594     }
2595     if (newValue == 1) {
2596         delete fMultiplier;
2597         fMultiplier = NULL;
2598     } else {
2599         if (fMultiplier == NULL) {
2600             fMultiplier = new DigitList;
2601         }
2602         if (fMultiplier != NULL) {
2603             fMultiplier->set(newValue);
2604         }
2605     }
2606 }
2607 
2608 /**
2609  * Get the rounding increment.
2610  * @return A positive rounding increment, or 0.0 if rounding
2611  * is not in effect.
2612  * @see #setRoundingIncrement
2613  * @see #getRoundingMode
2614  * @see #setRoundingMode
2615  */
getRoundingIncrement() const2616 double DecimalFormat::getRoundingIncrement() const {
2617     if (fRoundingIncrement == NULL) {
2618         return 0.0;
2619     } else {
2620         return fRoundingIncrement->getDouble();
2621     }
2622 }
2623 
2624 /**
2625  * Set the rounding increment.  This method also controls whether
2626  * rounding is enabled.
2627  * @param newValue A positive rounding increment, or 0.0 to disable rounding.
2628  * Negative increments are equivalent to 0.0.
2629  * @see #getRoundingIncrement
2630  * @see #getRoundingMode
2631  * @see #setRoundingMode
2632  */
setRoundingIncrement(double newValue)2633 void DecimalFormat::setRoundingIncrement(double newValue) {
2634     if (newValue > 0.0) {
2635         if (fRoundingIncrement == NULL) {
2636             fRoundingIncrement = new DigitList();
2637         }
2638         if (fRoundingIncrement != NULL) {
2639             fRoundingIncrement->set(newValue);
2640             return;
2641         }
2642     }
2643     // These statements are executed if newValue is less than 0.0
2644     // or fRoundingIncrement could not be created.
2645     delete fRoundingIncrement;
2646     fRoundingIncrement = NULL;
2647 }
2648 
2649 /**
2650  * Get the rounding mode.
2651  * @return A rounding mode
2652  * @see #setRoundingIncrement
2653  * @see #getRoundingIncrement
2654  * @see #setRoundingMode
2655  */
getRoundingMode() const2656 DecimalFormat::ERoundingMode DecimalFormat::getRoundingMode() const {
2657     return fRoundingMode;
2658 }
2659 
2660 /**
2661  * Set the rounding mode.  This has no effect unless the rounding
2662  * increment is greater than zero.
2663  * @param roundingMode A rounding mode
2664  * @see #setRoundingIncrement
2665  * @see #getRoundingIncrement
2666  * @see #getRoundingMode
2667  */
setRoundingMode(ERoundingMode roundingMode)2668 void DecimalFormat::setRoundingMode(ERoundingMode roundingMode) {
2669     fRoundingMode = roundingMode;
2670 }
2671 
2672 /**
2673  * Get the width to which the output of <code>format()</code> is padded.
2674  * @return the format width, or zero if no padding is in effect
2675  * @see #setFormatWidth
2676  * @see #getPadCharacter
2677  * @see #setPadCharacter
2678  * @see #getPadPosition
2679  * @see #setPadPosition
2680  */
getFormatWidth() const2681 int32_t DecimalFormat::getFormatWidth() const {
2682     return fFormatWidth;
2683 }
2684 
2685 /**
2686  * Set the width to which the output of <code>format()</code> is padded.
2687  * This method also controls whether padding is enabled.
2688  * @param width the width to which to pad the result of
2689  * <code>format()</code>, or zero to disable padding.  A negative
2690  * width is equivalent to 0.
2691  * @see #getFormatWidth
2692  * @see #getPadCharacter
2693  * @see #setPadCharacter
2694  * @see #getPadPosition
2695  * @see #setPadPosition
2696  */
setFormatWidth(int32_t width)2697 void DecimalFormat::setFormatWidth(int32_t width) {
2698     fFormatWidth = (width > 0) ? width : 0;
2699 }
2700 
getPadCharacterString() const2701 UnicodeString DecimalFormat::getPadCharacterString() const {
2702     return fPad;
2703 }
2704 
setPadCharacter(const UnicodeString & padChar)2705 void DecimalFormat::setPadCharacter(const UnicodeString &padChar) {
2706     if (padChar.length() > 0) {
2707         fPad = padChar.char32At(0);
2708     }
2709     else {
2710         fPad = kDefaultPad;
2711     }
2712 }
2713 
2714 /**
2715  * Get the position at which padding will take place.  This is the location
2716  * at which padding will be inserted if the result of <code>format()</code>
2717  * is shorter than the format width.
2718  * @return the pad position, one of <code>kPadBeforePrefix</code>,
2719  * <code>kPadAfterPrefix</code>, <code>kPadBeforeSuffix</code>, or
2720  * <code>kPadAfterSuffix</code>.
2721  * @see #setFormatWidth
2722  * @see #getFormatWidth
2723  * @see #setPadCharacter
2724  * @see #getPadCharacter
2725  * @see #setPadPosition
2726  * @see #kPadBeforePrefix
2727  * @see #kPadAfterPrefix
2728  * @see #kPadBeforeSuffix
2729  * @see #kPadAfterSuffix
2730  */
getPadPosition() const2731 DecimalFormat::EPadPosition DecimalFormat::getPadPosition() const {
2732     return fPadPosition;
2733 }
2734 
2735 /**
2736  * <strong><font face=helvetica color=red>NEW</font></strong>
2737  * Set the position at which padding will take place.  This is the location
2738  * at which padding will be inserted if the result of <code>format()</code>
2739  * is shorter than the format width.  This has no effect unless padding is
2740  * enabled.
2741  * @param padPos the pad position, one of <code>kPadBeforePrefix</code>,
2742  * <code>kPadAfterPrefix</code>, <code>kPadBeforeSuffix</code>, or
2743  * <code>kPadAfterSuffix</code>.
2744  * @see #setFormatWidth
2745  * @see #getFormatWidth
2746  * @see #setPadCharacter
2747  * @see #getPadCharacter
2748  * @see #getPadPosition
2749  * @see #kPadBeforePrefix
2750  * @see #kPadAfterPrefix
2751  * @see #kPadBeforeSuffix
2752  * @see #kPadAfterSuffix
2753  */
setPadPosition(EPadPosition padPos)2754 void DecimalFormat::setPadPosition(EPadPosition padPos) {
2755     fPadPosition = padPos;
2756 }
2757 
2758 /**
2759  * Return whether or not scientific notation is used.
2760  * @return TRUE if this object formats and parses scientific notation
2761  * @see #setScientificNotation
2762  * @see #getMinimumExponentDigits
2763  * @see #setMinimumExponentDigits
2764  * @see #isExponentSignAlwaysShown
2765  * @see #setExponentSignAlwaysShown
2766  */
isScientificNotation()2767 UBool DecimalFormat::isScientificNotation() {
2768     return fUseExponentialNotation;
2769 }
2770 
2771 /**
2772  * Set whether or not scientific notation is used.
2773  * @param useScientific TRUE if this object formats and parses scientific
2774  * notation
2775  * @see #isScientificNotation
2776  * @see #getMinimumExponentDigits
2777  * @see #setMinimumExponentDigits
2778  * @see #isExponentSignAlwaysShown
2779  * @see #setExponentSignAlwaysShown
2780  */
setScientificNotation(UBool useScientific)2781 void DecimalFormat::setScientificNotation(UBool useScientific) {
2782     fUseExponentialNotation = useScientific;
2783 }
2784 
2785 /**
2786  * Return the minimum exponent digits that will be shown.
2787  * @return the minimum exponent digits that will be shown
2788  * @see #setScientificNotation
2789  * @see #isScientificNotation
2790  * @see #setMinimumExponentDigits
2791  * @see #isExponentSignAlwaysShown
2792  * @see #setExponentSignAlwaysShown
2793  */
getMinimumExponentDigits() const2794 int8_t DecimalFormat::getMinimumExponentDigits() const {
2795     return fMinExponentDigits;
2796 }
2797 
2798 /**
2799  * Set the minimum exponent digits that will be shown.  This has no
2800  * effect unless scientific notation is in use.
2801  * @param minExpDig a value >= 1 indicating the fewest exponent digits
2802  * that will be shown.  Values less than 1 will be treated as 1.
2803  * @see #setScientificNotation
2804  * @see #isScientificNotation
2805  * @see #getMinimumExponentDigits
2806  * @see #isExponentSignAlwaysShown
2807  * @see #setExponentSignAlwaysShown
2808  */
setMinimumExponentDigits(int8_t minExpDig)2809 void DecimalFormat::setMinimumExponentDigits(int8_t minExpDig) {
2810     fMinExponentDigits = (int8_t)((minExpDig > 0) ? minExpDig : 1);
2811 }
2812 
2813 /**
2814  * Return whether the exponent sign is always shown.
2815  * @return TRUE if the exponent is always prefixed with either the
2816  * localized minus sign or the localized plus sign, false if only negative
2817  * exponents are prefixed with the localized minus sign.
2818  * @see #setScientificNotation
2819  * @see #isScientificNotation
2820  * @see #setMinimumExponentDigits
2821  * @see #getMinimumExponentDigits
2822  * @see #setExponentSignAlwaysShown
2823  */
isExponentSignAlwaysShown()2824 UBool DecimalFormat::isExponentSignAlwaysShown() {
2825     return fExponentSignAlwaysShown;
2826 }
2827 
2828 /**
2829  * Set whether the exponent sign is always shown.  This has no effect
2830  * unless scientific notation is in use.
2831  * @param expSignAlways TRUE if the exponent is always prefixed with either
2832  * the localized minus sign or the localized plus sign, false if only
2833  * negative exponents are prefixed with the localized minus sign.
2834  * @see #setScientificNotation
2835  * @see #isScientificNotation
2836  * @see #setMinimumExponentDigits
2837  * @see #getMinimumExponentDigits
2838  * @see #isExponentSignAlwaysShown
2839  */
setExponentSignAlwaysShown(UBool expSignAlways)2840 void DecimalFormat::setExponentSignAlwaysShown(UBool expSignAlways) {
2841     fExponentSignAlwaysShown = expSignAlways;
2842 }
2843 
2844 //------------------------------------------------------------------------------
2845 // Gets the grouping size of the number pattern.  For example, thousand or 10
2846 // thousand groupings.
2847 
2848 int32_t
getGroupingSize() const2849 DecimalFormat::getGroupingSize() const
2850 {
2851     return fGroupingSize;
2852 }
2853 
2854 //------------------------------------------------------------------------------
2855 // Gets the grouping size of the number pattern.
2856 
2857 void
setGroupingSize(int32_t newValue)2858 DecimalFormat::setGroupingSize(int32_t newValue)
2859 {
2860     fGroupingSize = newValue;
2861 }
2862 
2863 //------------------------------------------------------------------------------
2864 
2865 int32_t
getSecondaryGroupingSize() const2866 DecimalFormat::getSecondaryGroupingSize() const
2867 {
2868     return fGroupingSize2;
2869 }
2870 
2871 //------------------------------------------------------------------------------
2872 
2873 void
setSecondaryGroupingSize(int32_t newValue)2874 DecimalFormat::setSecondaryGroupingSize(int32_t newValue)
2875 {
2876     fGroupingSize2 = newValue;
2877 }
2878 
2879 //------------------------------------------------------------------------------
2880 // Checks if to show the decimal separator.
2881 
2882 UBool
isDecimalSeparatorAlwaysShown() const2883 DecimalFormat::isDecimalSeparatorAlwaysShown() const
2884 {
2885     return fDecimalSeparatorAlwaysShown;
2886 }
2887 
2888 //------------------------------------------------------------------------------
2889 // Sets to always show the decimal separator.
2890 
2891 void
setDecimalSeparatorAlwaysShown(UBool newValue)2892 DecimalFormat::setDecimalSeparatorAlwaysShown(UBool newValue)
2893 {
2894     fDecimalSeparatorAlwaysShown = newValue;
2895 }
2896 
2897 //------------------------------------------------------------------------------
2898 // Emits the pattern of this DecimalFormat instance.
2899 
2900 UnicodeString&
toPattern(UnicodeString & result) const2901 DecimalFormat::toPattern(UnicodeString& result) const
2902 {
2903     return toPattern(result, FALSE);
2904 }
2905 
2906 //------------------------------------------------------------------------------
2907 // Emits the localized pattern this DecimalFormat instance.
2908 
2909 UnicodeString&
toLocalizedPattern(UnicodeString & result) const2910 DecimalFormat::toLocalizedPattern(UnicodeString& result) const
2911 {
2912     return toPattern(result, TRUE);
2913 }
2914 
2915 //------------------------------------------------------------------------------
2916 /**
2917  * Expand the affix pattern strings into the expanded affix strings.  If any
2918  * affix pattern string is null, do not expand it.  This method should be
2919  * called any time the symbols or the affix patterns change in order to keep
2920  * the expanded affix strings up to date.
2921  * This method also will be called before formatting if format currency
2922  * plural names, since the plural name is not a static one, it is
2923  * based on the currency plural count, the affix will be known only
2924  * after the currency plural count is know.
2925  * In which case, the parameter
2926  * 'pluralCount' will be a non-null currency plural count.
2927  * In all other cases, the 'pluralCount' is null, which means it is not needed.
2928  */
expandAffixes(const UnicodeString * pluralCount)2929 void DecimalFormat::expandAffixes(const UnicodeString* pluralCount) {
2930     FieldPositionHandler none;
2931     if (fPosPrefixPattern != 0) {
2932       expandAffix(*fPosPrefixPattern, fPositivePrefix, 0, none, FALSE, pluralCount);
2933     }
2934     if (fPosSuffixPattern != 0) {
2935       expandAffix(*fPosSuffixPattern, fPositiveSuffix, 0, none, FALSE, pluralCount);
2936     }
2937     if (fNegPrefixPattern != 0) {
2938       expandAffix(*fNegPrefixPattern, fNegativePrefix, 0, none, FALSE, pluralCount);
2939     }
2940     if (fNegSuffixPattern != 0) {
2941       expandAffix(*fNegSuffixPattern, fNegativeSuffix, 0, none, FALSE, pluralCount);
2942     }
2943 #ifdef FMT_DEBUG
2944     UnicodeString s;
2945     s.append("[")
2946         .append(*fPosPrefixPattern).append("|").append(*fPosSuffixPattern)
2947         .append(";") .append(*fNegPrefixPattern).append("|").append(*fNegSuffixPattern)
2948         .append("]->[")
2949         .append(fPositivePrefix).append("|").append(fPositiveSuffix)
2950         .append(";") .append(fNegativePrefix).append("|").append(fNegativeSuffix)
2951         .append("]\n");
2952     debugout(s);
2953 #endif
2954 }
2955 
2956 /**
2957  * Expand an affix pattern into an affix string.  All characters in the
2958  * pattern are literal unless prefixed by kQuote.  The following characters
2959  * after kQuote are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE,
2960  * PATTERN_MINUS, and kCurrencySign.  If kCurrencySign is doubled (kQuote +
2961  * kCurrencySign + kCurrencySign), it is interpreted as an international
2962  * currency sign. If CURRENCY_SIGN is tripled, it is interpreted as
2963  * currency plural long names, such as "US Dollars".
2964  * Any other character after a kQuote represents itself.
2965  * kQuote must be followed by another character; kQuote may not occur by
2966  * itself at the end of the pattern.
2967  *
2968  * This method is used in two distinct ways.  First, it is used to expand
2969  * the stored affix patterns into actual affixes.  For this usage, doFormat
2970  * must be false.  Second, it is used to expand the stored affix patterns
2971  * given a specific number (doFormat == true), for those rare cases in
2972  * which a currency format references a ChoiceFormat (e.g., en_IN display
2973  * name for INR).  The number itself is taken from digitList.
2974  *
2975  * When used in the first way, this method has a side effect: It sets
2976  * currencyChoice to a ChoiceFormat object, if the currency's display name
2977  * in this locale is a ChoiceFormat pattern (very rare).  It only does this
2978  * if currencyChoice is null to start with.
2979  *
2980  * @param pattern the non-null, fPossibly empty pattern
2981  * @param affix string to receive the expanded equivalent of pattern.
2982  * Previous contents are deleted.
2983  * @param doFormat if false, then the pattern will be expanded, and if a
2984  * currency symbol is encountered that expands to a ChoiceFormat, the
2985  * currencyChoice member variable will be initialized if it is null.  If
2986  * doFormat is true, then it is assumed that the currencyChoice has been
2987  * created, and it will be used to format the value in digitList.
2988  * @param pluralCount the plural count. It is only used for currency
2989  *                    plural format. In which case, it is the plural
2990  *                    count of the currency amount. For example,
2991  *                    in en_US, it is the singular "one", or the plural
2992  *                    "other". For all other cases, it is null, and
2993  *                    is not being used.
2994  */
expandAffix(const UnicodeString & pattern,UnicodeString & affix,double number,FieldPositionHandler & handler,UBool doFormat,const UnicodeString * pluralCount) const2995 void DecimalFormat::expandAffix(const UnicodeString& pattern,
2996                                 UnicodeString& affix,
2997                                 double number,
2998                                 FieldPositionHandler& handler,
2999                                 UBool doFormat,
3000                                 const UnicodeString* pluralCount) const {
3001     affix.remove();
3002     for (int i=0; i<pattern.length(); ) {
3003         UChar32 c = pattern.char32At(i);
3004         i += U16_LENGTH(c);
3005         if (c == kQuote) {
3006             c = pattern.char32At(i);
3007             i += U16_LENGTH(c);
3008             int beginIdx = affix.length();
3009             switch (c) {
3010             case kCurrencySign: {
3011                 // As of ICU 2.2 we use the currency object, and
3012                 // ignore the currency symbols in the DFS, unless
3013                 // we have a null currency object.  This occurs if
3014                 // resurrecting a pre-2.2 object or if the user
3015                 // sets a custom DFS.
3016                 UBool intl = i<pattern.length() &&
3017                     pattern.char32At(i) == kCurrencySign;
3018                 UBool plural = FALSE;
3019                 if (intl) {
3020                     ++i;
3021                     plural = i<pattern.length() &&
3022                         pattern.char32At(i) == kCurrencySign;
3023                     if (plural) {
3024                         intl = FALSE;
3025                         ++i;
3026                     }
3027                 }
3028                 const UChar* currencyUChars = getCurrency();
3029                 if (currencyUChars[0] != 0) {
3030                     UErrorCode ec = U_ZERO_ERROR;
3031                     if (plural && pluralCount != NULL) {
3032                         // plural name is only needed when pluralCount != null,
3033                         // which means when formatting currency plural names.
3034                         // For other cases, pluralCount == null,
3035                         // and plural names are not needed.
3036                         int32_t len;
3037                         // TODO: num of char in plural count
3038                         char pluralCountChar[10];
3039                         if (pluralCount->length() >= 10) {
3040                             break;
3041                         }
3042                         pluralCount->extract(0, pluralCount->length(), pluralCountChar);
3043                         UBool isChoiceFormat;
3044                         const UChar* s = ucurr_getPluralName(currencyUChars,
3045                             fSymbols != NULL ? fSymbols->getLocale().getName() :
3046                             Locale::getDefault().getName(), &isChoiceFormat,
3047                             pluralCountChar, &len, &ec);
3048                         affix += UnicodeString(s, len);
3049                         handler.addAttribute(kCurrencyField, beginIdx, affix.length());
3050                     } else if(intl) {
3051                         affix += currencyUChars;
3052                         handler.addAttribute(kCurrencyField, beginIdx, affix.length());
3053                     } else {
3054                         int32_t len;
3055                         UBool isChoiceFormat;
3056                         // If fSymbols is NULL, use default locale
3057                         const UChar* s = ucurr_getName(currencyUChars,
3058                             fSymbols != NULL ? fSymbols->getLocale().getName() : Locale::getDefault().getName(),
3059                             UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec);
3060                         if (isChoiceFormat) {
3061                             // Two modes here: If doFormat is false, we set up
3062                             // currencyChoice.  If doFormat is true, we use the
3063                             // previously created currencyChoice to format the
3064                             // value in digitList.
3065                             if (!doFormat) {
3066                                 // If the currency is handled by a ChoiceFormat,
3067                                 // then we're not going to use the expanded
3068                                 // patterns.  Instantiate the ChoiceFormat and
3069                                 // return.
3070                                 if (fCurrencyChoice == NULL) {
3071                                     // TODO Replace double-check with proper thread-safe code
3072                                     ChoiceFormat* fmt = new ChoiceFormat(s, ec);
3073                                     if (U_SUCCESS(ec)) {
3074                                         umtx_lock(NULL);
3075                                         if (fCurrencyChoice == NULL) {
3076                                             // Cast away const
3077                                             ((DecimalFormat*)this)->fCurrencyChoice = fmt;
3078                                             fmt = NULL;
3079                                         }
3080                                         umtx_unlock(NULL);
3081                                         delete fmt;
3082                                     }
3083                                 }
3084                                 // We could almost return null or "" here, since the
3085                                 // expanded affixes are almost not used at all
3086                                 // in this situation.  However, one method --
3087                                 // toPattern() -- still does use the expanded
3088                                 // affixes, in order to set up a padding
3089                                 // pattern.  We use the CURRENCY_SIGN as a
3090                                 // placeholder.
3091                                 affix.append(kCurrencySign);
3092                             } else {
3093                                 if (fCurrencyChoice != NULL) {
3094                                     FieldPosition pos(0); // ignored
3095                                     if (number < 0) {
3096                                         number = -number;
3097                                     }
3098                                     fCurrencyChoice->format(number, affix, pos);
3099                                 } else {
3100                                     // We only arrive here if the currency choice
3101                                     // format in the locale data is INVALID.
3102                                     affix += currencyUChars;
3103                                     handler.addAttribute(kCurrencyField, beginIdx, affix.length());
3104                                 }
3105                             }
3106                             continue;
3107                         }
3108                         affix += UnicodeString(s, len);
3109                         handler.addAttribute(kCurrencyField, beginIdx, affix.length());
3110                     }
3111                 } else {
3112                     if(intl) {
3113                         affix += getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol);
3114                     } else {
3115                         affix += getConstSymbol(DecimalFormatSymbols::kCurrencySymbol);
3116                     }
3117                     handler.addAttribute(kCurrencyField, beginIdx, affix.length());
3118                 }
3119                 break;
3120             }
3121             case kPatternPercent:
3122                 affix += getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
3123                 handler.addAttribute(kPercentField, beginIdx, affix.length());
3124                 break;
3125             case kPatternPerMill:
3126                 affix += getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
3127                 handler.addAttribute(kPermillField, beginIdx, affix.length());
3128                 break;
3129             case kPatternPlus:
3130                 affix += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
3131                 handler.addAttribute(kSignField, beginIdx, affix.length());
3132                 break;
3133             case kPatternMinus:
3134                 affix += getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
3135                 handler.addAttribute(kSignField, beginIdx, affix.length());
3136                 break;
3137             default:
3138                 affix.append(c);
3139                 break;
3140             }
3141         }
3142         else {
3143             affix.append(c);
3144         }
3145     }
3146 }
3147 
3148 /**
3149  * Append an affix to the given StringBuffer.
3150  * @param buf buffer to append to
3151  * @param isNegative
3152  * @param isPrefix
3153  */
appendAffix(UnicodeString & buf,double number,FieldPositionHandler & handler,UBool isNegative,UBool isPrefix) const3154 int32_t DecimalFormat::appendAffix(UnicodeString& buf, double number,
3155                                    FieldPositionHandler& handler,
3156                                    UBool isNegative, UBool isPrefix) const {
3157     // plural format precedes choice format
3158     if (fCurrencyChoice != 0 &&
3159         fCurrencySignCount != fgCurrencySignCountInPluralFormat) {
3160         const UnicodeString* affixPat;
3161         if (isPrefix) {
3162             affixPat = isNegative ? fNegPrefixPattern : fPosPrefixPattern;
3163         } else {
3164             affixPat = isNegative ? fNegSuffixPattern : fPosSuffixPattern;
3165         }
3166         if (affixPat) {
3167             UnicodeString affixBuf;
3168             expandAffix(*affixPat, affixBuf, number, handler, TRUE, NULL);
3169             buf.append(affixBuf);
3170             return affixBuf.length();
3171         }
3172         // else someone called a function that reset the pattern.
3173     }
3174 
3175     const UnicodeString* affix;
3176     if (fCurrencySignCount == fgCurrencySignCountInPluralFormat) {
3177         UnicodeString pluralCount = fCurrencyPluralInfo->getPluralRules()->select(number);
3178         AffixesForCurrency* oneSet;
3179         if (fStyle == NumberFormat::kPluralCurrencyStyle) {
3180             oneSet = (AffixesForCurrency*)fPluralAffixesForCurrency->get(pluralCount);
3181         } else {
3182             oneSet = (AffixesForCurrency*)fAffixesForCurrency->get(pluralCount);
3183         }
3184         if (isPrefix) {
3185             affix = isNegative ? &oneSet->negPrefixForCurrency :
3186                                  &oneSet->posPrefixForCurrency;
3187         } else {
3188             affix = isNegative ? &oneSet->negSuffixForCurrency :
3189                                  &oneSet->posSuffixForCurrency;
3190         }
3191     } else {
3192         if (isPrefix) {
3193             affix = isNegative ? &fNegativePrefix : &fPositivePrefix;
3194         } else {
3195             affix = isNegative ? &fNegativeSuffix : &fPositiveSuffix;
3196         }
3197     }
3198 
3199     int32_t begin = (int) buf.length();
3200 
3201     buf.append(*affix);
3202 
3203     if (handler.isRecording()) {
3204       int32_t offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kCurrencySymbol));
3205       if (offset > -1) {
3206         UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kCurrencySymbol);
3207         handler.addAttribute(kCurrencyField, begin + offset, begin + offset + aff.length());
3208       }
3209 
3210       offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol));
3211       if (offset > -1) {
3212         UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol);
3213         handler.addAttribute(kCurrencyField, begin + offset, begin + offset + aff.length());
3214       }
3215 
3216       offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol));
3217       if (offset > -1) {
3218         UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
3219         handler.addAttribute(kSignField, begin + offset, begin + offset + aff.length());
3220       }
3221 
3222       offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kPercentSymbol));
3223       if (offset > -1) {
3224         UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
3225         handler.addAttribute(kPercentField, begin + offset, begin + offset + aff.length());
3226       }
3227 
3228       offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kPerMillSymbol));
3229       if (offset > -1) {
3230         UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
3231         handler.addAttribute(kPermillField, begin + offset, begin + offset + aff.length());
3232       }
3233     }
3234     return affix->length();
3235 }
3236 
3237 /**
3238  * Appends an affix pattern to the given StringBuffer, quoting special
3239  * characters as needed.  Uses the internal affix pattern, if that exists,
3240  * or the literal affix, if the internal affix pattern is null.  The
3241  * appended string will generate the same affix pattern (or literal affix)
3242  * when passed to toPattern().
3243  *
3244  * @param appendTo the affix string is appended to this
3245  * @param affixPattern a pattern such as fPosPrefixPattern; may be null
3246  * @param expAffix a corresponding expanded affix, such as fPositivePrefix.
3247  * Ignored unless affixPattern is null.  If affixPattern is null, then
3248  * expAffix is appended as a literal affix.
3249  * @param localized true if the appended pattern should contain localized
3250  * pattern characters; otherwise, non-localized pattern chars are appended
3251  */
appendAffixPattern(UnicodeString & appendTo,const UnicodeString * affixPattern,const UnicodeString & expAffix,UBool localized) const3252 void DecimalFormat::appendAffixPattern(UnicodeString& appendTo,
3253                                        const UnicodeString* affixPattern,
3254                                        const UnicodeString& expAffix,
3255                                        UBool localized) const {
3256     if (affixPattern == 0) {
3257         appendAffixPattern(appendTo, expAffix, localized);
3258     } else {
3259         int i;
3260         for (int pos=0; pos<affixPattern->length(); pos=i) {
3261             i = affixPattern->indexOf(kQuote, pos);
3262             if (i < 0) {
3263                 UnicodeString s;
3264                 affixPattern->extractBetween(pos, affixPattern->length(), s);
3265                 appendAffixPattern(appendTo, s, localized);
3266                 break;
3267             }
3268             if (i > pos) {
3269                 UnicodeString s;
3270                 affixPattern->extractBetween(pos, i, s);
3271                 appendAffixPattern(appendTo, s, localized);
3272             }
3273             UChar32 c = affixPattern->char32At(++i);
3274             ++i;
3275             if (c == kQuote) {
3276                 appendTo.append(c).append(c);
3277                 // Fall through and append another kQuote below
3278             } else if (c == kCurrencySign &&
3279                        i<affixPattern->length() &&
3280                        affixPattern->char32At(i) == kCurrencySign) {
3281                 ++i;
3282                 appendTo.append(c).append(c);
3283             } else if (localized) {
3284                 switch (c) {
3285                 case kPatternPercent:
3286                     appendTo += getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
3287                     break;
3288                 case kPatternPerMill:
3289                     appendTo += getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
3290                     break;
3291                 case kPatternPlus:
3292                     appendTo += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
3293                     break;
3294                 case kPatternMinus:
3295                     appendTo += getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
3296                     break;
3297                 default:
3298                     appendTo.append(c);
3299                 }
3300             } else {
3301                 appendTo.append(c);
3302             }
3303         }
3304     }
3305 }
3306 
3307 /**
3308  * Append an affix to the given StringBuffer, using quotes if
3309  * there are special characters.  Single quotes themselves must be
3310  * escaped in either case.
3311  */
3312 void
appendAffixPattern(UnicodeString & appendTo,const UnicodeString & affix,UBool localized) const3313 DecimalFormat::appendAffixPattern(UnicodeString& appendTo,
3314                                   const UnicodeString& affix,
3315                                   UBool localized) const {
3316     UBool needQuote;
3317     if(localized) {
3318         needQuote = affix.indexOf(getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol)) >= 0
3319             || affix.indexOf(getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol)) >= 0
3320             || affix.indexOf(getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol)) >= 0
3321             || affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPercentSymbol)) >= 0
3322             || affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPerMillSymbol)) >= 0
3323             || affix.indexOf(getConstSymbol(DecimalFormatSymbols::kDigitSymbol)) >= 0
3324             || affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol)) >= 0
3325             || affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol)) >= 0
3326             || affix.indexOf(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol)) >= 0
3327             || affix.indexOf(kCurrencySign) >= 0;
3328     }
3329     else {
3330         needQuote = affix.indexOf(kPatternZeroDigit) >= 0
3331             || affix.indexOf(kPatternGroupingSeparator) >= 0
3332             || affix.indexOf(kPatternDecimalSeparator) >= 0
3333             || affix.indexOf(kPatternPercent) >= 0
3334             || affix.indexOf(kPatternPerMill) >= 0
3335             || affix.indexOf(kPatternDigit) >= 0
3336             || affix.indexOf(kPatternSeparator) >= 0
3337             || affix.indexOf(kPatternExponent) >= 0
3338             || affix.indexOf(kPatternPlus) >= 0
3339             || affix.indexOf(kPatternMinus) >= 0
3340             || affix.indexOf(kCurrencySign) >= 0;
3341     }
3342     if (needQuote)
3343         appendTo += (UChar)0x0027 /*'\''*/;
3344     if (affix.indexOf((UChar)0x0027 /*'\''*/) < 0)
3345         appendTo += affix;
3346     else {
3347         for (int32_t j = 0; j < affix.length(); ) {
3348             UChar32 c = affix.char32At(j);
3349             j += U16_LENGTH(c);
3350             appendTo += c;
3351             if (c == 0x0027 /*'\''*/)
3352                 appendTo += c;
3353         }
3354     }
3355     if (needQuote)
3356         appendTo += (UChar)0x0027 /*'\''*/;
3357 }
3358 
3359 //------------------------------------------------------------------------------
3360 
3361 UnicodeString&
toPattern(UnicodeString & result,UBool localized) const3362 DecimalFormat::toPattern(UnicodeString& result, UBool localized) const
3363 {
3364     if (fStyle == NumberFormat::kPluralCurrencyStyle) {
3365         // the prefix or suffix pattern might not be defined yet,
3366         // so they can not be synthesized,
3367         // instead, get them directly.
3368         // but it might not be the actual pattern used in formatting.
3369         // the actual pattern used in formatting depends on the
3370         // formatted number's plural count.
3371         result = fFormatPattern;
3372         return result;
3373     }
3374     result.remove();
3375     UChar32 zero, sigDigit = kPatternSignificantDigit;
3376     UnicodeString digit, group;
3377     int32_t i;
3378     int32_t roundingDecimalPos = 0; // Pos of decimal in roundingDigits
3379     UnicodeString roundingDigits;
3380     int32_t padPos = (fFormatWidth > 0) ? fPadPosition : -1;
3381     UnicodeString padSpec;
3382     UBool useSigDig = areSignificantDigitsUsed();
3383 
3384     if (localized) {
3385         digit.append(getConstSymbol(DecimalFormatSymbols::kDigitSymbol));
3386         group.append(getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol));
3387         zero = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
3388         if (useSigDig) {
3389             sigDigit = getConstSymbol(DecimalFormatSymbols::kSignificantDigitSymbol).char32At(0);
3390         }
3391     }
3392     else {
3393         digit.append((UChar)kPatternDigit);
3394         group.append((UChar)kPatternGroupingSeparator);
3395         zero = (UChar32)kPatternZeroDigit;
3396     }
3397     if (fFormatWidth > 0) {
3398         if (localized) {
3399             padSpec.append(getConstSymbol(DecimalFormatSymbols::kPadEscapeSymbol));
3400         }
3401         else {
3402             padSpec.append((UChar)kPatternPadEscape);
3403         }
3404         padSpec.append(fPad);
3405     }
3406     if (fRoundingIncrement != NULL) {
3407         for(i=0; i<fRoundingIncrement->getCount(); ++i) {
3408             roundingDigits.append((UChar)fRoundingIncrement->getDigit(i));
3409         }
3410         roundingDecimalPos = fRoundingIncrement->getDecimalAt();
3411     }
3412     for (int32_t part=0; part<2; ++part) {
3413         if (padPos == kPadBeforePrefix) {
3414             result.append(padSpec);
3415         }
3416         appendAffixPattern(result,
3417                     (part==0 ? fPosPrefixPattern : fNegPrefixPattern),
3418                     (part==0 ? fPositivePrefix : fNegativePrefix),
3419                     localized);
3420         if (padPos == kPadAfterPrefix && ! padSpec.isEmpty()) {
3421             result.append(padSpec);
3422         }
3423         int32_t sub0Start = result.length();
3424         int32_t g = isGroupingUsed() ? _max(0, fGroupingSize) : 0;
3425         if (g > 0 && fGroupingSize2 > 0 && fGroupingSize2 != fGroupingSize) {
3426             g += fGroupingSize2;
3427         }
3428         int32_t maxDig = 0, minDig = 0, maxSigDig = 0;
3429         if (useSigDig) {
3430             minDig = getMinimumSignificantDigits();
3431             maxDig = maxSigDig = getMaximumSignificantDigits();
3432         } else {
3433             minDig = getMinimumIntegerDigits();
3434             maxDig = getMaximumIntegerDigits();
3435         }
3436         if (fUseExponentialNotation) {
3437             if (maxDig > kMaxScientificIntegerDigits) {
3438                 maxDig = 1;
3439             }
3440         } else if (useSigDig) {
3441             maxDig = _max(maxDig, g+1);
3442         } else {
3443             maxDig = _max(_max(g, getMinimumIntegerDigits()),
3444                           roundingDecimalPos) + 1;
3445         }
3446         for (i = maxDig; i > 0; --i) {
3447             if (!fUseExponentialNotation && i<maxDig &&
3448                 isGroupingPosition(i)) {
3449                 result.append(group);
3450             }
3451             if (useSigDig) {
3452                 //  #@,@###   (maxSigDig == 5, minSigDig == 2)
3453                 //  65 4321   (1-based pos, count from the right)
3454                 // Use # if pos > maxSigDig or 1 <= pos <= (maxSigDig - minSigDig)
3455                 // Use @ if (maxSigDig - minSigDig) < pos <= maxSigDig
3456                 if (maxSigDig >= i && i > (maxSigDig - minDig)) {
3457                     result.append(sigDigit);
3458                 } else {
3459                     result.append(digit);
3460                 }
3461             } else {
3462                 if (! roundingDigits.isEmpty()) {
3463                     int32_t pos = roundingDecimalPos - i;
3464                     if (pos >= 0 && pos < roundingDigits.length()) {
3465                         result.append((UChar) (roundingDigits.char32At(pos) - kPatternZeroDigit + zero));
3466                         continue;
3467                     }
3468                 }
3469                 if (i<=minDig) {
3470                     result.append(zero);
3471                 } else {
3472                     result.append(digit);
3473                 }
3474             }
3475         }
3476         if (!useSigDig) {
3477             if (getMaximumFractionDigits() > 0 || fDecimalSeparatorAlwaysShown) {
3478                 if (localized) {
3479                     result += getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
3480                 }
3481                 else {
3482                     result.append((UChar)kPatternDecimalSeparator);
3483                 }
3484             }
3485             int32_t pos = roundingDecimalPos;
3486             for (i = 0; i < getMaximumFractionDigits(); ++i) {
3487                 if (! roundingDigits.isEmpty() && pos < roundingDigits.length()) {
3488                     if (pos < 0) {
3489                         result.append(zero);
3490                     }
3491                     else {
3492                         result.append((UChar)(roundingDigits.char32At(pos) - kPatternZeroDigit + zero));
3493                     }
3494                     ++pos;
3495                     continue;
3496                 }
3497                 if (i<getMinimumFractionDigits()) {
3498                     result.append(zero);
3499                 }
3500                 else {
3501                     result.append(digit);
3502                 }
3503             }
3504         }
3505         if (fUseExponentialNotation) {
3506             if (localized) {
3507                 result += getConstSymbol(DecimalFormatSymbols::kExponentialSymbol);
3508             }
3509             else {
3510                 result.append((UChar)kPatternExponent);
3511             }
3512             if (fExponentSignAlwaysShown) {
3513                 if (localized) {
3514                     result += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
3515                 }
3516                 else {
3517                     result.append((UChar)kPatternPlus);
3518                 }
3519             }
3520             for (i=0; i<fMinExponentDigits; ++i) {
3521                 result.append(zero);
3522             }
3523         }
3524         if (! padSpec.isEmpty() && !fUseExponentialNotation) {
3525             int32_t add = fFormatWidth - result.length() + sub0Start
3526                 - ((part == 0)
3527                    ? fPositivePrefix.length() + fPositiveSuffix.length()
3528                    : fNegativePrefix.length() + fNegativeSuffix.length());
3529             while (add > 0) {
3530                 result.insert(sub0Start, digit);
3531                 ++maxDig;
3532                 --add;
3533                 // Only add a grouping separator if we have at least
3534                 // 2 additional characters to be added, so we don't
3535                 // end up with ",###".
3536                 if (add>1 && isGroupingPosition(maxDig)) {
3537                     result.insert(sub0Start, group);
3538                     --add;
3539                 }
3540             }
3541         }
3542         if (fPadPosition == kPadBeforeSuffix && ! padSpec.isEmpty()) {
3543             result.append(padSpec);
3544         }
3545         if (part == 0) {
3546             appendAffixPattern(result, fPosSuffixPattern, fPositiveSuffix, localized);
3547             if (fPadPosition == kPadAfterSuffix && ! padSpec.isEmpty()) {
3548                 result.append(padSpec);
3549             }
3550             UBool isDefault = FALSE;
3551             if ((fNegSuffixPattern == fPosSuffixPattern && // both null
3552                  fNegativeSuffix == fPositiveSuffix)
3553                 || (fNegSuffixPattern != 0 && fPosSuffixPattern != 0 &&
3554                     *fNegSuffixPattern == *fPosSuffixPattern))
3555             {
3556                 if (fNegPrefixPattern != NULL && fPosPrefixPattern != NULL)
3557                 {
3558                     int32_t length = fPosPrefixPattern->length();
3559                     isDefault = fNegPrefixPattern->length() == (length+2) &&
3560                         (*fNegPrefixPattern)[(int32_t)0] == kQuote &&
3561                         (*fNegPrefixPattern)[(int32_t)1] == kPatternMinus &&
3562                         fNegPrefixPattern->compare(2, length, *fPosPrefixPattern, 0, length) == 0;
3563                 }
3564                 if (!isDefault &&
3565                     fNegPrefixPattern == NULL && fPosPrefixPattern == NULL)
3566                 {
3567                     int32_t length = fPositivePrefix.length();
3568                     isDefault = fNegativePrefix.length() == (length+1) &&
3569                         fNegativePrefix.compare(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol)) == 0 &&
3570                         fNegativePrefix.compare(1, length, fPositivePrefix, 0, length) == 0;
3571                 }
3572             }
3573             if (isDefault) {
3574                 break; // Don't output default negative subpattern
3575             } else {
3576                 if (localized) {
3577                     result += getConstSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol);
3578                 }
3579                 else {
3580                     result.append((UChar)kPatternSeparator);
3581                 }
3582             }
3583         } else {
3584             appendAffixPattern(result, fNegSuffixPattern, fNegativeSuffix, localized);
3585             if (fPadPosition == kPadAfterSuffix && ! padSpec.isEmpty()) {
3586                 result.append(padSpec);
3587             }
3588         }
3589     }
3590 
3591     return result;
3592 }
3593 
3594 //------------------------------------------------------------------------------
3595 
3596 void
applyPattern(const UnicodeString & pattern,UErrorCode & status)3597 DecimalFormat::applyPattern(const UnicodeString& pattern, UErrorCode& status)
3598 {
3599     UParseError parseError;
3600     applyPattern(pattern, FALSE, parseError, status);
3601 }
3602 
3603 //------------------------------------------------------------------------------
3604 
3605 void
applyPattern(const UnicodeString & pattern,UParseError & parseError,UErrorCode & status)3606 DecimalFormat::applyPattern(const UnicodeString& pattern,
3607                             UParseError& parseError,
3608                             UErrorCode& status)
3609 {
3610     applyPattern(pattern, FALSE, parseError, status);
3611 }
3612 //------------------------------------------------------------------------------
3613 
3614 void
applyLocalizedPattern(const UnicodeString & pattern,UErrorCode & status)3615 DecimalFormat::applyLocalizedPattern(const UnicodeString& pattern, UErrorCode& status)
3616 {
3617     UParseError parseError;
3618     applyPattern(pattern, TRUE,parseError,status);
3619 }
3620 
3621 //------------------------------------------------------------------------------
3622 
3623 void
applyLocalizedPattern(const UnicodeString & pattern,UParseError & parseError,UErrorCode & status)3624 DecimalFormat::applyLocalizedPattern(const UnicodeString& pattern,
3625                                      UParseError& parseError,
3626                                      UErrorCode& status)
3627 {
3628     applyPattern(pattern, TRUE,parseError,status);
3629 }
3630 
3631 //------------------------------------------------------------------------------
3632 
3633 void
applyPatternWithoutExpandAffix(const UnicodeString & pattern,UBool localized,UParseError & parseError,UErrorCode & status)3634 DecimalFormat::applyPatternWithoutExpandAffix(const UnicodeString& pattern,
3635                                               UBool localized,
3636                                               UParseError& parseError,
3637                                               UErrorCode& status)
3638 {
3639     if (U_FAILURE(status))
3640     {
3641         return;
3642     }
3643     // Clear error struct
3644     parseError.offset = -1;
3645     parseError.preContext[0] = parseError.postContext[0] = (UChar)0;
3646 
3647     // Set the significant pattern symbols
3648     UChar32 zeroDigit               = kPatternZeroDigit; // '0'
3649     UChar32 sigDigit                = kPatternSignificantDigit; // '@'
3650     UnicodeString groupingSeparator ((UChar)kPatternGroupingSeparator);
3651     UnicodeString decimalSeparator  ((UChar)kPatternDecimalSeparator);
3652     UnicodeString percent           ((UChar)kPatternPercent);
3653     UnicodeString perMill           ((UChar)kPatternPerMill);
3654     UnicodeString digit             ((UChar)kPatternDigit); // '#'
3655     UnicodeString separator         ((UChar)kPatternSeparator);
3656     UnicodeString exponent          ((UChar)kPatternExponent);
3657     UnicodeString plus              ((UChar)kPatternPlus);
3658     UnicodeString minus             ((UChar)kPatternMinus);
3659     UnicodeString padEscape         ((UChar)kPatternPadEscape);
3660     // Substitute with the localized symbols if necessary
3661     if (localized) {
3662         zeroDigit = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
3663         sigDigit = getConstSymbol(DecimalFormatSymbols::kSignificantDigitSymbol).char32At(0);
3664         groupingSeparator.  remove().append(getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol));
3665         decimalSeparator.   remove().append(getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol));
3666         percent.            remove().append(getConstSymbol(DecimalFormatSymbols::kPercentSymbol));
3667         perMill.            remove().append(getConstSymbol(DecimalFormatSymbols::kPerMillSymbol));
3668         digit.              remove().append(getConstSymbol(DecimalFormatSymbols::kDigitSymbol));
3669         separator.          remove().append(getConstSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol));
3670         exponent.           remove().append(getConstSymbol(DecimalFormatSymbols::kExponentialSymbol));
3671         plus.               remove().append(getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol));
3672         minus.              remove().append(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol));
3673         padEscape.          remove().append(getConstSymbol(DecimalFormatSymbols::kPadEscapeSymbol));
3674     }
3675     UChar nineDigit = (UChar)(zeroDigit + 9);
3676     int32_t digitLen = digit.length();
3677     int32_t groupSepLen = groupingSeparator.length();
3678     int32_t decimalSepLen = decimalSeparator.length();
3679 
3680     int32_t pos = 0;
3681     int32_t patLen = pattern.length();
3682     // Part 0 is the positive pattern.  Part 1, if present, is the negative
3683     // pattern.
3684     for (int32_t part=0; part<2 && pos<patLen; ++part) {
3685         // The subpart ranges from 0 to 4: 0=pattern proper, 1=prefix,
3686         // 2=suffix, 3=prefix in quote, 4=suffix in quote.  Subpart 0 is
3687         // between the prefix and suffix, and consists of pattern
3688         // characters.  In the prefix and suffix, percent, perMill, and
3689         // currency symbols are recognized and translated.
3690         int32_t subpart = 1, sub0Start = 0, sub0Limit = 0, sub2Limit = 0;
3691 
3692         // It's important that we don't change any fields of this object
3693         // prematurely.  We set the following variables for the multiplier,
3694         // grouping, etc., and then only change the actual object fields if
3695         // everything parses correctly.  This also lets us register
3696         // the data from part 0 and ignore the part 1, except for the
3697         // prefix and suffix.
3698         UnicodeString prefix;
3699         UnicodeString suffix;
3700         int32_t decimalPos = -1;
3701         int32_t multiplier = 1;
3702         int32_t digitLeftCount = 0, zeroDigitCount = 0, digitRightCount = 0, sigDigitCount = 0;
3703         int8_t groupingCount = -1;
3704         int8_t groupingCount2 = -1;
3705         int32_t padPos = -1;
3706         UChar32 padChar = 0;
3707         int32_t roundingPos = -1;
3708         DigitList roundingInc;
3709         int8_t expDigits = -1;
3710         UBool expSignAlways = FALSE;
3711 
3712         // The affix is either the prefix or the suffix.
3713         UnicodeString* affix = &prefix;
3714 
3715         int32_t start = pos;
3716         UBool isPartDone = FALSE;
3717         UChar32 ch;
3718 
3719         for (; !isPartDone && pos < patLen; ) {
3720             // Todo: account for surrogate pairs
3721             ch = pattern.char32At(pos);
3722             switch (subpart) {
3723             case 0: // Pattern proper subpart (between prefix & suffix)
3724                 // Process the digits, decimal, and grouping characters.  We
3725                 // record five pieces of information.  We expect the digits
3726                 // to occur in the pattern ####00.00####, and we record the
3727                 // number of left digits, zero (central) digits, and right
3728                 // digits.  The position of the last grouping character is
3729                 // recorded (should be somewhere within the first two blocks
3730                 // of characters), as is the position of the decimal point,
3731                 // if any (should be in the zero digits).  If there is no
3732                 // decimal point, then there should be no right digits.
3733                 if (pattern.compare(pos, digitLen, digit) == 0) {
3734                     if (zeroDigitCount > 0 || sigDigitCount > 0) {
3735                         ++digitRightCount;
3736                     } else {
3737                         ++digitLeftCount;
3738                     }
3739                     if (groupingCount >= 0 && decimalPos < 0) {
3740                         ++groupingCount;
3741                     }
3742                     pos += digitLen;
3743                 } else if ((ch >= zeroDigit && ch <= nineDigit) ||
3744                            ch == sigDigit) {
3745                     if (digitRightCount > 0) {
3746                         // Unexpected '0'
3747                         debug("Unexpected '0'")
3748                         status = U_UNEXPECTED_TOKEN;
3749                         syntaxError(pattern,pos,parseError);
3750                         return;
3751                     }
3752                     if (ch == sigDigit) {
3753                         ++sigDigitCount;
3754                     } else {
3755                         ++zeroDigitCount;
3756                         if (ch != zeroDigit && roundingPos < 0) {
3757                             roundingPos = digitLeftCount + zeroDigitCount;
3758                         }
3759                         if (roundingPos >= 0) {
3760                             roundingInc.append((char)(ch - zeroDigit + '0'));
3761                         }
3762                     }
3763                     if (groupingCount >= 0 && decimalPos < 0) {
3764                         ++groupingCount;
3765                     }
3766                     pos += U16_LENGTH(ch);
3767                 } else if (pattern.compare(pos, groupSepLen, groupingSeparator) == 0) {
3768                     if (decimalPos >= 0) {
3769                         // Grouping separator after decimal
3770                         debug("Grouping separator after decimal")
3771                         status = U_UNEXPECTED_TOKEN;
3772                         syntaxError(pattern,pos,parseError);
3773                         return;
3774                     }
3775                     groupingCount2 = groupingCount;
3776                     groupingCount = 0;
3777                     pos += groupSepLen;
3778                 } else if (pattern.compare(pos, decimalSepLen, decimalSeparator) == 0) {
3779                     if (decimalPos >= 0) {
3780                         // Multiple decimal separators
3781                         debug("Multiple decimal separators")
3782                         status = U_MULTIPLE_DECIMAL_SEPARATORS;
3783                         syntaxError(pattern,pos,parseError);
3784                         return;
3785                     }
3786                     // Intentionally incorporate the digitRightCount,
3787                     // even though it is illegal for this to be > 0
3788                     // at this point.  We check pattern syntax below.
3789                     decimalPos = digitLeftCount + zeroDigitCount + digitRightCount;
3790                     pos += decimalSepLen;
3791                 } else {
3792                     if (pattern.compare(pos, exponent.length(), exponent) == 0) {
3793                         if (expDigits >= 0) {
3794                             // Multiple exponential symbols
3795                             debug("Multiple exponential symbols")
3796                             status = U_MULTIPLE_EXPONENTIAL_SYMBOLS;
3797                             syntaxError(pattern,pos,parseError);
3798                             return;
3799                         }
3800                         if (groupingCount >= 0) {
3801                             // Grouping separator in exponential pattern
3802                             debug("Grouping separator in exponential pattern")
3803                             status = U_MALFORMED_EXPONENTIAL_PATTERN;
3804                             syntaxError(pattern,pos,parseError);
3805                             return;
3806                         }
3807                         pos += exponent.length();
3808                         // Check for positive prefix
3809                         if (pos < patLen
3810                             && pattern.compare(pos, plus.length(), plus) == 0) {
3811                             expSignAlways = TRUE;
3812                             pos += plus.length();
3813                         }
3814                         // Use lookahead to parse out the exponential part of the
3815                         // pattern, then jump into suffix subpart.
3816                         expDigits = 0;
3817                         while (pos < patLen &&
3818                                pattern.char32At(pos) == zeroDigit) {
3819                             ++expDigits;
3820                             pos += U16_LENGTH(zeroDigit);
3821                         }
3822 
3823                         // 1. Require at least one mantissa pattern digit
3824                         // 2. Disallow "#+ @" in mantissa
3825                         // 3. Require at least one exponent pattern digit
3826                         if (((digitLeftCount + zeroDigitCount) < 1 &&
3827                              (sigDigitCount + digitRightCount) < 1) ||
3828                             (sigDigitCount > 0 && digitLeftCount > 0) ||
3829                             expDigits < 1) {
3830                             // Malformed exponential pattern
3831                             debug("Malformed exponential pattern")
3832                             status = U_MALFORMED_EXPONENTIAL_PATTERN;
3833                             syntaxError(pattern,pos,parseError);
3834                             return;
3835                         }
3836                     }
3837                     // Transition to suffix subpart
3838                     subpart = 2; // suffix subpart
3839                     affix = &suffix;
3840                     sub0Limit = pos;
3841                     continue;
3842                 }
3843                 break;
3844             case 1: // Prefix subpart
3845             case 2: // Suffix subpart
3846                 // Process the prefix / suffix characters
3847                 // Process unquoted characters seen in prefix or suffix
3848                 // subpart.
3849 
3850                 // Several syntax characters implicitly begins the
3851                 // next subpart if we are in the prefix; otherwise
3852                 // they are illegal if unquoted.
3853                 if (!pattern.compare(pos, digitLen, digit) ||
3854                     !pattern.compare(pos, groupSepLen, groupingSeparator) ||
3855                     !pattern.compare(pos, decimalSepLen, decimalSeparator) ||
3856                     (ch >= zeroDigit && ch <= nineDigit) ||
3857                     ch == sigDigit) {
3858                     if (subpart == 1) { // prefix subpart
3859                         subpart = 0; // pattern proper subpart
3860                         sub0Start = pos; // Reprocess this character
3861                         continue;
3862                     } else {
3863                         status = U_UNQUOTED_SPECIAL;
3864                         syntaxError(pattern,pos,parseError);
3865                         return;
3866                     }
3867                 } else if (ch == kCurrencySign) {
3868                     affix->append(kQuote); // Encode currency
3869                     // Use lookahead to determine if the currency sign is
3870                     // doubled or not.
3871                     U_ASSERT(U16_LENGTH(kCurrencySign) == 1);
3872                     if ((pos+1) < pattern.length() && pattern[pos+1] == kCurrencySign) {
3873                         affix->append(kCurrencySign);
3874                         ++pos; // Skip over the doubled character
3875                         if ((pos+1) < pattern.length() &&
3876                             pattern[pos+1] == kCurrencySign) {
3877                             affix->append(kCurrencySign);
3878                             ++pos; // Skip over the doubled character
3879                             fCurrencySignCount = fgCurrencySignCountInPluralFormat;
3880                         } else {
3881                             fCurrencySignCount = fgCurrencySignCountInISOFormat;
3882                         }
3883                     } else {
3884                         fCurrencySignCount = fgCurrencySignCountInSymbolFormat;
3885                     }
3886                     // Fall through to append(ch)
3887                 } else if (ch == kQuote) {
3888                     // A quote outside quotes indicates either the opening
3889                     // quote or two quotes, which is a quote literal.  That is,
3890                     // we have the first quote in 'do' or o''clock.
3891                     U_ASSERT(U16_LENGTH(kQuote) == 1);
3892                     ++pos;
3893                     if (pos < pattern.length() && pattern[pos] == kQuote) {
3894                         affix->append(kQuote); // Encode quote
3895                         // Fall through to append(ch)
3896                     } else {
3897                         subpart += 2; // open quote
3898                         continue;
3899                     }
3900                 } else if (pattern.compare(pos, separator.length(), separator) == 0) {
3901                     // Don't allow separators in the prefix, and don't allow
3902                     // separators in the second pattern (part == 1).
3903                     if (subpart == 1 || part == 1) {
3904                         // Unexpected separator
3905                         debug("Unexpected separator")
3906                         status = U_UNEXPECTED_TOKEN;
3907                         syntaxError(pattern,pos,parseError);
3908                         return;
3909                     }
3910                     sub2Limit = pos;
3911                     isPartDone = TRUE; // Go to next part
3912                     pos += separator.length();
3913                     break;
3914                 } else if (pattern.compare(pos, percent.length(), percent) == 0) {
3915                     // Next handle characters which are appended directly.
3916                     if (multiplier != 1) {
3917                         // Too many percent/perMill characters
3918                         debug("Too many percent characters")
3919                         status = U_MULTIPLE_PERCENT_SYMBOLS;
3920                         syntaxError(pattern,pos,parseError);
3921                         return;
3922                     }
3923                     affix->append(kQuote); // Encode percent/perMill
3924                     affix->append(kPatternPercent); // Use unlocalized pattern char
3925                     multiplier = 100;
3926                     pos += percent.length();
3927                     break;
3928                 } else if (pattern.compare(pos, perMill.length(), perMill) == 0) {
3929                     // Next handle characters which are appended directly.
3930                     if (multiplier != 1) {
3931                         // Too many percent/perMill characters
3932                         debug("Too many perMill characters")
3933                         status = U_MULTIPLE_PERMILL_SYMBOLS;
3934                         syntaxError(pattern,pos,parseError);
3935                         return;
3936                     }
3937                     affix->append(kQuote); // Encode percent/perMill
3938                     affix->append(kPatternPerMill); // Use unlocalized pattern char
3939                     multiplier = 1000;
3940                     pos += perMill.length();
3941                     break;
3942                 } else if (pattern.compare(pos, padEscape.length(), padEscape) == 0) {
3943                     if (padPos >= 0 ||               // Multiple pad specifiers
3944                         (pos+1) == pattern.length()) { // Nothing after padEscape
3945                         debug("Multiple pad specifiers")
3946                         status = U_MULTIPLE_PAD_SPECIFIERS;
3947                         syntaxError(pattern,pos,parseError);
3948                         return;
3949                     }
3950                     padPos = pos;
3951                     pos += padEscape.length();
3952                     padChar = pattern.char32At(pos);
3953                     pos += U16_LENGTH(padChar);
3954                     break;
3955                 } else if (pattern.compare(pos, minus.length(), minus) == 0) {
3956                     affix->append(kQuote); // Encode minus
3957                     affix->append(kPatternMinus);
3958                     pos += minus.length();
3959                     break;
3960                 } else if (pattern.compare(pos, plus.length(), plus) == 0) {
3961                     affix->append(kQuote); // Encode plus
3962                     affix->append(kPatternPlus);
3963                     pos += plus.length();
3964                     break;
3965                 }
3966                 // Unquoted, non-special characters fall through to here, as
3967                 // well as other code which needs to append something to the
3968                 // affix.
3969                 affix->append(ch);
3970                 pos += U16_LENGTH(ch);
3971                 break;
3972             case 3: // Prefix subpart, in quote
3973             case 4: // Suffix subpart, in quote
3974                 // A quote within quotes indicates either the closing
3975                 // quote or two quotes, which is a quote literal.  That is,
3976                 // we have the second quote in 'do' or 'don''t'.
3977                 if (ch == kQuote) {
3978                     ++pos;
3979                     if (pos < pattern.length() && pattern[pos] == kQuote) {
3980                         affix->append(kQuote); // Encode quote
3981                         // Fall through to append(ch)
3982                     } else {
3983                         subpart -= 2; // close quote
3984                         continue;
3985                     }
3986                 }
3987                 affix->append(ch);
3988                 pos += U16_LENGTH(ch);
3989                 break;
3990             }
3991         }
3992 
3993         if (sub0Limit == 0) {
3994             sub0Limit = pattern.length();
3995         }
3996 
3997         if (sub2Limit == 0) {
3998             sub2Limit = pattern.length();
3999         }
4000 
4001         /* Handle patterns with no '0' pattern character.  These patterns
4002          * are legal, but must be recodified to make sense.  "##.###" ->
4003          * "#0.###".  ".###" -> ".0##".
4004          *
4005          * We allow patterns of the form "####" to produce a zeroDigitCount
4006          * of zero (got that?); although this seems like it might make it
4007          * possible for format() to produce empty strings, format() checks
4008          * for this condition and outputs a zero digit in this situation.
4009          * Having a zeroDigitCount of zero yields a minimum integer digits
4010          * of zero, which allows proper round-trip patterns.  We don't want
4011          * "#" to become "#0" when toPattern() is called (even though that's
4012          * what it really is, semantically).
4013          */
4014         if (zeroDigitCount == 0 && sigDigitCount == 0 &&
4015             digitLeftCount > 0 && decimalPos >= 0) {
4016             // Handle "###.###" and "###." and ".###"
4017             int n = decimalPos;
4018             if (n == 0)
4019                 ++n; // Handle ".###"
4020             digitRightCount = digitLeftCount - n;
4021             digitLeftCount = n - 1;
4022             zeroDigitCount = 1;
4023         }
4024 
4025         // Do syntax checking on the digits, decimal points, and quotes.
4026         if ((decimalPos < 0 && digitRightCount > 0 && sigDigitCount == 0) ||
4027             (decimalPos >= 0 &&
4028              (sigDigitCount > 0 ||
4029               decimalPos < digitLeftCount ||
4030               decimalPos > (digitLeftCount + zeroDigitCount))) ||
4031             groupingCount == 0 || groupingCount2 == 0 ||
4032             (sigDigitCount > 0 && zeroDigitCount > 0) ||
4033             subpart > 2)
4034         { // subpart > 2 == unmatched quote
4035             debug("Syntax error")
4036             status = U_PATTERN_SYNTAX_ERROR;
4037             syntaxError(pattern,pos,parseError);
4038             return;
4039         }
4040 
4041         // Make sure pad is at legal position before or after affix.
4042         if (padPos >= 0) {
4043             if (padPos == start) {
4044                 padPos = kPadBeforePrefix;
4045             } else if (padPos+2 == sub0Start) {
4046                 padPos = kPadAfterPrefix;
4047             } else if (padPos == sub0Limit) {
4048                 padPos = kPadBeforeSuffix;
4049             } else if (padPos+2 == sub2Limit) {
4050                 padPos = kPadAfterSuffix;
4051             } else {
4052                 // Illegal pad position
4053                 debug("Illegal pad position")
4054                 status = U_ILLEGAL_PAD_POSITION;
4055                 syntaxError(pattern,pos,parseError);
4056                 return;
4057             }
4058         }
4059 
4060         if (part == 0) {
4061             delete fPosPrefixPattern;
4062             delete fPosSuffixPattern;
4063             delete fNegPrefixPattern;
4064             delete fNegSuffixPattern;
4065             fPosPrefixPattern = new UnicodeString(prefix);
4066             /* test for NULL */
4067             if (fPosPrefixPattern == 0) {
4068                 status = U_MEMORY_ALLOCATION_ERROR;
4069                 return;
4070             }
4071             fPosSuffixPattern = new UnicodeString(suffix);
4072             /* test for NULL */
4073             if (fPosSuffixPattern == 0) {
4074                 status = U_MEMORY_ALLOCATION_ERROR;
4075                 delete fPosPrefixPattern;
4076                 return;
4077             }
4078             fNegPrefixPattern = 0;
4079             fNegSuffixPattern = 0;
4080 
4081             fUseExponentialNotation = (expDigits >= 0);
4082             if (fUseExponentialNotation) {
4083                 fMinExponentDigits = expDigits;
4084             }
4085             fExponentSignAlwaysShown = expSignAlways;
4086             int32_t digitTotalCount = digitLeftCount + zeroDigitCount + digitRightCount;
4087             // The effectiveDecimalPos is the position the decimal is at or
4088             // would be at if there is no decimal.  Note that if
4089             // decimalPos<0, then digitTotalCount == digitLeftCount +
4090             // zeroDigitCount.
4091             int32_t effectiveDecimalPos = decimalPos >= 0 ? decimalPos : digitTotalCount;
4092             UBool isSigDig = (sigDigitCount > 0);
4093             setSignificantDigitsUsed(isSigDig);
4094             if (isSigDig) {
4095                 setMinimumSignificantDigits(sigDigitCount);
4096                 setMaximumSignificantDigits(sigDigitCount + digitRightCount);
4097             } else {
4098                 int32_t minInt = effectiveDecimalPos - digitLeftCount;
4099                 setMinimumIntegerDigits(minInt);
4100                 setMaximumIntegerDigits(fUseExponentialNotation
4101                     ? digitLeftCount + getMinimumIntegerDigits()
4102                     : kDoubleIntegerDigits);
4103                 setMaximumFractionDigits(decimalPos >= 0
4104                     ? (digitTotalCount - decimalPos) : 0);
4105                 setMinimumFractionDigits(decimalPos >= 0
4106                     ? (digitLeftCount + zeroDigitCount - decimalPos) : 0);
4107             }
4108             setGroupingUsed(groupingCount > 0);
4109             fGroupingSize = (groupingCount > 0) ? groupingCount : 0;
4110             fGroupingSize2 = (groupingCount2 > 0 && groupingCount2 != groupingCount)
4111                 ? groupingCount2 : 0;
4112             setMultiplier(multiplier);
4113             setDecimalSeparatorAlwaysShown(decimalPos == 0
4114                     || decimalPos == digitTotalCount);
4115             if (padPos >= 0) {
4116                 fPadPosition = (EPadPosition) padPos;
4117                 // To compute the format width, first set up sub0Limit -
4118                 // sub0Start.  Add in prefix/suffix length later.
4119 
4120                 // fFormatWidth = prefix.length() + suffix.length() +
4121                 //    sub0Limit - sub0Start;
4122                 fFormatWidth = sub0Limit - sub0Start;
4123                 fPad = padChar;
4124             } else {
4125                 fFormatWidth = 0;
4126             }
4127             if (roundingPos >= 0) {
4128                 roundingInc.setDecimalAt(effectiveDecimalPos - roundingPos);
4129                 if (fRoundingIncrement != NULL) {
4130                     *fRoundingIncrement = roundingInc;
4131                 } else {
4132                     fRoundingIncrement = new DigitList(roundingInc);
4133                     /* test for NULL */
4134                     if (fRoundingIncrement == NULL) {
4135                         status = U_MEMORY_ALLOCATION_ERROR;
4136                         delete fPosPrefixPattern;
4137                         delete fPosSuffixPattern;
4138                         return;
4139                     }
4140                 }
4141                 fRoundingIncrement->getDouble();   // forces caching of double in the DigitList,
4142                                                    //    makes getting it thread safe.
4143                 fRoundingMode = kRoundHalfEven;
4144             } else {
4145                 setRoundingIncrement(0.0);
4146             }
4147         } else {
4148             fNegPrefixPattern = new UnicodeString(prefix);
4149             /* test for NULL */
4150             if (fNegPrefixPattern == 0) {
4151                 status = U_MEMORY_ALLOCATION_ERROR;
4152                 return;
4153             }
4154             fNegSuffixPattern = new UnicodeString(suffix);
4155             /* test for NULL */
4156             if (fNegSuffixPattern == 0) {
4157                 delete fNegPrefixPattern;
4158                 status = U_MEMORY_ALLOCATION_ERROR;
4159                 return;
4160             }
4161         }
4162     }
4163 
4164     if (pattern.length() == 0) {
4165         delete fNegPrefixPattern;
4166         delete fNegSuffixPattern;
4167         fNegPrefixPattern = NULL;
4168         fNegSuffixPattern = NULL;
4169         if (fPosPrefixPattern != NULL) {
4170             fPosPrefixPattern->remove();
4171         } else {
4172             fPosPrefixPattern = new UnicodeString();
4173             /* test for NULL */
4174             if (fPosPrefixPattern == 0) {
4175                 status = U_MEMORY_ALLOCATION_ERROR;
4176                 return;
4177             }
4178         }
4179         if (fPosSuffixPattern != NULL) {
4180             fPosSuffixPattern->remove();
4181         } else {
4182             fPosSuffixPattern = new UnicodeString();
4183             /* test for NULL */
4184             if (fPosSuffixPattern == 0) {
4185                 delete fPosPrefixPattern;
4186                 status = U_MEMORY_ALLOCATION_ERROR;
4187                 return;
4188             }
4189         }
4190 
4191         setMinimumIntegerDigits(0);
4192         setMaximumIntegerDigits(kDoubleIntegerDigits);
4193         setMinimumFractionDigits(0);
4194         setMaximumFractionDigits(kDoubleFractionDigits);
4195 
4196         fUseExponentialNotation = FALSE;
4197         fCurrencySignCount = 0;
4198         setGroupingUsed(FALSE);
4199         fGroupingSize = 0;
4200         fGroupingSize2 = 0;
4201         setMultiplier(1);
4202         setDecimalSeparatorAlwaysShown(FALSE);
4203         fFormatWidth = 0;
4204         setRoundingIncrement(0.0);
4205     }
4206 
4207     // If there was no negative pattern, or if the negative pattern is
4208     // identical to the positive pattern, then prepend the minus sign to the
4209     // positive pattern to form the negative pattern.
4210     if (fNegPrefixPattern == NULL ||
4211         (*fNegPrefixPattern == *fPosPrefixPattern
4212          && *fNegSuffixPattern == *fPosSuffixPattern)) {
4213         _copy_us_ptr(&fNegSuffixPattern, fPosSuffixPattern);
4214         if (fNegPrefixPattern == NULL) {
4215             fNegPrefixPattern = new UnicodeString();
4216             /* test for NULL */
4217             if (fNegPrefixPattern == 0) {
4218                 status = U_MEMORY_ALLOCATION_ERROR;
4219                 return;
4220             }
4221         } else {
4222             fNegPrefixPattern->remove();
4223         }
4224         fNegPrefixPattern->append(kQuote).append(kPatternMinus)
4225             .append(*fPosPrefixPattern);
4226     }
4227 #ifdef FMT_DEBUG
4228     UnicodeString s;
4229     s.append("\"").append(pattern).append("\"->");
4230     debugout(s);
4231 #endif
4232 
4233     // save the pattern
4234     fFormatPattern = pattern;
4235 }
4236 
4237 
4238 void
expandAffixAdjustWidth(const UnicodeString * pluralCount)4239 DecimalFormat::expandAffixAdjustWidth(const UnicodeString* pluralCount) {
4240     expandAffixes(pluralCount);
4241     if (fFormatWidth > 0) {
4242         // Finish computing format width (see above)
4243             // TODO: how to handle fFormatWidth,
4244             // need to save in f(Plural)AffixesForCurrecy?
4245             fFormatWidth += fPositivePrefix.length() + fPositiveSuffix.length();
4246     }
4247 }
4248 
4249 
4250 void
applyPattern(const UnicodeString & pattern,UBool localized,UParseError & parseError,UErrorCode & status)4251 DecimalFormat::applyPattern(const UnicodeString& pattern,
4252                             UBool localized,
4253                             UParseError& parseError,
4254                             UErrorCode& status)
4255 {
4256     // do the following re-set first. since they change private data by
4257     // apply pattern again.
4258     if (pattern.indexOf(kCurrencySign) != -1) {
4259         if (fCurrencyPluralInfo == NULL) {
4260             // initialize currencyPluralInfo if needed
4261             fCurrencyPluralInfo = new CurrencyPluralInfo(fSymbols->getLocale(), status);
4262         }
4263         if (fAffixPatternsForCurrency == NULL) {
4264             setupCurrencyAffixPatterns(status);
4265         }
4266         if (pattern.indexOf(fgTripleCurrencySign) != -1) {
4267             // only setup the affixes of the current pattern.
4268             setupCurrencyAffixes(pattern, TRUE, FALSE, status);
4269         }
4270     }
4271     applyPatternWithoutExpandAffix(pattern, localized, parseError, status);
4272     expandAffixAdjustWidth(NULL);
4273 }
4274 
4275 
4276 void
applyPatternInternally(const UnicodeString & pluralCount,const UnicodeString & pattern,UBool localized,UParseError & parseError,UErrorCode & status)4277 DecimalFormat::applyPatternInternally(const UnicodeString& pluralCount,
4278                                       const UnicodeString& pattern,
4279                                       UBool localized,
4280                                       UParseError& parseError,
4281                                       UErrorCode& status) {
4282     applyPatternWithoutExpandAffix(pattern, localized, parseError, status);
4283     expandAffixAdjustWidth(&pluralCount);
4284 }
4285 
4286 
4287 /**
4288  * Sets the maximum number of digits allowed in the integer portion of a
4289  * number. This override limits the integer digit count to 309.
4290  * @see NumberFormat#setMaximumIntegerDigits
4291  */
setMaximumIntegerDigits(int32_t newValue)4292 void DecimalFormat::setMaximumIntegerDigits(int32_t newValue) {
4293     NumberFormat::setMaximumIntegerDigits(_min(newValue, kDoubleIntegerDigits));
4294 }
4295 
4296 /**
4297  * Sets the minimum number of digits allowed in the integer portion of a
4298  * number. This override limits the integer digit count to 309.
4299  * @see NumberFormat#setMinimumIntegerDigits
4300  */
setMinimumIntegerDigits(int32_t newValue)4301 void DecimalFormat::setMinimumIntegerDigits(int32_t newValue) {
4302     NumberFormat::setMinimumIntegerDigits(_min(newValue, kDoubleIntegerDigits));
4303 }
4304 
4305 /**
4306  * Sets the maximum number of digits allowed in the fraction portion of a
4307  * number. This override limits the fraction digit count to 340.
4308  * @see NumberFormat#setMaximumFractionDigits
4309  */
setMaximumFractionDigits(int32_t newValue)4310 void DecimalFormat::setMaximumFractionDigits(int32_t newValue) {
4311     NumberFormat::setMaximumFractionDigits(_min(newValue, kDoubleFractionDigits));
4312 }
4313 
4314 /**
4315  * Sets the minimum number of digits allowed in the fraction portion of a
4316  * number. This override limits the fraction digit count to 340.
4317  * @see NumberFormat#setMinimumFractionDigits
4318  */
setMinimumFractionDigits(int32_t newValue)4319 void DecimalFormat::setMinimumFractionDigits(int32_t newValue) {
4320     NumberFormat::setMinimumFractionDigits(_min(newValue, kDoubleFractionDigits));
4321 }
4322 
getMinimumSignificantDigits() const4323 int32_t DecimalFormat::getMinimumSignificantDigits() const {
4324     return fMinSignificantDigits;
4325 }
4326 
getMaximumSignificantDigits() const4327 int32_t DecimalFormat::getMaximumSignificantDigits() const {
4328     return fMaxSignificantDigits;
4329 }
4330 
setMinimumSignificantDigits(int32_t min)4331 void DecimalFormat::setMinimumSignificantDigits(int32_t min) {
4332     if (min < 1) {
4333         min = 1;
4334     }
4335     // pin max sig dig to >= min
4336     int32_t max = _max(fMaxSignificantDigits, min);
4337     fMinSignificantDigits = min;
4338     fMaxSignificantDigits = max;
4339 }
4340 
setMaximumSignificantDigits(int32_t max)4341 void DecimalFormat::setMaximumSignificantDigits(int32_t max) {
4342     if (max < 1) {
4343         max = 1;
4344     }
4345     // pin min sig dig to 1..max
4346     U_ASSERT(fMinSignificantDigits >= 1);
4347     int32_t min = _min(fMinSignificantDigits, max);
4348     fMinSignificantDigits = min;
4349     fMaxSignificantDigits = max;
4350 }
4351 
areSignificantDigitsUsed() const4352 UBool DecimalFormat::areSignificantDigitsUsed() const {
4353     return fUseSignificantDigits;
4354 }
4355 
setSignificantDigitsUsed(UBool useSignificantDigits)4356 void DecimalFormat::setSignificantDigitsUsed(UBool useSignificantDigits) {
4357     fUseSignificantDigits = useSignificantDigits;
4358 }
4359 
setCurrencyInternally(const UChar * theCurrency,UErrorCode & ec)4360 void DecimalFormat::setCurrencyInternally(const UChar* theCurrency,
4361                                           UErrorCode& ec) {
4362     // If we are a currency format, then modify our affixes to
4363     // encode the currency symbol for the given currency in our
4364     // locale, and adjust the decimal digits and rounding for the
4365     // given currency.
4366 
4367     // Note: The code is ordered so that this object is *not changed*
4368     // until we are sure we are going to succeed.
4369 
4370     // NULL or empty currency is *legal* and indicates no currency.
4371     UBool isCurr = (theCurrency && *theCurrency);
4372 
4373     double rounding = 0.0;
4374     int32_t frac = 0;
4375     if (fCurrencySignCount > fgCurrencySignCountZero && isCurr) {
4376         rounding = ucurr_getRoundingIncrement(theCurrency, &ec);
4377         frac = ucurr_getDefaultFractionDigits(theCurrency, &ec);
4378     }
4379 
4380     NumberFormat::setCurrency(theCurrency, ec);
4381     if (U_FAILURE(ec)) return;
4382 
4383     if (fCurrencySignCount > fgCurrencySignCountZero) {
4384         // NULL or empty currency is *legal* and indicates no currency.
4385         if (isCurr) {
4386             setRoundingIncrement(rounding);
4387             setMinimumFractionDigits(frac);
4388             setMaximumFractionDigits(frac);
4389         }
4390         expandAffixes(NULL);
4391     }
4392 }
4393 
setCurrency(const UChar * theCurrency,UErrorCode & ec)4394 void DecimalFormat::setCurrency(const UChar* theCurrency, UErrorCode& ec) {
4395     // set the currency before compute affixes to get the right currency names
4396     NumberFormat::setCurrency(theCurrency, ec);
4397     if (fFormatPattern.indexOf(fgTripleCurrencySign) != -1) {
4398         UnicodeString savedPtn = fFormatPattern;
4399         setupCurrencyAffixes(fFormatPattern, TRUE, TRUE, ec);
4400         UParseError parseErr;
4401         applyPattern(savedPtn, FALSE, parseErr, ec);
4402     }
4403     // set the currency after apply pattern to get the correct rounding/fraction
4404     setCurrencyInternally(theCurrency, ec);
4405 }
4406 
4407 // Deprecated variant with no UErrorCode parameter
setCurrency(const UChar * theCurrency)4408 void DecimalFormat::setCurrency(const UChar* theCurrency) {
4409     UErrorCode ec = U_ZERO_ERROR;
4410     setCurrency(theCurrency, ec);
4411 }
4412 
getEffectiveCurrency(UChar * result,UErrorCode & ec) const4413 void DecimalFormat::getEffectiveCurrency(UChar* result, UErrorCode& ec) const {
4414     if (fSymbols == NULL) {
4415         ec = U_MEMORY_ALLOCATION_ERROR;
4416         return;
4417     }
4418     ec = U_ZERO_ERROR;
4419     const UChar* c = getCurrency();
4420     if (*c == 0) {
4421         const UnicodeString &intl =
4422             fSymbols->getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol);
4423         c = intl.getBuffer(); // ok for intl to go out of scope
4424     }
4425     u_strncpy(result, c, 3);
4426     result[3] = 0;
4427 }
4428 
4429 /**
4430  * Return the number of fraction digits to display, or the total
4431  * number of digits for significant digit formats and exponential
4432  * formats.
4433  */
4434 int32_t
precision() const4435 DecimalFormat::precision() const {
4436     if (areSignificantDigitsUsed()) {
4437         return getMaximumSignificantDigits();
4438     } else if (fUseExponentialNotation) {
4439         return getMinimumIntegerDigits() + getMaximumFractionDigits();
4440     } else {
4441         return getMaximumFractionDigits();
4442     }
4443 }
4444 
4445 
4446 // TODO: template algorithm
4447 Hashtable*
initHashForAffix(UErrorCode & status)4448 DecimalFormat::initHashForAffix(UErrorCode& status) {
4449     if ( U_FAILURE(status) ) {
4450         return NULL;
4451     }
4452     Hashtable* hTable;
4453     if ( (hTable = new Hashtable(TRUE, status)) == NULL ) {
4454         status = U_MEMORY_ALLOCATION_ERROR;
4455         return NULL;
4456     }
4457     hTable->setValueComparator(decimfmtAffixValueComparator);
4458     return hTable;
4459 }
4460 
4461 Hashtable*
initHashForAffixPattern(UErrorCode & status)4462 DecimalFormat::initHashForAffixPattern(UErrorCode& status) {
4463     if ( U_FAILURE(status) ) {
4464         return NULL;
4465     }
4466     Hashtable* hTable;
4467     if ( (hTable = new Hashtable(TRUE, status)) == NULL ) {
4468         status = U_MEMORY_ALLOCATION_ERROR;
4469         return NULL;
4470     }
4471     hTable->setValueComparator(decimfmtAffixPatternValueComparator);
4472     return hTable;
4473 }
4474 
4475 void
deleteHashForAffix(Hashtable * & table)4476 DecimalFormat::deleteHashForAffix(Hashtable*& table)
4477 {
4478     if ( table == NULL ) {
4479         return;
4480     }
4481     int32_t pos = -1;
4482     const UHashElement* element = NULL;
4483     while ( (element = table->nextElement(pos)) != NULL ) {
4484         const UHashTok keyTok = element->key;
4485         const UHashTok valueTok = element->value;
4486         const AffixesForCurrency* value = (AffixesForCurrency*)valueTok.pointer;
4487         delete value;
4488     }
4489     delete table;
4490     table = NULL;
4491 }
4492 
4493 
4494 
4495 void
deleteHashForAffixPattern()4496 DecimalFormat::deleteHashForAffixPattern()
4497 {
4498     if ( fAffixPatternsForCurrency == NULL ) {
4499         return;
4500     }
4501     int32_t pos = -1;
4502     const UHashElement* element = NULL;
4503     while ( (element = fAffixPatternsForCurrency->nextElement(pos)) != NULL ) {
4504         const UHashTok keyTok = element->key;
4505         const UHashTok valueTok = element->value;
4506         const AffixPatternsForCurrency* value = (AffixPatternsForCurrency*)valueTok.pointer;
4507         delete value;
4508     }
4509     delete fAffixPatternsForCurrency;
4510     fAffixPatternsForCurrency = NULL;
4511 }
4512 
4513 
4514 void
copyHashForAffixPattern(const Hashtable * source,Hashtable * target,UErrorCode & status)4515 DecimalFormat::copyHashForAffixPattern(const Hashtable* source,
4516                                        Hashtable* target,
4517                                        UErrorCode& status) {
4518     if ( U_FAILURE(status) ) {
4519         return;
4520     }
4521     int32_t pos = -1;
4522     const UHashElement* element = NULL;
4523     if ( source ) {
4524         while ( (element = source->nextElement(pos)) != NULL ) {
4525             const UHashTok keyTok = element->key;
4526             const UnicodeString* key = (UnicodeString*)keyTok.pointer;
4527             const UHashTok valueTok = element->value;
4528             const AffixPatternsForCurrency* value = (AffixPatternsForCurrency*)valueTok.pointer;
4529             AffixPatternsForCurrency* copy = new AffixPatternsForCurrency(
4530                 value->negPrefixPatternForCurrency,
4531                 value->negSuffixPatternForCurrency,
4532                 value->posPrefixPatternForCurrency,
4533                 value->posSuffixPatternForCurrency,
4534                 value->patternType);
4535             target->put(UnicodeString(*key), copy, status);
4536             if ( U_FAILURE(status) ) {
4537                 return;
4538             }
4539         }
4540     }
4541 }
4542 
4543 
4544 
4545 void
copyHashForAffix(const Hashtable * source,Hashtable * target,UErrorCode & status)4546 DecimalFormat::copyHashForAffix(const Hashtable* source,
4547                                 Hashtable* target,
4548                                 UErrorCode& status) {
4549     if ( U_FAILURE(status) ) {
4550         return;
4551     }
4552     int32_t pos = -1;
4553     const UHashElement* element = NULL;
4554     if ( source ) {
4555         while ( (element = source->nextElement(pos)) != NULL ) {
4556             const UHashTok keyTok = element->key;
4557             const UnicodeString* key = (UnicodeString*)keyTok.pointer;
4558 
4559             const UHashTok valueTok = element->value;
4560             const AffixesForCurrency* value = (AffixesForCurrency*)valueTok.pointer;
4561             AffixesForCurrency* copy = new AffixesForCurrency(
4562                 value->negPrefixForCurrency,
4563                 value->negSuffixForCurrency,
4564                 value->posPrefixForCurrency,
4565                 value->posSuffixForCurrency);
4566             target->put(UnicodeString(*key), copy, status);
4567             if ( U_FAILURE(status) ) {
4568                 return;
4569             }
4570         }
4571     }
4572 }
4573 
4574 U_NAMESPACE_END
4575 
4576 #endif /* #if !UCONFIG_NO_FORMATTING */
4577 
4578 //eof
4579