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