1 // © 2018 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 
4 #include "unicode/utypes.h"
5 
6 #if !UCONFIG_NO_FORMATTING
7 
8 // Allow implicit conversion from char16_t* to UnicodeString for this file:
9 // Helpful in toString methods and elsewhere.
10 #define UNISTR_FROM_STRING_EXPLICIT
11 
12 #include <cmath>
13 #include <cstdlib>
14 #include <stdlib.h>
15 #include "unicode/errorcode.h"
16 #include "unicode/decimfmt.h"
17 #include "number_decimalquantity.h"
18 #include "number_types.h"
19 #include "numparse_impl.h"
20 #include "number_mapper.h"
21 #include "number_patternstring.h"
22 #include "putilimp.h"
23 #include "number_utils.h"
24 #include "number_utypes.h"
25 
26 using namespace icu;
27 using namespace icu::number;
28 using namespace icu::number::impl;
29 using namespace icu::numparse;
30 using namespace icu::numparse::impl;
31 using ERoundingMode = icu::DecimalFormat::ERoundingMode;
32 using EPadPosition = icu::DecimalFormat::EPadPosition;
33 
34 // MSVC VS2015 warns C4805 when comparing bool with UBool, VS2017 no longer emits this warning.
35 // TODO: Move this macro into a better place?
36 #if U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN
37 #define UBOOL_TO_BOOL(b) static_cast<bool>(b)
38 #else
39 #define UBOOL_TO_BOOL(b) b
40 #endif
41 
42 
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DecimalFormat)43 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DecimalFormat)
44 
45 
46 DecimalFormat::DecimalFormat(UErrorCode& status)
47         : DecimalFormat(nullptr, status) {
48     if (U_FAILURE(status)) { return; }
49     // Use the default locale and decimal pattern.
50     const char* localeName = Locale::getDefault().getName();
51     LocalPointer<NumberingSystem> ns(NumberingSystem::createInstance(status));
52     UnicodeString patternString = utils::getPatternForStyle(
53             localeName,
54             ns->getName(),
55             CLDR_PATTERN_STYLE_DECIMAL,
56             status);
57     setPropertiesFromPattern(patternString, IGNORE_ROUNDING_IF_CURRENCY, status);
58     touch(status);
59 }
60 
DecimalFormat(const UnicodeString & pattern,UErrorCode & status)61 DecimalFormat::DecimalFormat(const UnicodeString& pattern, UErrorCode& status)
62         : DecimalFormat(nullptr, status) {
63     if (U_FAILURE(status)) { return; }
64     setPropertiesFromPattern(pattern, IGNORE_ROUNDING_IF_CURRENCY, status);
65     touch(status);
66 }
67 
DecimalFormat(const UnicodeString & pattern,DecimalFormatSymbols * symbolsToAdopt,UErrorCode & status)68 DecimalFormat::DecimalFormat(const UnicodeString& pattern, DecimalFormatSymbols* symbolsToAdopt,
69                              UErrorCode& status)
70         : DecimalFormat(symbolsToAdopt, status) {
71     if (U_FAILURE(status)) { return; }
72     setPropertiesFromPattern(pattern, IGNORE_ROUNDING_IF_CURRENCY, status);
73     touch(status);
74 }
75 
DecimalFormat(const UnicodeString & pattern,DecimalFormatSymbols * symbolsToAdopt,UNumberFormatStyle style,UErrorCode & status)76 DecimalFormat::DecimalFormat(const UnicodeString& pattern, DecimalFormatSymbols* symbolsToAdopt,
77                              UNumberFormatStyle style, UErrorCode& status)
78         : DecimalFormat(symbolsToAdopt, status) {
79     if (U_FAILURE(status)) { return; }
80     // If choice is a currency type, ignore the rounding information.
81     if (style == UNumberFormatStyle::UNUM_CURRENCY ||
82         style == UNumberFormatStyle::UNUM_CURRENCY_ISO ||
83         style == UNumberFormatStyle::UNUM_CURRENCY_ACCOUNTING ||
84         style == UNumberFormatStyle::UNUM_CASH_CURRENCY ||
85         style == UNumberFormatStyle::UNUM_CURRENCY_STANDARD ||
86         style == UNumberFormatStyle::UNUM_CURRENCY_PLURAL) {
87         setPropertiesFromPattern(pattern, IGNORE_ROUNDING_ALWAYS, status);
88     } else {
89         setPropertiesFromPattern(pattern, IGNORE_ROUNDING_IF_CURRENCY, status);
90     }
91     // Note: in Java, CurrencyPluralInfo is set in NumberFormat.java, but in C++, it is not set there,
92     // so we have to set it here.
93     if (style == UNumberFormatStyle::UNUM_CURRENCY_PLURAL) {
94         LocalPointer<CurrencyPluralInfo> cpi(
95                 new CurrencyPluralInfo(fields->symbols->getLocale(), status),
96                 status);
97         if (U_FAILURE(status)) { return; }
98         fields->properties.currencyPluralInfo.fPtr.adoptInstead(cpi.orphan());
99     }
100     touch(status);
101 }
102 
DecimalFormat(const DecimalFormatSymbols * symbolsToAdopt,UErrorCode & status)103 DecimalFormat::DecimalFormat(const DecimalFormatSymbols* symbolsToAdopt, UErrorCode& status) {
104     // we must take ownership of symbolsToAdopt, even in a failure case.
105     LocalPointer<const DecimalFormatSymbols> adoptedSymbols(symbolsToAdopt);
106     if (U_FAILURE(status)) {
107         return;
108     }
109     fields = new DecimalFormatFields();
110     if (fields == nullptr) {
111         status = U_MEMORY_ALLOCATION_ERROR;
112         return;
113     }
114     if (adoptedSymbols.isNull()) {
115         fields->symbols.adoptInsteadAndCheckErrorCode(new DecimalFormatSymbols(status), status);
116     } else {
117         fields->symbols.adoptInsteadAndCheckErrorCode(adoptedSymbols.orphan(), status);
118     }
119     if (U_FAILURE(status)) {
120         delete fields;
121         fields = nullptr;
122     }
123 }
124 
125 #if UCONFIG_HAVE_PARSEALLINPUT
126 
setParseAllInput(UNumberFormatAttributeValue value)127 void DecimalFormat::setParseAllInput(UNumberFormatAttributeValue value) {
128     if (fields == nullptr) { return; }
129     if (value == fields->properties.parseAllInput) { return; }
130     fields->properties.parseAllInput = value;
131 }
132 
133 #endif
134 
135 DecimalFormat&
setAttribute(UNumberFormatAttribute attr,int32_t newValue,UErrorCode & status)136 DecimalFormat::setAttribute(UNumberFormatAttribute attr, int32_t newValue, UErrorCode& status) {
137     if (U_FAILURE(status)) { return *this; }
138 
139     if (fields == nullptr) {
140         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
141         status = U_MEMORY_ALLOCATION_ERROR;
142         return *this;
143     }
144 
145     switch (attr) {
146         case UNUM_LENIENT_PARSE:
147             setLenient(newValue != 0);
148             break;
149 
150         case UNUM_PARSE_INT_ONLY:
151             setParseIntegerOnly(newValue != 0);
152             break;
153 
154         case UNUM_GROUPING_USED:
155             setGroupingUsed(newValue != 0);
156             break;
157 
158         case UNUM_DECIMAL_ALWAYS_SHOWN:
159             setDecimalSeparatorAlwaysShown(newValue != 0);
160             break;
161 
162         case UNUM_MAX_INTEGER_DIGITS:
163             setMaximumIntegerDigits(newValue);
164             break;
165 
166         case UNUM_MIN_INTEGER_DIGITS:
167             setMinimumIntegerDigits(newValue);
168             break;
169 
170         case UNUM_INTEGER_DIGITS:
171             setMinimumIntegerDigits(newValue);
172             setMaximumIntegerDigits(newValue);
173             break;
174 
175         case UNUM_MAX_FRACTION_DIGITS:
176             setMaximumFractionDigits(newValue);
177             break;
178 
179         case UNUM_MIN_FRACTION_DIGITS:
180             setMinimumFractionDigits(newValue);
181             break;
182 
183         case UNUM_FRACTION_DIGITS:
184             setMinimumFractionDigits(newValue);
185             setMaximumFractionDigits(newValue);
186             break;
187 
188         case UNUM_SIGNIFICANT_DIGITS_USED:
189             setSignificantDigitsUsed(newValue != 0);
190             break;
191 
192         case UNUM_MAX_SIGNIFICANT_DIGITS:
193             setMaximumSignificantDigits(newValue);
194             break;
195 
196         case UNUM_MIN_SIGNIFICANT_DIGITS:
197             setMinimumSignificantDigits(newValue);
198             break;
199 
200         case UNUM_MULTIPLIER:
201             setMultiplier(newValue);
202             break;
203 
204         case UNUM_SCALE:
205             setMultiplierScale(newValue);
206             break;
207 
208         case UNUM_GROUPING_SIZE:
209             setGroupingSize(newValue);
210             break;
211 
212         case UNUM_ROUNDING_MODE:
213             setRoundingMode((DecimalFormat::ERoundingMode) newValue);
214             break;
215 
216         case UNUM_FORMAT_WIDTH:
217             setFormatWidth(newValue);
218             break;
219 
220         case UNUM_PADDING_POSITION:
221             /** The position at which padding will take place. */
222             setPadPosition((DecimalFormat::EPadPosition) newValue);
223             break;
224 
225         case UNUM_SECONDARY_GROUPING_SIZE:
226             setSecondaryGroupingSize(newValue);
227             break;
228 
229 #if UCONFIG_HAVE_PARSEALLINPUT
230         case UNUM_PARSE_ALL_INPUT:
231             setParseAllInput((UNumberFormatAttributeValue) newValue);
232             break;
233 #endif
234 
235         case UNUM_PARSE_NO_EXPONENT:
236             setParseNoExponent((UBool) newValue);
237             break;
238 
239         case UNUM_PARSE_DECIMAL_MARK_REQUIRED:
240             setDecimalPatternMatchRequired((UBool) newValue);
241             break;
242 
243         case UNUM_CURRENCY_USAGE:
244             setCurrencyUsage((UCurrencyUsage) newValue, &status);
245             break;
246 
247         case UNUM_MINIMUM_GROUPING_DIGITS:
248             setMinimumGroupingDigits(newValue);
249             break;
250 
251         case UNUM_PARSE_CASE_SENSITIVE:
252             setParseCaseSensitive(static_cast<UBool>(newValue));
253             break;
254 
255         case UNUM_SIGN_ALWAYS_SHOWN:
256             setSignAlwaysShown(static_cast<UBool>(newValue));
257             break;
258 
259         case UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS:
260             setFormatFailIfMoreThanMaxDigits(static_cast<UBool>(newValue));
261             break;
262 
263         default:
264             status = U_UNSUPPORTED_ERROR;
265             break;
266     }
267     return *this;
268 }
269 
getAttribute(UNumberFormatAttribute attr,UErrorCode & status) const270 int32_t DecimalFormat::getAttribute(UNumberFormatAttribute attr, UErrorCode& status) const {
271     if (U_FAILURE(status)) { return -1; }
272 
273     if (fields == nullptr) {
274         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
275         status = U_MEMORY_ALLOCATION_ERROR;
276         return -1;
277     }
278 
279     switch (attr) {
280         case UNUM_LENIENT_PARSE:
281             return isLenient();
282 
283         case UNUM_PARSE_INT_ONLY:
284             return isParseIntegerOnly();
285 
286         case UNUM_GROUPING_USED:
287             return isGroupingUsed();
288 
289         case UNUM_DECIMAL_ALWAYS_SHOWN:
290             return isDecimalSeparatorAlwaysShown();
291 
292         case UNUM_MAX_INTEGER_DIGITS:
293             return getMaximumIntegerDigits();
294 
295         case UNUM_MIN_INTEGER_DIGITS:
296             return getMinimumIntegerDigits();
297 
298         case UNUM_INTEGER_DIGITS:
299             // TBD: what should this return?
300             return getMinimumIntegerDigits();
301 
302         case UNUM_MAX_FRACTION_DIGITS:
303             return getMaximumFractionDigits();
304 
305         case UNUM_MIN_FRACTION_DIGITS:
306             return getMinimumFractionDigits();
307 
308         case UNUM_FRACTION_DIGITS:
309             // TBD: what should this return?
310             return getMinimumFractionDigits();
311 
312         case UNUM_SIGNIFICANT_DIGITS_USED:
313             return areSignificantDigitsUsed();
314 
315         case UNUM_MAX_SIGNIFICANT_DIGITS:
316             return getMaximumSignificantDigits();
317 
318         case UNUM_MIN_SIGNIFICANT_DIGITS:
319             return getMinimumSignificantDigits();
320 
321         case UNUM_MULTIPLIER:
322             return getMultiplier();
323 
324         case UNUM_SCALE:
325             return getMultiplierScale();
326 
327         case UNUM_GROUPING_SIZE:
328             return getGroupingSize();
329 
330         case UNUM_ROUNDING_MODE:
331             return getRoundingMode();
332 
333         case UNUM_FORMAT_WIDTH:
334             return getFormatWidth();
335 
336         case UNUM_PADDING_POSITION:
337             return getPadPosition();
338 
339         case UNUM_SECONDARY_GROUPING_SIZE:
340             return getSecondaryGroupingSize();
341 
342         case UNUM_PARSE_NO_EXPONENT:
343             return isParseNoExponent();
344 
345         case UNUM_PARSE_DECIMAL_MARK_REQUIRED:
346             return isDecimalPatternMatchRequired();
347 
348         case UNUM_CURRENCY_USAGE:
349             return getCurrencyUsage();
350 
351         case UNUM_MINIMUM_GROUPING_DIGITS:
352             return getMinimumGroupingDigits();
353 
354         case UNUM_PARSE_CASE_SENSITIVE:
355             return isParseCaseSensitive();
356 
357         case UNUM_SIGN_ALWAYS_SHOWN:
358             return isSignAlwaysShown();
359 
360         case UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS:
361             return isFormatFailIfMoreThanMaxDigits();
362 
363         default:
364             status = U_UNSUPPORTED_ERROR;
365             break;
366     }
367 
368     return -1; /* undefined */
369 }
370 
setGroupingUsed(UBool enabled)371 void DecimalFormat::setGroupingUsed(UBool enabled) {
372     if (fields == nullptr) {
373         return;
374     }
375     if (UBOOL_TO_BOOL(enabled) == fields->properties.groupingUsed) { return; }
376     NumberFormat::setGroupingUsed(enabled); // to set field for compatibility
377     fields->properties.groupingUsed = enabled;
378     touchNoError();
379 }
380 
setParseIntegerOnly(UBool value)381 void DecimalFormat::setParseIntegerOnly(UBool value) {
382     if (fields == nullptr) {
383         return;
384     }
385     if (UBOOL_TO_BOOL(value) == fields->properties.parseIntegerOnly) { return; }
386     NumberFormat::setParseIntegerOnly(value); // to set field for compatibility
387     fields->properties.parseIntegerOnly = value;
388     touchNoError();
389 }
390 
setLenient(UBool enable)391 void DecimalFormat::setLenient(UBool enable) {
392     if (fields == nullptr) {
393         return;
394     }
395     ParseMode mode = enable ? PARSE_MODE_LENIENT : PARSE_MODE_STRICT;
396     if (!fields->properties.parseMode.isNull() && mode == fields->properties.parseMode.getNoError()) { return; }
397     NumberFormat::setLenient(enable); // to set field for compatibility
398     fields->properties.parseMode = mode;
399     touchNoError();
400 }
401 
DecimalFormat(const UnicodeString & pattern,DecimalFormatSymbols * symbolsToAdopt,UParseError &,UErrorCode & status)402 DecimalFormat::DecimalFormat(const UnicodeString& pattern, DecimalFormatSymbols* symbolsToAdopt,
403                              UParseError&, UErrorCode& status)
404         : DecimalFormat(symbolsToAdopt, status) {
405     if (U_FAILURE(status)) { return; }
406     // TODO: What is parseError for?
407     setPropertiesFromPattern(pattern, IGNORE_ROUNDING_IF_CURRENCY, status);
408     touch(status);
409 }
410 
DecimalFormat(const UnicodeString & pattern,const DecimalFormatSymbols & symbols,UErrorCode & status)411 DecimalFormat::DecimalFormat(const UnicodeString& pattern, const DecimalFormatSymbols& symbols,
412                              UErrorCode& status)
413         : DecimalFormat(nullptr, status) {
414     if (U_FAILURE(status)) { return; }
415     LocalPointer<DecimalFormatSymbols> dfs(new DecimalFormatSymbols(symbols), status);
416     if (U_FAILURE(status)) {
417         // If we failed to allocate DecimalFormatSymbols, then release fields and its members.
418         // We must have a fully complete fields object, we cannot have partially populated members.
419         delete fields;
420         fields = nullptr;
421         status = U_MEMORY_ALLOCATION_ERROR;
422         return;
423     }
424     fields->symbols.adoptInstead(dfs.orphan());
425     setPropertiesFromPattern(pattern, IGNORE_ROUNDING_IF_CURRENCY, status);
426     touch(status);
427 }
428 
DecimalFormat(const DecimalFormat & source)429 DecimalFormat::DecimalFormat(const DecimalFormat& source) : NumberFormat(source) {
430     // If the object that we are copying from is invalid, no point in going further.
431     if (source.fields == nullptr) {
432         return;
433     }
434     // Note: it is not safe to copy fields->formatter or fWarehouse directly because fields->formatter might have
435     // dangling pointers to fields inside fWarehouse. The safe thing is to re-construct fields->formatter from
436     // the property bag, despite being somewhat slower.
437     fields = new DecimalFormatFields(source.fields->properties);
438     if (fields == nullptr) {
439         return; // no way to report an error.
440     }
441     UErrorCode status = U_ZERO_ERROR;
442     fields->symbols.adoptInsteadAndCheckErrorCode(new DecimalFormatSymbols(*source.fields->symbols), status);
443     // In order to simplify error handling logic in the various getters/setters/etc, we do not allow
444     // any partially populated DecimalFormatFields object. We must have a fully complete fields object
445     // or else we set it to nullptr.
446     if (U_FAILURE(status)) {
447         delete fields;
448         fields = nullptr;
449         return;
450     }
451     touch(status);
452 }
453 
operator =(const DecimalFormat & rhs)454 DecimalFormat& DecimalFormat::operator=(const DecimalFormat& rhs) {
455     // guard against self-assignment
456     if (this == &rhs) {
457         return *this;
458     }
459     // Make sure both objects are valid.
460     if (fields == nullptr || rhs.fields == nullptr) {
461         return *this; // unfortunately, no way to report an error.
462     }
463     fields->properties = rhs.fields->properties;
464     fields->exportedProperties.clear();
465     UErrorCode status = U_ZERO_ERROR;
466     LocalPointer<DecimalFormatSymbols> dfs(new DecimalFormatSymbols(*rhs.fields->symbols), status);
467     if (U_FAILURE(status)) {
468         // We failed to allocate DecimalFormatSymbols, release fields and its members.
469         // We must have a fully complete fields object, we cannot have partially populated members.
470         delete fields;
471         fields = nullptr;
472         return *this;
473     }
474     fields->symbols.adoptInstead(dfs.orphan());
475     touch(status);
476 
477     return *this;
478 }
479 
~DecimalFormat()480 DecimalFormat::~DecimalFormat() {
481     if (fields == nullptr) { return; }
482 
483 #ifndef __wasi__
484     delete fields->atomicParser.exchange(nullptr);
485     delete fields->atomicCurrencyParser.exchange(nullptr);
486 #else
487     delete fields->atomicParser;
488     delete fields->atomicCurrencyParser;
489 #endif
490     delete fields;
491 }
492 
clone() const493 DecimalFormat* DecimalFormat::clone() const {
494     // can only clone valid objects.
495     if (fields == nullptr) {
496         return nullptr;
497     }
498     LocalPointer<DecimalFormat> df(new DecimalFormat(*this));
499     if (df.isValid() && df->fields != nullptr) {
500         return df.orphan();
501     }
502     return nullptr;
503 }
504 
operator ==(const Format & other) const505 UBool DecimalFormat::operator==(const Format& other) const {
506     auto* otherDF = dynamic_cast<const DecimalFormat*>(&other);
507     if (otherDF == nullptr) {
508         return false;
509     }
510     // If either object is in an invalid state, prevent dereferencing nullptr below.
511     // Additionally, invalid objects should not be considered equal to anything.
512     if (fields == nullptr || otherDF->fields == nullptr) {
513         return false;
514     }
515     return fields->properties == otherDF->fields->properties && *fields->symbols == *otherDF->fields->symbols;
516 }
517 
format(double number,UnicodeString & appendTo,FieldPosition & pos) const518 UnicodeString& DecimalFormat::format(double number, UnicodeString& appendTo, FieldPosition& pos) const {
519     if (fields == nullptr) {
520         appendTo.setToBogus();
521         return appendTo;
522     }
523     if (pos.getField() == FieldPosition::DONT_CARE && fastFormatDouble(number, appendTo)) {
524         return appendTo;
525     }
526     UErrorCode localStatus = U_ZERO_ERROR;
527     UFormattedNumberData output;
528     output.quantity.setToDouble(number);
529     fields->formatter.formatImpl(&output, localStatus);
530     fieldPositionHelper(output, pos, appendTo.length(), localStatus);
531     auto appendable = UnicodeStringAppendable(appendTo);
532     output.appendTo(appendable, localStatus);
533     return appendTo;
534 }
535 
format(double number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const536 UnicodeString& DecimalFormat::format(double number, UnicodeString& appendTo, FieldPosition& pos,
537                                      UErrorCode& status) const {
538     if (U_FAILURE(status)) {
539         return appendTo; // don't overwrite status if it's already a failure.
540     }
541     if (fields == nullptr) {
542         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
543         status = U_MEMORY_ALLOCATION_ERROR;
544         appendTo.setToBogus();
545         return appendTo;
546     }
547     if (pos.getField() == FieldPosition::DONT_CARE && fastFormatDouble(number, appendTo)) {
548         return appendTo;
549     }
550     UFormattedNumberData output;
551     output.quantity.setToDouble(number);
552     fields->formatter.formatImpl(&output, status);
553     fieldPositionHelper(output, pos, appendTo.length(), status);
554     auto appendable = UnicodeStringAppendable(appendTo);
555     output.appendTo(appendable, status);
556     return appendTo;
557 }
558 
559 UnicodeString&
format(double number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const560 DecimalFormat::format(double number, UnicodeString& appendTo, FieldPositionIterator* posIter,
561                       UErrorCode& status) const {
562     if (U_FAILURE(status)) {
563         return appendTo; // don't overwrite status if it's already a failure.
564     }
565     if (fields == nullptr) {
566         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
567         status = U_MEMORY_ALLOCATION_ERROR;
568         appendTo.setToBogus();
569         return appendTo;
570     }
571     if (posIter == nullptr && fastFormatDouble(number, appendTo)) {
572         return appendTo;
573     }
574     UFormattedNumberData output;
575     output.quantity.setToDouble(number);
576     fields->formatter.formatImpl(&output, status);
577     fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
578     auto appendable = UnicodeStringAppendable(appendTo);
579     output.appendTo(appendable, status);
580     return appendTo;
581 }
582 
format(int32_t number,UnicodeString & appendTo,FieldPosition & pos) const583 UnicodeString& DecimalFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& pos) const {
584     return format(static_cast<int64_t> (number), appendTo, pos);
585 }
586 
format(int32_t number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const587 UnicodeString& DecimalFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& pos,
588                                      UErrorCode& status) const {
589     return format(static_cast<int64_t> (number), appendTo, pos, status);
590 }
591 
592 UnicodeString&
format(int32_t number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const593 DecimalFormat::format(int32_t number, UnicodeString& appendTo, FieldPositionIterator* posIter,
594                       UErrorCode& status) const {
595     return format(static_cast<int64_t> (number), appendTo, posIter, status);
596 }
597 
format(int64_t number,UnicodeString & appendTo,FieldPosition & pos) const598 UnicodeString& DecimalFormat::format(int64_t number, UnicodeString& appendTo, FieldPosition& pos) const {
599     if (fields == nullptr) {
600         appendTo.setToBogus();
601         return appendTo;
602     }
603     if (pos.getField() == FieldPosition::DONT_CARE && fastFormatInt64(number, appendTo)) {
604         return appendTo;
605     }
606     UErrorCode localStatus = U_ZERO_ERROR;
607     UFormattedNumberData output;
608     output.quantity.setToLong(number);
609     fields->formatter.formatImpl(&output, localStatus);
610     fieldPositionHelper(output, pos, appendTo.length(), localStatus);
611     auto appendable = UnicodeStringAppendable(appendTo);
612     output.appendTo(appendable, localStatus);
613     return appendTo;
614 }
615 
format(int64_t number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const616 UnicodeString& DecimalFormat::format(int64_t number, UnicodeString& appendTo, FieldPosition& pos,
617                                      UErrorCode& status) const {
618     if (U_FAILURE(status)) {
619         return appendTo; // don't overwrite status if it's already a failure.
620     }
621     if (fields == nullptr) {
622         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
623         status = U_MEMORY_ALLOCATION_ERROR;
624         appendTo.setToBogus();
625         return appendTo;
626     }
627     if (pos.getField() == FieldPosition::DONT_CARE && fastFormatInt64(number, appendTo)) {
628         return appendTo;
629     }
630     UFormattedNumberData output;
631     output.quantity.setToLong(number);
632     fields->formatter.formatImpl(&output, status);
633     fieldPositionHelper(output, pos, appendTo.length(), status);
634     auto appendable = UnicodeStringAppendable(appendTo);
635     output.appendTo(appendable, status);
636     return appendTo;
637 }
638 
639 UnicodeString&
format(int64_t number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const640 DecimalFormat::format(int64_t number, UnicodeString& appendTo, FieldPositionIterator* posIter,
641                       UErrorCode& status) const {
642     if (U_FAILURE(status)) {
643         return appendTo; // don't overwrite status if it's already a failure.
644     }
645     if (fields == nullptr) {
646         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
647         status = U_MEMORY_ALLOCATION_ERROR;
648         appendTo.setToBogus();
649         return appendTo;
650     }
651     if (posIter == nullptr && fastFormatInt64(number, appendTo)) {
652         return appendTo;
653     }
654     UFormattedNumberData output;
655     output.quantity.setToLong(number);
656     fields->formatter.formatImpl(&output, status);
657     fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
658     auto appendable = UnicodeStringAppendable(appendTo);
659     output.appendTo(appendable, status);
660     return appendTo;
661 }
662 
663 UnicodeString&
format(StringPiece number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const664 DecimalFormat::format(StringPiece number, UnicodeString& appendTo, FieldPositionIterator* posIter,
665                       UErrorCode& status) const {
666     if (U_FAILURE(status)) {
667         return appendTo; // don't overwrite status if it's already a failure.
668     }
669     if (fields == nullptr) {
670         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
671         status = U_MEMORY_ALLOCATION_ERROR;
672         appendTo.setToBogus();
673         return appendTo;
674     }
675     UFormattedNumberData output;
676     output.quantity.setToDecNumber(number, status);
677     fields->formatter.formatImpl(&output, status);
678     fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
679     auto appendable = UnicodeStringAppendable(appendTo);
680     output.appendTo(appendable, status);
681     return appendTo;
682 }
683 
format(const DecimalQuantity & number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const684 UnicodeString& DecimalFormat::format(const DecimalQuantity& number, UnicodeString& appendTo,
685                                      FieldPositionIterator* posIter, UErrorCode& status) const {
686     if (U_FAILURE(status)) {
687         return appendTo; // don't overwrite status if it's already a failure.
688     }
689     if (fields == nullptr) {
690         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
691         status = U_MEMORY_ALLOCATION_ERROR;
692         appendTo.setToBogus();
693         return appendTo;
694     }
695     UFormattedNumberData output;
696     output.quantity = number;
697     fields->formatter.formatImpl(&output, status);
698     fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
699     auto appendable = UnicodeStringAppendable(appendTo);
700     output.appendTo(appendable, status);
701     return appendTo;
702 }
703 
704 UnicodeString&
format(const DecimalQuantity & number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const705 DecimalFormat::format(const DecimalQuantity& number, UnicodeString& appendTo, FieldPosition& pos,
706                       UErrorCode& status) const {
707     if (U_FAILURE(status)) {
708         return appendTo; // don't overwrite status if it's already a failure.
709     }
710     if (fields == nullptr) {
711         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
712         status = U_MEMORY_ALLOCATION_ERROR;
713         appendTo.setToBogus();
714         return appendTo;
715     }
716     UFormattedNumberData output;
717     output.quantity = number;
718     fields->formatter.formatImpl(&output, status);
719     fieldPositionHelper(output, pos, appendTo.length(), status);
720     auto appendable = UnicodeStringAppendable(appendTo);
721     output.appendTo(appendable, status);
722     return appendTo;
723 }
724 
parse(const UnicodeString & text,Formattable & output,ParsePosition & parsePosition) const725 void DecimalFormat::parse(const UnicodeString& text, Formattable& output,
726                           ParsePosition& parsePosition) const {
727     if (fields == nullptr) {
728         return;
729     }
730     if (parsePosition.getIndex() < 0 || parsePosition.getIndex() >= text.length()) {
731         if (parsePosition.getIndex() == text.length()) {
732             // If there is nothing to parse, it is an error
733             parsePosition.setErrorIndex(parsePosition.getIndex());
734         }
735         return;
736     }
737 
738     ErrorCode status;
739     ParsedNumber result;
740     // Note: if this is a currency instance, currencies will be matched despite the fact that we are not in the
741     // parseCurrency method (backwards compatibility)
742     int32_t startIndex = parsePosition.getIndex();
743     const NumberParserImpl* parser = getParser(status);
744     if (U_FAILURE(status)) {
745         return; // unfortunately no way to report back the error.
746     }
747     parser->parse(text, startIndex, true, result, status);
748     if (U_FAILURE(status)) {
749         return; // unfortunately no way to report back the error.
750     }
751     // TODO: Do we need to check for fImpl->properties->parseAllInput (UCONFIG_HAVE_PARSEALLINPUT) here?
752     if (result.success()) {
753         parsePosition.setIndex(result.charEnd);
754         result.populateFormattable(output, parser->getParseFlags());
755     } else {
756         parsePosition.setErrorIndex(startIndex + result.charEnd);
757     }
758 }
759 
parseCurrency(const UnicodeString & text,ParsePosition & parsePosition) const760 CurrencyAmount* DecimalFormat::parseCurrency(const UnicodeString& text, ParsePosition& parsePosition) const {
761     if (fields == nullptr) {
762         return nullptr;
763     }
764     if (parsePosition.getIndex() < 0 || parsePosition.getIndex() >= text.length()) {
765         return nullptr;
766     }
767 
768     ErrorCode status;
769     ParsedNumber result;
770     // Note: if this is a currency instance, currencies will be matched despite the fact that we are not in the
771     // parseCurrency method (backwards compatibility)
772     int32_t startIndex = parsePosition.getIndex();
773     const NumberParserImpl* parser = getCurrencyParser(status);
774     if (U_FAILURE(status)) {
775         return nullptr;
776     }
777     parser->parse(text, startIndex, true, result, status);
778     if (U_FAILURE(status)) {
779         return nullptr;
780     }
781     // TODO: Do we need to check for fImpl->properties->parseAllInput (UCONFIG_HAVE_PARSEALLINPUT) here?
782     if (result.success()) {
783         parsePosition.setIndex(result.charEnd);
784         Formattable formattable;
785         result.populateFormattable(formattable, parser->getParseFlags());
786         LocalPointer<CurrencyAmount> currencyAmount(
787             new CurrencyAmount(formattable, result.currencyCode, status), status);
788         if (U_FAILURE(status)) {
789             return nullptr;
790         }
791         return currencyAmount.orphan();
792     } else {
793         parsePosition.setErrorIndex(startIndex + result.charEnd);
794         return nullptr;
795     }
796 }
797 
getDecimalFormatSymbols(void) const798 const DecimalFormatSymbols* DecimalFormat::getDecimalFormatSymbols(void) const {
799     if (fields == nullptr) {
800         return nullptr;
801     }
802     return fields->symbols.getAlias();
803 }
804 
adoptDecimalFormatSymbols(DecimalFormatSymbols * symbolsToAdopt)805 void DecimalFormat::adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt) {
806     if (symbolsToAdopt == nullptr) {
807         return; // do not allow caller to set fields->symbols to NULL
808     }
809     // we must take ownership of symbolsToAdopt, even in a failure case.
810     LocalPointer<DecimalFormatSymbols> dfs(symbolsToAdopt);
811     if (fields == nullptr) {
812         return;
813     }
814     fields->symbols.adoptInstead(dfs.orphan());
815     touchNoError();
816 }
817 
setDecimalFormatSymbols(const DecimalFormatSymbols & symbols)818 void DecimalFormat::setDecimalFormatSymbols(const DecimalFormatSymbols& symbols) {
819     if (fields == nullptr) {
820         return;
821     }
822     UErrorCode status = U_ZERO_ERROR;
823     LocalPointer<DecimalFormatSymbols> dfs(new DecimalFormatSymbols(symbols), status);
824     if (U_FAILURE(status)) {
825         // We failed to allocate DecimalFormatSymbols, release fields and its members.
826         // We must have a fully complete fields object, we cannot have partially populated members.
827         delete fields;
828         fields = nullptr;
829         return;
830     }
831     fields->symbols.adoptInstead(dfs.orphan());
832     touchNoError();
833 }
834 
getCurrencyPluralInfo(void) const835 const CurrencyPluralInfo* DecimalFormat::getCurrencyPluralInfo(void) const {
836     if (fields == nullptr) {
837         return nullptr;
838     }
839     return fields->properties.currencyPluralInfo.fPtr.getAlias();
840 }
841 
adoptCurrencyPluralInfo(CurrencyPluralInfo * toAdopt)842 void DecimalFormat::adoptCurrencyPluralInfo(CurrencyPluralInfo* toAdopt) {
843     // TODO: should we guard against nullptr input, like in adoptDecimalFormatSymbols?
844     // we must take ownership of toAdopt, even in a failure case.
845     LocalPointer<CurrencyPluralInfo> cpi(toAdopt);
846     if (fields == nullptr) {
847         return;
848     }
849     fields->properties.currencyPluralInfo.fPtr.adoptInstead(cpi.orphan());
850     touchNoError();
851 }
852 
setCurrencyPluralInfo(const CurrencyPluralInfo & info)853 void DecimalFormat::setCurrencyPluralInfo(const CurrencyPluralInfo& info) {
854     if (fields == nullptr) {
855         return;
856     }
857     if (fields->properties.currencyPluralInfo.fPtr.isNull()) {
858         // Note: clone() can fail with OOM error, but we have no way to report it. :(
859         fields->properties.currencyPluralInfo.fPtr.adoptInstead(info.clone());
860     } else {
861         *fields->properties.currencyPluralInfo.fPtr = info; // copy-assignment operator
862     }
863     touchNoError();
864 }
865 
getPositivePrefix(UnicodeString & result) const866 UnicodeString& DecimalFormat::getPositivePrefix(UnicodeString& result) const {
867     if (fields == nullptr) {
868         result.setToBogus();
869         return result;
870     }
871     UErrorCode status = U_ZERO_ERROR;
872     fields->formatter.getAffixImpl(true, false, result, status);
873     if (U_FAILURE(status)) { result.setToBogus(); }
874     return result;
875 }
876 
setPositivePrefix(const UnicodeString & newValue)877 void DecimalFormat::setPositivePrefix(const UnicodeString& newValue) {
878     if (fields == nullptr) {
879         return;
880     }
881     if (newValue == fields->properties.positivePrefix) { return; }
882     fields->properties.positivePrefix = newValue;
883     touchNoError();
884 }
885 
getNegativePrefix(UnicodeString & result) const886 UnicodeString& DecimalFormat::getNegativePrefix(UnicodeString& result) const {
887     if (fields == nullptr) {
888         result.setToBogus();
889         return result;
890     }
891     UErrorCode status = U_ZERO_ERROR;
892     fields->formatter.getAffixImpl(true, true, result, status);
893     if (U_FAILURE(status)) { result.setToBogus(); }
894     return result;
895 }
896 
setNegativePrefix(const UnicodeString & newValue)897 void DecimalFormat::setNegativePrefix(const UnicodeString& newValue) {
898     if (fields == nullptr) {
899         return;
900     }
901     if (newValue == fields->properties.negativePrefix) { return; }
902     fields->properties.negativePrefix = newValue;
903     touchNoError();
904 }
905 
getPositiveSuffix(UnicodeString & result) const906 UnicodeString& DecimalFormat::getPositiveSuffix(UnicodeString& result) const {
907     if (fields == nullptr) {
908         result.setToBogus();
909         return result;
910     }
911     UErrorCode status = U_ZERO_ERROR;
912     fields->formatter.getAffixImpl(false, false, result, status);
913     if (U_FAILURE(status)) { result.setToBogus(); }
914     return result;
915 }
916 
setPositiveSuffix(const UnicodeString & newValue)917 void DecimalFormat::setPositiveSuffix(const UnicodeString& newValue) {
918     if (fields == nullptr) {
919         return;
920     }
921     if (newValue == fields->properties.positiveSuffix) { return; }
922     fields->properties.positiveSuffix = newValue;
923     touchNoError();
924 }
925 
getNegativeSuffix(UnicodeString & result) const926 UnicodeString& DecimalFormat::getNegativeSuffix(UnicodeString& result) const {
927     if (fields == nullptr) {
928         result.setToBogus();
929         return result;
930     }
931     UErrorCode status = U_ZERO_ERROR;
932     fields->formatter.getAffixImpl(false, true, result, status);
933     if (U_FAILURE(status)) { result.setToBogus(); }
934     return result;
935 }
936 
setNegativeSuffix(const UnicodeString & newValue)937 void DecimalFormat::setNegativeSuffix(const UnicodeString& newValue) {
938     if (fields == nullptr) {
939         return;
940     }
941     if (newValue == fields->properties.negativeSuffix) { return; }
942     fields->properties.negativeSuffix = newValue;
943     touchNoError();
944 }
945 
isSignAlwaysShown() const946 UBool DecimalFormat::isSignAlwaysShown() const {
947     // Not much we can do to report an error.
948     if (fields == nullptr) {
949         return DecimalFormatProperties::getDefault().signAlwaysShown;
950     }
951     return fields->properties.signAlwaysShown;
952 }
953 
setSignAlwaysShown(UBool value)954 void DecimalFormat::setSignAlwaysShown(UBool value) {
955     if (fields == nullptr) { return; }
956     if (UBOOL_TO_BOOL(value) == fields->properties.signAlwaysShown) { return; }
957     fields->properties.signAlwaysShown = value;
958     touchNoError();
959 }
960 
getMultiplier(void) const961 int32_t DecimalFormat::getMultiplier(void) const {
962     const DecimalFormatProperties *dfp;
963     // Not much we can do to report an error.
964     if (fields == nullptr) {
965         // Fallback to using the default instance of DecimalFormatProperties.
966         dfp = &(DecimalFormatProperties::getDefault());
967     } else {
968         dfp = &fields->properties;
969     }
970     if (dfp->multiplier != 1) {
971         return dfp->multiplier;
972     } else if (dfp->magnitudeMultiplier != 0) {
973         return static_cast<int32_t>(uprv_pow10(dfp->magnitudeMultiplier));
974     } else {
975         return 1;
976     }
977 }
978 
setMultiplier(int32_t multiplier)979 void DecimalFormat::setMultiplier(int32_t multiplier) {
980     if (fields == nullptr) {
981          return;
982     }
983     if (multiplier == 0) {
984         multiplier = 1;     // one being the benign default value for a multiplier.
985     }
986 
987     // Try to convert to a magnitude multiplier first
988     int delta = 0;
989     int value = multiplier;
990     while (value != 1) {
991         delta++;
992         int temp = value / 10;
993         if (temp * 10 != value) {
994             delta = -1;
995             break;
996         }
997         value = temp;
998     }
999     if (delta != -1) {
1000         fields->properties.magnitudeMultiplier = delta;
1001         fields->properties.multiplier = 1;
1002     } else {
1003         fields->properties.magnitudeMultiplier = 0;
1004         fields->properties.multiplier = multiplier;
1005     }
1006     touchNoError();
1007 }
1008 
getMultiplierScale() const1009 int32_t DecimalFormat::getMultiplierScale() const {
1010     // Not much we can do to report an error.
1011     if (fields == nullptr) {
1012         // Fallback to using the default instance of DecimalFormatProperties.
1013         return DecimalFormatProperties::getDefault().multiplierScale;
1014     }
1015     return fields->properties.multiplierScale;
1016 }
1017 
setMultiplierScale(int32_t newValue)1018 void DecimalFormat::setMultiplierScale(int32_t newValue) {
1019     if (fields == nullptr) { return; }
1020     if (newValue == fields->properties.multiplierScale) { return; }
1021     fields->properties.multiplierScale = newValue;
1022     touchNoError();
1023 }
1024 
getRoundingIncrement(void) const1025 double DecimalFormat::getRoundingIncrement(void) const {
1026     // Not much we can do to report an error.
1027     if (fields == nullptr) {
1028         // Fallback to using the default instance of DecimalFormatProperties.
1029         return DecimalFormatProperties::getDefault().roundingIncrement;
1030     }
1031     return fields->exportedProperties.roundingIncrement;
1032 }
1033 
setRoundingIncrement(double newValue)1034 void DecimalFormat::setRoundingIncrement(double newValue) {
1035     if (fields == nullptr) { return; }
1036     if (newValue == fields->properties.roundingIncrement) { return; }
1037     fields->properties.roundingIncrement = newValue;
1038     touchNoError();
1039 }
1040 
getRoundingMode(void) const1041 ERoundingMode DecimalFormat::getRoundingMode(void) const {
1042     // Not much we can do to report an error.
1043     if (fields == nullptr) {
1044         // Fallback to using the default instance of DecimalFormatProperties.
1045         return static_cast<ERoundingMode>(DecimalFormatProperties::getDefault().roundingMode.getNoError());
1046     }
1047     // UNumberFormatRoundingMode and ERoundingMode have the same values.
1048     return static_cast<ERoundingMode>(fields->exportedProperties.roundingMode.getNoError());
1049 }
1050 
setRoundingMode(ERoundingMode roundingMode)1051 void DecimalFormat::setRoundingMode(ERoundingMode roundingMode) {
1052     if (fields == nullptr) { return; }
1053     auto uRoundingMode = static_cast<UNumberFormatRoundingMode>(roundingMode);
1054     if (!fields->properties.roundingMode.isNull() && uRoundingMode == fields->properties.roundingMode.getNoError()) {
1055         return;
1056     }
1057     NumberFormat::setMaximumIntegerDigits(roundingMode); // to set field for compatibility
1058     fields->properties.roundingMode = uRoundingMode;
1059     touchNoError();
1060 }
1061 
getFormatWidth(void) const1062 int32_t DecimalFormat::getFormatWidth(void) const {
1063     // Not much we can do to report an error.
1064     if (fields == nullptr) {
1065         // Fallback to using the default instance of DecimalFormatProperties.
1066         return DecimalFormatProperties::getDefault().formatWidth;
1067     }
1068     return fields->properties.formatWidth;
1069 }
1070 
setFormatWidth(int32_t width)1071 void DecimalFormat::setFormatWidth(int32_t width) {
1072     if (fields == nullptr) { return; }
1073     if (width == fields->properties.formatWidth) { return; }
1074     fields->properties.formatWidth = width;
1075     touchNoError();
1076 }
1077 
getPadCharacterString() const1078 UnicodeString DecimalFormat::getPadCharacterString() const {
1079     if (fields == nullptr || fields->properties.padString.isBogus()) {
1080         // Readonly-alias the static string kFallbackPaddingString
1081         return {TRUE, kFallbackPaddingString, -1};
1082     } else {
1083         return fields->properties.padString;
1084     }
1085 }
1086 
setPadCharacter(const UnicodeString & padChar)1087 void DecimalFormat::setPadCharacter(const UnicodeString& padChar) {
1088     if (fields == nullptr) { return; }
1089     if (padChar == fields->properties.padString) { return; }
1090     if (padChar.length() > 0) {
1091         fields->properties.padString = UnicodeString(padChar.char32At(0));
1092     } else {
1093         fields->properties.padString.setToBogus();
1094     }
1095     touchNoError();
1096 }
1097 
getPadPosition(void) const1098 EPadPosition DecimalFormat::getPadPosition(void) const {
1099     if (fields == nullptr || fields->properties.padPosition.isNull()) {
1100         return EPadPosition::kPadBeforePrefix;
1101     } else {
1102         // UNumberFormatPadPosition and EPadPosition have the same values.
1103         return static_cast<EPadPosition>(fields->properties.padPosition.getNoError());
1104     }
1105 }
1106 
setPadPosition(EPadPosition padPos)1107 void DecimalFormat::setPadPosition(EPadPosition padPos) {
1108     if (fields == nullptr) { return; }
1109     auto uPadPos = static_cast<UNumberFormatPadPosition>(padPos);
1110     if (!fields->properties.padPosition.isNull() && uPadPos == fields->properties.padPosition.getNoError()) {
1111         return;
1112     }
1113     fields->properties.padPosition = uPadPos;
1114     touchNoError();
1115 }
1116 
isScientificNotation(void) const1117 UBool DecimalFormat::isScientificNotation(void) const {
1118     // Not much we can do to report an error.
1119     if (fields == nullptr) {
1120         // Fallback to using the default instance of DecimalFormatProperties.
1121         return (DecimalFormatProperties::getDefault().minimumExponentDigits != -1);
1122     }
1123     return (fields->properties.minimumExponentDigits != -1);
1124 }
1125 
setScientificNotation(UBool useScientific)1126 void DecimalFormat::setScientificNotation(UBool useScientific) {
1127     if (fields == nullptr) { return; }
1128     int32_t minExp = useScientific ? 1 : -1;
1129     if (fields->properties.minimumExponentDigits == minExp) { return; }
1130     if (useScientific) {
1131         fields->properties.minimumExponentDigits = 1;
1132     } else {
1133         fields->properties.minimumExponentDigits = -1;
1134     }
1135     touchNoError();
1136 }
1137 
getMinimumExponentDigits(void) const1138 int8_t DecimalFormat::getMinimumExponentDigits(void) const {
1139     // Not much we can do to report an error.
1140     if (fields == nullptr) {
1141         // Fallback to using the default instance of DecimalFormatProperties.
1142         return static_cast<int8_t>(DecimalFormatProperties::getDefault().minimumExponentDigits);
1143     }
1144     return static_cast<int8_t>(fields->properties.minimumExponentDigits);
1145 }
1146 
setMinimumExponentDigits(int8_t minExpDig)1147 void DecimalFormat::setMinimumExponentDigits(int8_t minExpDig) {
1148     if (fields == nullptr) { return; }
1149     if (minExpDig == fields->properties.minimumExponentDigits) { return; }
1150     fields->properties.minimumExponentDigits = minExpDig;
1151     touchNoError();
1152 }
1153 
isExponentSignAlwaysShown(void) const1154 UBool DecimalFormat::isExponentSignAlwaysShown(void) const {
1155     // Not much we can do to report an error.
1156     if (fields == nullptr) {
1157         // Fallback to using the default instance of DecimalFormatProperties.
1158         return DecimalFormatProperties::getDefault().exponentSignAlwaysShown;
1159     }
1160     return fields->properties.exponentSignAlwaysShown;
1161 }
1162 
setExponentSignAlwaysShown(UBool expSignAlways)1163 void DecimalFormat::setExponentSignAlwaysShown(UBool expSignAlways) {
1164     if (fields == nullptr) { return; }
1165     if (UBOOL_TO_BOOL(expSignAlways) == fields->properties.exponentSignAlwaysShown) { return; }
1166     fields->properties.exponentSignAlwaysShown = expSignAlways;
1167     touchNoError();
1168 }
1169 
getGroupingSize(void) const1170 int32_t DecimalFormat::getGroupingSize(void) const {
1171     int32_t groupingSize;
1172     // Not much we can do to report an error.
1173     if (fields == nullptr) {
1174         // Fallback to using the default instance of DecimalFormatProperties.
1175         groupingSize = DecimalFormatProperties::getDefault().groupingSize;
1176     } else {
1177         groupingSize = fields->properties.groupingSize;
1178     }
1179     if (groupingSize < 0) {
1180         return 0;
1181     }
1182     return groupingSize;
1183 }
1184 
setGroupingSize(int32_t newValue)1185 void DecimalFormat::setGroupingSize(int32_t newValue) {
1186     if (fields == nullptr) { return; }
1187     if (newValue == fields->properties.groupingSize) { return; }
1188     fields->properties.groupingSize = newValue;
1189     touchNoError();
1190 }
1191 
getSecondaryGroupingSize(void) const1192 int32_t DecimalFormat::getSecondaryGroupingSize(void) const {
1193     int32_t grouping2;
1194     // Not much we can do to report an error.
1195     if (fields == nullptr) {
1196         // Fallback to using the default instance of DecimalFormatProperties.
1197         grouping2 = DecimalFormatProperties::getDefault().secondaryGroupingSize;
1198     } else {
1199         grouping2 = fields->properties.secondaryGroupingSize;
1200     }
1201     if (grouping2 < 0) {
1202         return 0;
1203     }
1204     return grouping2;
1205 }
1206 
setSecondaryGroupingSize(int32_t newValue)1207 void DecimalFormat::setSecondaryGroupingSize(int32_t newValue) {
1208     if (fields == nullptr) { return; }
1209     if (newValue == fields->properties.secondaryGroupingSize) { return; }
1210     fields->properties.secondaryGroupingSize = newValue;
1211     touchNoError();
1212 }
1213 
getMinimumGroupingDigits() const1214 int32_t DecimalFormat::getMinimumGroupingDigits() const {
1215     // Not much we can do to report an error.
1216     if (fields == nullptr) {
1217         // Fallback to using the default instance of DecimalFormatProperties.
1218         return DecimalFormatProperties::getDefault().minimumGroupingDigits;
1219     }
1220     return fields->properties.minimumGroupingDigits;
1221 }
1222 
setMinimumGroupingDigits(int32_t newValue)1223 void DecimalFormat::setMinimumGroupingDigits(int32_t newValue) {
1224     if (fields == nullptr) { return; }
1225     if (newValue == fields->properties.minimumGroupingDigits) { return; }
1226     fields->properties.minimumGroupingDigits = newValue;
1227     touchNoError();
1228 }
1229 
isDecimalSeparatorAlwaysShown(void) const1230 UBool DecimalFormat::isDecimalSeparatorAlwaysShown(void) const {
1231     // Not much we can do to report an error.
1232     if (fields == nullptr) {
1233         // Fallback to using the default instance of DecimalFormatProperties.
1234         return DecimalFormatProperties::getDefault().decimalSeparatorAlwaysShown;
1235     }
1236     return fields->properties.decimalSeparatorAlwaysShown;
1237 }
1238 
setDecimalSeparatorAlwaysShown(UBool newValue)1239 void DecimalFormat::setDecimalSeparatorAlwaysShown(UBool newValue) {
1240     if (fields == nullptr) { return; }
1241     if (UBOOL_TO_BOOL(newValue) == fields->properties.decimalSeparatorAlwaysShown) { return; }
1242     fields->properties.decimalSeparatorAlwaysShown = newValue;
1243     touchNoError();
1244 }
1245 
isDecimalPatternMatchRequired(void) const1246 UBool DecimalFormat::isDecimalPatternMatchRequired(void) const {
1247     // Not much we can do to report an error.
1248     if (fields == nullptr) {
1249         // Fallback to using the default instance of DecimalFormatProperties.
1250         return DecimalFormatProperties::getDefault().decimalPatternMatchRequired;
1251     }
1252     return fields->properties.decimalPatternMatchRequired;
1253 }
1254 
setDecimalPatternMatchRequired(UBool newValue)1255 void DecimalFormat::setDecimalPatternMatchRequired(UBool newValue) {
1256     if (fields == nullptr) { return; }
1257     if (UBOOL_TO_BOOL(newValue) == fields->properties.decimalPatternMatchRequired) { return; }
1258     fields->properties.decimalPatternMatchRequired = newValue;
1259     touchNoError();
1260 }
1261 
isParseNoExponent() const1262 UBool DecimalFormat::isParseNoExponent() const {
1263     // Not much we can do to report an error.
1264     if (fields == nullptr) {
1265         // Fallback to using the default instance of DecimalFormatProperties.
1266         return DecimalFormatProperties::getDefault().parseNoExponent;
1267     }
1268     return fields->properties.parseNoExponent;
1269 }
1270 
setParseNoExponent(UBool value)1271 void DecimalFormat::setParseNoExponent(UBool value) {
1272     if (fields == nullptr) { return; }
1273     if (UBOOL_TO_BOOL(value) == fields->properties.parseNoExponent) { return; }
1274     fields->properties.parseNoExponent = value;
1275     touchNoError();
1276 }
1277 
isParseCaseSensitive() const1278 UBool DecimalFormat::isParseCaseSensitive() const {
1279     // Not much we can do to report an error.
1280     if (fields == nullptr) {
1281         // Fallback to using the default instance of DecimalFormatProperties.
1282         return DecimalFormatProperties::getDefault().parseCaseSensitive;
1283     }
1284     return fields->properties.parseCaseSensitive;
1285 }
1286 
setParseCaseSensitive(UBool value)1287 void DecimalFormat::setParseCaseSensitive(UBool value) {
1288     if (fields == nullptr) { return; }
1289     if (UBOOL_TO_BOOL(value) == fields->properties.parseCaseSensitive) { return; }
1290     fields->properties.parseCaseSensitive = value;
1291     touchNoError();
1292 }
1293 
isFormatFailIfMoreThanMaxDigits() const1294 UBool DecimalFormat::isFormatFailIfMoreThanMaxDigits() const {
1295     // Not much we can do to report an error.
1296     if (fields == nullptr) {
1297         // Fallback to using the default instance of DecimalFormatProperties.
1298         return DecimalFormatProperties::getDefault().formatFailIfMoreThanMaxDigits;
1299     }
1300     return fields->properties.formatFailIfMoreThanMaxDigits;
1301 }
1302 
setFormatFailIfMoreThanMaxDigits(UBool value)1303 void DecimalFormat::setFormatFailIfMoreThanMaxDigits(UBool value) {
1304     if (fields == nullptr) { return; }
1305     if (UBOOL_TO_BOOL(value) == fields->properties.formatFailIfMoreThanMaxDigits) { return; }
1306     fields->properties.formatFailIfMoreThanMaxDigits = value;
1307     touchNoError();
1308 }
1309 
toPattern(UnicodeString & result) const1310 UnicodeString& DecimalFormat::toPattern(UnicodeString& result) const {
1311     if (fields == nullptr) {
1312         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1313         result.setToBogus();
1314         return result;
1315     }
1316     // Pull some properties from exportedProperties and others from properties
1317     // to keep affix patterns intact.  In particular, pull rounding properties
1318     // so that CurrencyUsage is reflected properly.
1319     // TODO: Consider putting this logic in number_patternstring.cpp instead.
1320     ErrorCode localStatus;
1321     DecimalFormatProperties tprops(fields->properties);
1322     bool useCurrency = (
1323         !tprops.currency.isNull() ||
1324         !tprops.currencyPluralInfo.fPtr.isNull() ||
1325         !tprops.currencyUsage.isNull() ||
1326         AffixUtils::hasCurrencySymbols(tprops.positivePrefixPattern, localStatus) ||
1327         AffixUtils::hasCurrencySymbols(tprops.positiveSuffixPattern, localStatus) ||
1328         AffixUtils::hasCurrencySymbols(tprops.negativePrefixPattern, localStatus) ||
1329         AffixUtils::hasCurrencySymbols(tprops.negativeSuffixPattern, localStatus));
1330     if (useCurrency) {
1331         tprops.minimumFractionDigits = fields->exportedProperties.minimumFractionDigits;
1332         tprops.maximumFractionDigits = fields->exportedProperties.maximumFractionDigits;
1333         tprops.roundingIncrement = fields->exportedProperties.roundingIncrement;
1334     }
1335     result = PatternStringUtils::propertiesToPatternString(tprops, localStatus);
1336     return result;
1337 }
1338 
toLocalizedPattern(UnicodeString & result) const1339 UnicodeString& DecimalFormat::toLocalizedPattern(UnicodeString& result) const {
1340     if (fields == nullptr) {
1341         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1342         result.setToBogus();
1343         return result;
1344     }
1345     ErrorCode localStatus;
1346     result = toPattern(result);
1347     result = PatternStringUtils::convertLocalized(result, *fields->symbols, true, localStatus);
1348     return result;
1349 }
1350 
applyPattern(const UnicodeString & pattern,UParseError &,UErrorCode & status)1351 void DecimalFormat::applyPattern(const UnicodeString& pattern, UParseError&, UErrorCode& status) {
1352     // TODO: What is parseError for?
1353     applyPattern(pattern, status);
1354 }
1355 
applyPattern(const UnicodeString & pattern,UErrorCode & status)1356 void DecimalFormat::applyPattern(const UnicodeString& pattern, UErrorCode& status) {
1357     // don't overwrite status if it's already a failure.
1358     if (U_FAILURE(status)) { return; }
1359     if (fields == nullptr) {
1360         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1361         status = U_MEMORY_ALLOCATION_ERROR;
1362         return;
1363     }
1364     setPropertiesFromPattern(pattern, IGNORE_ROUNDING_NEVER, status);
1365     touch(status);
1366 }
1367 
applyLocalizedPattern(const UnicodeString & localizedPattern,UParseError &,UErrorCode & status)1368 void DecimalFormat::applyLocalizedPattern(const UnicodeString& localizedPattern, UParseError&,
1369                                           UErrorCode& status) {
1370     // TODO: What is parseError for?
1371     applyLocalizedPattern(localizedPattern, status);
1372 }
1373 
applyLocalizedPattern(const UnicodeString & localizedPattern,UErrorCode & status)1374 void DecimalFormat::applyLocalizedPattern(const UnicodeString& localizedPattern, UErrorCode& status) {
1375     // don't overwrite status if it's already a failure.
1376     if (U_FAILURE(status)) { return; }
1377     if (fields == nullptr) {
1378         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1379         status = U_MEMORY_ALLOCATION_ERROR;
1380         return;
1381     }
1382     UnicodeString pattern = PatternStringUtils::convertLocalized(
1383             localizedPattern, *fields->symbols, false, status);
1384     applyPattern(pattern, status);
1385 }
1386 
setMaximumIntegerDigits(int32_t newValue)1387 void DecimalFormat::setMaximumIntegerDigits(int32_t newValue) {
1388     if (fields == nullptr) { return; }
1389     if (newValue == fields->properties.maximumIntegerDigits) { return; }
1390     // For backwards compatibility, conflicting min/max need to keep the most recent setting.
1391     int32_t min = fields->properties.minimumIntegerDigits;
1392     if (min >= 0 && min > newValue) {
1393         fields->properties.minimumIntegerDigits = newValue;
1394     }
1395     fields->properties.maximumIntegerDigits = newValue;
1396     touchNoError();
1397 }
1398 
setMinimumIntegerDigits(int32_t newValue)1399 void DecimalFormat::setMinimumIntegerDigits(int32_t newValue) {
1400     if (fields == nullptr) { return; }
1401     if (newValue == fields->properties.minimumIntegerDigits) { return; }
1402     // For backwards compatibility, conflicting min/max need to keep the most recent setting.
1403     int32_t max = fields->properties.maximumIntegerDigits;
1404     if (max >= 0 && max < newValue) {
1405         fields->properties.maximumIntegerDigits = newValue;
1406     }
1407     fields->properties.minimumIntegerDigits = newValue;
1408     touchNoError();
1409 }
1410 
setMaximumFractionDigits(int32_t newValue)1411 void DecimalFormat::setMaximumFractionDigits(int32_t newValue) {
1412     if (fields == nullptr) { return; }
1413     if (newValue == fields->properties.maximumFractionDigits) { return; }
1414     // cap for backward compatibility, formerly 340, now 999
1415     if (newValue > kMaxIntFracSig) {
1416         newValue = kMaxIntFracSig;
1417     }
1418     // For backwards compatibility, conflicting min/max need to keep the most recent setting.
1419     int32_t min = fields->properties.minimumFractionDigits;
1420     if (min >= 0 && min > newValue) {
1421         fields->properties.minimumFractionDigits = newValue;
1422     }
1423     fields->properties.maximumFractionDigits = newValue;
1424     touchNoError();
1425 }
1426 
setMinimumFractionDigits(int32_t newValue)1427 void DecimalFormat::setMinimumFractionDigits(int32_t newValue) {
1428     if (fields == nullptr) { return; }
1429     if (newValue == fields->properties.minimumFractionDigits) { return; }
1430     // For backwards compatibility, conflicting min/max need to keep the most recent setting.
1431     int32_t max = fields->properties.maximumFractionDigits;
1432     if (max >= 0 && max < newValue) {
1433         fields->properties.maximumFractionDigits = newValue;
1434     }
1435     fields->properties.minimumFractionDigits = newValue;
1436     touchNoError();
1437 }
1438 
getMinimumSignificantDigits() const1439 int32_t DecimalFormat::getMinimumSignificantDigits() const {
1440     // Not much we can do to report an error.
1441     if (fields == nullptr) {
1442         // Fallback to using the default instance of DecimalFormatProperties.
1443         return DecimalFormatProperties::getDefault().minimumSignificantDigits;
1444     }
1445     return fields->exportedProperties.minimumSignificantDigits;
1446 }
1447 
getMaximumSignificantDigits() const1448 int32_t DecimalFormat::getMaximumSignificantDigits() const {
1449     // Not much we can do to report an error.
1450     if (fields == nullptr) {
1451         // Fallback to using the default instance of DecimalFormatProperties.
1452         return DecimalFormatProperties::getDefault().maximumSignificantDigits;
1453     }
1454     return fields->exportedProperties.maximumSignificantDigits;
1455 }
1456 
setMinimumSignificantDigits(int32_t value)1457 void DecimalFormat::setMinimumSignificantDigits(int32_t value) {
1458     if (fields == nullptr) { return; }
1459     if (value == fields->properties.minimumSignificantDigits) { return; }
1460     int32_t max = fields->properties.maximumSignificantDigits;
1461     if (max >= 0 && max < value) {
1462         fields->properties.maximumSignificantDigits = value;
1463     }
1464     fields->properties.minimumSignificantDigits = value;
1465     touchNoError();
1466 }
1467 
setMaximumSignificantDigits(int32_t value)1468 void DecimalFormat::setMaximumSignificantDigits(int32_t value) {
1469     if (fields == nullptr) { return; }
1470     if (value == fields->properties.maximumSignificantDigits) { return; }
1471     int32_t min = fields->properties.minimumSignificantDigits;
1472     if (min >= 0 && min > value) {
1473         fields->properties.minimumSignificantDigits = value;
1474     }
1475     fields->properties.maximumSignificantDigits = value;
1476     touchNoError();
1477 }
1478 
areSignificantDigitsUsed() const1479 UBool DecimalFormat::areSignificantDigitsUsed() const {
1480     const DecimalFormatProperties* dfp;
1481     // Not much we can do to report an error.
1482     if (fields == nullptr) {
1483         // Fallback to using the default instance of DecimalFormatProperties.
1484         dfp = &(DecimalFormatProperties::getDefault());
1485     } else {
1486         dfp = &fields->properties;
1487     }
1488     return dfp->minimumSignificantDigits != -1 || dfp->maximumSignificantDigits != -1;
1489 }
1490 
setSignificantDigitsUsed(UBool useSignificantDigits)1491 void DecimalFormat::setSignificantDigitsUsed(UBool useSignificantDigits) {
1492     if (fields == nullptr) { return; }
1493 
1494     // These are the default values from the old implementation.
1495     if (useSignificantDigits) {
1496         if (fields->properties.minimumSignificantDigits != -1 ||
1497             fields->properties.maximumSignificantDigits != -1) {
1498             return;
1499         }
1500     } else {
1501         if (fields->properties.minimumSignificantDigits == -1 &&
1502             fields->properties.maximumSignificantDigits == -1) {
1503             return;
1504         }
1505     }
1506     int32_t minSig = useSignificantDigits ? 1 : -1;
1507     int32_t maxSig = useSignificantDigits ? 6 : -1;
1508     fields->properties.minimumSignificantDigits = minSig;
1509     fields->properties.maximumSignificantDigits = maxSig;
1510     touchNoError();
1511 }
1512 
setCurrency(const char16_t * theCurrency,UErrorCode & ec)1513 void DecimalFormat::setCurrency(const char16_t* theCurrency, UErrorCode& ec) {
1514     // don't overwrite ec if it's already a failure.
1515     if (U_FAILURE(ec)) { return; }
1516     if (fields == nullptr) {
1517         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1518         ec = U_MEMORY_ALLOCATION_ERROR;
1519         return;
1520     }
1521     CurrencyUnit currencyUnit(theCurrency, ec);
1522     if (U_FAILURE(ec)) { return; }
1523     if (!fields->properties.currency.isNull() && fields->properties.currency.getNoError() == currencyUnit) {
1524         return;
1525     }
1526     NumberFormat::setCurrency(theCurrency, ec); // to set field for compatibility
1527     fields->properties.currency = currencyUnit;
1528     // In Java, the DecimalFormatSymbols is mutable. Why not in C++?
1529     LocalPointer<DecimalFormatSymbols> newSymbols(new DecimalFormatSymbols(*fields->symbols), ec);
1530     newSymbols->setCurrency(currencyUnit.getISOCurrency(), ec);
1531     fields->symbols.adoptInsteadAndCheckErrorCode(newSymbols.orphan(), ec);
1532     touch(ec);
1533 }
1534 
setCurrency(const char16_t * theCurrency)1535 void DecimalFormat::setCurrency(const char16_t* theCurrency) {
1536     ErrorCode localStatus;
1537     setCurrency(theCurrency, localStatus);
1538 }
1539 
setCurrencyUsage(UCurrencyUsage newUsage,UErrorCode * ec)1540 void DecimalFormat::setCurrencyUsage(UCurrencyUsage newUsage, UErrorCode* ec) {
1541     // don't overwrite ec if it's already a failure.
1542     if (U_FAILURE(*ec)) { return; }
1543     if (fields == nullptr) {
1544         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1545         *ec = U_MEMORY_ALLOCATION_ERROR;
1546         return;
1547     }
1548     if (!fields->properties.currencyUsage.isNull() && newUsage == fields->properties.currencyUsage.getNoError()) {
1549         return;
1550     }
1551     fields->properties.currencyUsage = newUsage;
1552     touch(*ec);
1553 }
1554 
getCurrencyUsage() const1555 UCurrencyUsage DecimalFormat::getCurrencyUsage() const {
1556     // CurrencyUsage is not exported, so we have to get it from the input property bag.
1557     // TODO: Should we export CurrencyUsage instead?
1558     if (fields == nullptr || fields->properties.currencyUsage.isNull()) {
1559         return UCURR_USAGE_STANDARD;
1560     }
1561     return fields->properties.currencyUsage.getNoError();
1562 }
1563 
1564 void
formatToDecimalQuantity(double number,DecimalQuantity & output,UErrorCode & status) const1565 DecimalFormat::formatToDecimalQuantity(double number, DecimalQuantity& output, UErrorCode& status) const {
1566     // don't overwrite status if it's already a failure.
1567     if (U_FAILURE(status)) { return; }
1568     if (fields == nullptr) {
1569         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1570         status = U_MEMORY_ALLOCATION_ERROR;
1571         return;
1572     }
1573     fields->formatter.formatDouble(number, status).getDecimalQuantity(output, status);
1574 }
1575 
formatToDecimalQuantity(const Formattable & number,DecimalQuantity & output,UErrorCode & status) const1576 void DecimalFormat::formatToDecimalQuantity(const Formattable& number, DecimalQuantity& output,
1577                                             UErrorCode& status) const {
1578     // don't overwrite status if it's already a failure.
1579     if (U_FAILURE(status)) { return; }
1580     if (fields == nullptr) {
1581         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1582         status = U_MEMORY_ALLOCATION_ERROR;
1583         return;
1584     }
1585     UFormattedNumberData obj;
1586     number.populateDecimalQuantity(obj.quantity, status);
1587     fields->formatter.formatImpl(&obj, status);
1588     output = std::move(obj.quantity);
1589 }
1590 
toNumberFormatter(UErrorCode & status) const1591 const number::LocalizedNumberFormatter* DecimalFormat::toNumberFormatter(UErrorCode& status) const {
1592     // We sometimes need to return nullptr here (see ICU-20380)
1593     if (U_FAILURE(status)) { return nullptr; }
1594     if (fields == nullptr) {
1595         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1596         status = U_MEMORY_ALLOCATION_ERROR;
1597         return nullptr;
1598     }
1599     return &fields->formatter;
1600 }
1601 
1602 /** Rebuilds the formatter object from the property bag. */
touch(UErrorCode & status)1603 void DecimalFormat::touch(UErrorCode& status) {
1604     if (U_FAILURE(status)) {
1605         return;
1606     }
1607     if (fields == nullptr) {
1608         // We only get here if an OOM error happend during construction, copy construction, assignment, or modification.
1609         // For regular construction, the caller should have checked the status variable for errors.
1610         // For copy construction, there is unfortunately nothing to report the error, so we need to guard against
1611         // this possible bad state here and set the status to an error.
1612         status = U_MEMORY_ALLOCATION_ERROR;
1613         return;
1614     }
1615 
1616     // In C++, fields->symbols is the source of truth for the locale.
1617     Locale locale = fields->symbols->getLocale();
1618 
1619     // Note: The formatter is relatively cheap to create, and we need it to populate fields->exportedProperties,
1620     // so automatically recompute it here. The parser is a bit more expensive and is not needed until the
1621     // parse method is called, so defer that until needed.
1622     // TODO: Only update the pieces that changed instead of re-computing the whole formatter?
1623 
1624     // Since memory has already been allocated for the formatter, we can move assign a stack-allocated object
1625     // and don't need to call new. (Which is slower and could possibly fail).
1626     fields->formatter = NumberPropertyMapper::create(
1627         fields->properties, *fields->symbols, fields->warehouse, fields->exportedProperties, status
1628     ).locale(locale);
1629 
1630     // Do this after fields->exportedProperties are set up
1631     setupFastFormat();
1632 
1633     // Delete the parsers if they were made previously
1634 #ifndef __wasi__
1635     delete fields->atomicParser.exchange(nullptr);
1636     delete fields->atomicCurrencyParser.exchange(nullptr);
1637 #else
1638     delete fields->atomicParser;
1639     delete fields->atomicCurrencyParser;
1640 #endif
1641 
1642     // In order for the getters to work, we need to populate some fields in NumberFormat.
1643     NumberFormat::setCurrency(fields->exportedProperties.currency.get(status).getISOCurrency(), status);
1644     NumberFormat::setMaximumIntegerDigits(fields->exportedProperties.maximumIntegerDigits);
1645     NumberFormat::setMinimumIntegerDigits(fields->exportedProperties.minimumIntegerDigits);
1646     NumberFormat::setMaximumFractionDigits(fields->exportedProperties.maximumFractionDigits);
1647     NumberFormat::setMinimumFractionDigits(fields->exportedProperties.minimumFractionDigits);
1648     // fImpl->properties, not fields->exportedProperties, since this information comes from the pattern:
1649     NumberFormat::setGroupingUsed(fields->properties.groupingUsed);
1650 }
1651 
touchNoError()1652 void DecimalFormat::touchNoError() {
1653     UErrorCode localStatus = U_ZERO_ERROR;
1654     touch(localStatus);
1655 }
1656 
setPropertiesFromPattern(const UnicodeString & pattern,int32_t ignoreRounding,UErrorCode & status)1657 void DecimalFormat::setPropertiesFromPattern(const UnicodeString& pattern, int32_t ignoreRounding,
1658                                              UErrorCode& status) {
1659     if (U_SUCCESS(status)) {
1660         // Cast workaround to get around putting the enum in the public header file
1661         auto actualIgnoreRounding = static_cast<IgnoreRounding>(ignoreRounding);
1662         PatternParser::parseToExistingProperties(pattern, fields->properties,  actualIgnoreRounding, status);
1663     }
1664 }
1665 
getParser(UErrorCode & status) const1666 const numparse::impl::NumberParserImpl* DecimalFormat::getParser(UErrorCode& status) const {
1667     // TODO: Move this into umutex.h? (similar logic also in numrange_fluent.cpp)
1668     // See ICU-20146
1669 
1670     if (U_FAILURE(status)) {
1671         return nullptr;
1672     }
1673 
1674     // First try to get the pre-computed parser
1675 #ifndef __wasi__
1676     auto* ptr = fields->atomicParser.load();
1677 #else
1678     auto* ptr = fields->atomicParser;
1679 #endif
1680     if (ptr != nullptr) {
1681         return ptr;
1682     }
1683 
1684     // Try computing the parser on our own
1685     auto* temp = NumberParserImpl::createParserFromProperties(fields->properties, *fields->symbols, false, status);
1686     if (U_FAILURE(status)) {
1687         return nullptr;
1688     }
1689     if (temp == nullptr) {
1690         status = U_MEMORY_ALLOCATION_ERROR;
1691         return nullptr;
1692     }
1693 
1694     // Note: ptr starts as nullptr; during compare_exchange,
1695     // it is set to what is actually stored in the atomic
1696     // if another thread beat us to computing the parser object.
1697     auto* nonConstThis = const_cast<DecimalFormat*>(this);
1698 #ifndef __wasi__
1699     if (!nonConstThis->fields->atomicParser.compare_exchange_strong(ptr, temp)) {
1700         // Another thread beat us to computing the parser
1701         delete temp;
1702         return ptr;
1703     } else {
1704         // Our copy of the parser got stored in the atomic
1705         return temp;
1706     }
1707 #else
1708     nonConstThis->fields->atomicParser = temp;
1709     return temp;
1710 #endif
1711 }
1712 
getCurrencyParser(UErrorCode & status) const1713 const numparse::impl::NumberParserImpl* DecimalFormat::getCurrencyParser(UErrorCode& status) const {
1714     if (U_FAILURE(status)) { return nullptr; }
1715 
1716     // First try to get the pre-computed parser
1717 #ifndef __wasi__
1718     auto* ptr = fields->atomicCurrencyParser.load();
1719 #else
1720     auto* ptr = fields->atomicCurrencyParser;
1721 #endif
1722     if (ptr != nullptr) {
1723         return ptr;
1724     }
1725 
1726     // Try computing the parser on our own
1727     auto* temp = NumberParserImpl::createParserFromProperties(fields->properties, *fields->symbols, true, status);
1728     if (temp == nullptr) {
1729         status = U_MEMORY_ALLOCATION_ERROR;
1730         // although we may still dereference, call sites should be guarded
1731     }
1732 
1733     // Note: ptr starts as nullptr; during compare_exchange, it is set to what is actually stored in the
1734     // atomic if another thread beat us to computing the parser object.
1735     auto* nonConstThis = const_cast<DecimalFormat*>(this);
1736 #ifndef __wasi__
1737     if (!nonConstThis->fields->atomicCurrencyParser.compare_exchange_strong(ptr, temp)) {
1738         // Another thread beat us to computing the parser
1739         delete temp;
1740         return ptr;
1741     } else {
1742         // Our copy of the parser got stored in the atomic
1743         return temp;
1744     }
1745 #else
1746     nonConstThis->fields->atomicCurrencyParser = temp;
1747     return temp;
1748 #endif
1749 }
1750 
1751 void
fieldPositionHelper(const UFormattedNumberData & formatted,FieldPosition & fieldPosition,int32_t offset,UErrorCode & status)1752 DecimalFormat::fieldPositionHelper(
1753         const UFormattedNumberData& formatted,
1754         FieldPosition& fieldPosition,
1755         int32_t offset,
1756         UErrorCode& status) {
1757     if (U_FAILURE(status)) { return; }
1758     // always return first occurrence:
1759     fieldPosition.setBeginIndex(0);
1760     fieldPosition.setEndIndex(0);
1761     bool found = formatted.nextFieldPosition(fieldPosition, status);
1762     if (found && offset != 0) {
1763         FieldPositionOnlyHandler fpoh(fieldPosition);
1764         fpoh.shiftLast(offset);
1765     }
1766 }
1767 
1768 void
fieldPositionIteratorHelper(const UFormattedNumberData & formatted,FieldPositionIterator * fpi,int32_t offset,UErrorCode & status)1769 DecimalFormat::fieldPositionIteratorHelper(
1770         const UFormattedNumberData& formatted,
1771         FieldPositionIterator* fpi,
1772         int32_t offset,
1773         UErrorCode& status) {
1774     if (U_SUCCESS(status) && (fpi != nullptr)) {
1775         FieldPositionIteratorHandler fpih(fpi, status);
1776         fpih.setShift(offset);
1777         formatted.getAllFieldPositions(fpih, status);
1778     }
1779 }
1780 
1781 // To debug fast-format, change void(x) to printf(x)
1782 #define trace(x) void(x)
1783 
setupFastFormat()1784 void DecimalFormat::setupFastFormat() {
1785     // Check the majority of properties:
1786     if (!fields->properties.equalsDefaultExceptFastFormat()) {
1787         trace("no fast format: equality\n");
1788         fields->canUseFastFormat = false;
1789         return;
1790     }
1791 
1792     // Now check the remaining properties.
1793     // Nontrivial affixes:
1794     UBool trivialPP = fields->properties.positivePrefixPattern.isEmpty();
1795     UBool trivialPS = fields->properties.positiveSuffixPattern.isEmpty();
1796     UBool trivialNP = fields->properties.negativePrefixPattern.isBogus() || (
1797             fields->properties.negativePrefixPattern.length() == 1 &&
1798             fields->properties.negativePrefixPattern.charAt(0) == u'-');
1799     UBool trivialNS = fields->properties.negativeSuffixPattern.isEmpty();
1800     if (!trivialPP || !trivialPS || !trivialNP || !trivialNS) {
1801         trace("no fast format: affixes\n");
1802         fields->canUseFastFormat = false;
1803         return;
1804     }
1805 
1806     // Grouping (secondary grouping is forbidden in equalsDefaultExceptFastFormat):
1807     bool groupingUsed = fields->properties.groupingUsed;
1808     int32_t groupingSize = fields->properties.groupingSize;
1809     bool unusualGroupingSize = groupingSize > 0 && groupingSize != 3;
1810     const UnicodeString& groupingString = fields->symbols->getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
1811     if (groupingUsed && (unusualGroupingSize || groupingString.length() != 1)) {
1812         trace("no fast format: grouping\n");
1813         fields->canUseFastFormat = false;
1814         return;
1815     }
1816 
1817     // Integer length:
1818     int32_t minInt = fields->exportedProperties.minimumIntegerDigits;
1819     int32_t maxInt = fields->exportedProperties.maximumIntegerDigits;
1820     // Fastpath supports up to only 10 digits (length of INT32_MIN)
1821     if (minInt > 10) {
1822         trace("no fast format: integer\n");
1823         fields->canUseFastFormat = false;
1824         return;
1825     }
1826 
1827     // Fraction length (no fraction part allowed in fast path):
1828     int32_t minFrac = fields->exportedProperties.minimumFractionDigits;
1829     if (minFrac > 0) {
1830         trace("no fast format: fraction\n");
1831         fields->canUseFastFormat = false;
1832         return;
1833     }
1834 
1835     // Other symbols:
1836     const UnicodeString& minusSignString = fields->symbols->getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
1837     UChar32 codePointZero = fields->symbols->getCodePointZero();
1838     if (minusSignString.length() != 1 || U16_LENGTH(codePointZero) != 1) {
1839         trace("no fast format: symbols\n");
1840         fields->canUseFastFormat = false;
1841         return;
1842     }
1843 
1844     // Good to go!
1845     trace("can use fast format!\n");
1846     fields->canUseFastFormat = true;
1847     fields->fastData.cpZero = static_cast<char16_t>(codePointZero);
1848     fields->fastData.cpGroupingSeparator = groupingUsed && groupingSize == 3 ? groupingString.charAt(0) : 0;
1849     fields->fastData.cpMinusSign = minusSignString.charAt(0);
1850     fields->fastData.minInt = (minInt < 0 || minInt > 127) ? 0 : static_cast<int8_t>(minInt);
1851     fields->fastData.maxInt = (maxInt < 0 || maxInt > 127) ? 127 : static_cast<int8_t>(maxInt);
1852 }
1853 
fastFormatDouble(double input,UnicodeString & output) const1854 bool DecimalFormat::fastFormatDouble(double input, UnicodeString& output) const {
1855     if (!fields->canUseFastFormat) {
1856         return false;
1857     }
1858     if (std::isnan(input)
1859             || uprv_trunc(input) != input
1860             || input <= INT32_MIN
1861             || input > INT32_MAX) {
1862         return false;
1863     }
1864     doFastFormatInt32(static_cast<int32_t>(input), std::signbit(input), output);
1865     return true;
1866 }
1867 
fastFormatInt64(int64_t input,UnicodeString & output) const1868 bool DecimalFormat::fastFormatInt64(int64_t input, UnicodeString& output) const {
1869     if (!fields->canUseFastFormat) {
1870         return false;
1871     }
1872     if (input <= INT32_MIN || input > INT32_MAX) {
1873         return false;
1874     }
1875     doFastFormatInt32(static_cast<int32_t>(input), input < 0, output);
1876     return true;
1877 }
1878 
doFastFormatInt32(int32_t input,bool isNegative,UnicodeString & output) const1879 void DecimalFormat::doFastFormatInt32(int32_t input, bool isNegative, UnicodeString& output) const {
1880     U_ASSERT(fields->canUseFastFormat);
1881     if (isNegative) {
1882         output.append(fields->fastData.cpMinusSign);
1883         U_ASSERT(input != INT32_MIN);  // handled by callers
1884         input = -input;
1885     }
1886     // Cap at int32_t to make the buffer small and operations fast.
1887     // Longest string: "2,147,483,648" (13 chars in length)
1888     static constexpr int32_t localCapacity = 13;
1889     char16_t localBuffer[localCapacity];
1890     char16_t* ptr = localBuffer + localCapacity;
1891     int8_t group = 0;
1892     int8_t minInt = (fields->fastData.minInt < 1)? 1: fields->fastData.minInt;
1893     for (int8_t i = 0; i < fields->fastData.maxInt && (input != 0 || i < minInt); i++) {
1894         if (group++ == 3 && fields->fastData.cpGroupingSeparator != 0) {
1895             *(--ptr) = fields->fastData.cpGroupingSeparator;
1896             group = 1;
1897         }
1898         std::div_t res = std::div(input, 10);
1899         *(--ptr) = static_cast<char16_t>(fields->fastData.cpZero + res.rem);
1900         input = res.quot;
1901     }
1902     int32_t len = localCapacity - static_cast<int32_t>(ptr - localBuffer);
1903     output.append(ptr, len);
1904 }
1905 
1906 
1907 #endif /* #if !UCONFIG_NO_FORMATTING */
1908