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 happened 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 happened 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.getDecimalFormatSymbols()), 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.getDecimalFormatSymbols()), 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 delete fields->atomicParser.exchange(nullptr);
484 delete fields->atomicCurrencyParser.exchange(nullptr);
485 delete fields;
486 }
487
clone() const488 DecimalFormat* DecimalFormat::clone() const {
489 // can only clone valid objects.
490 if (fields == nullptr) {
491 return nullptr;
492 }
493 LocalPointer<DecimalFormat> df(new DecimalFormat(*this));
494 if (df.isValid() && df->fields != nullptr) {
495 return df.orphan();
496 }
497 return nullptr;
498 }
499
operator ==(const Format & other) const500 bool DecimalFormat::operator==(const Format& other) const {
501 auto* otherDF = dynamic_cast<const DecimalFormat*>(&other);
502 if (otherDF == nullptr) {
503 return false;
504 }
505 // If either object is in an invalid state, prevent dereferencing nullptr below.
506 // Additionally, invalid objects should not be considered equal to anything.
507 if (fields == nullptr || otherDF->fields == nullptr) {
508 return false;
509 }
510 return fields->properties == otherDF->fields->properties && *getDecimalFormatSymbols() == *otherDF->getDecimalFormatSymbols();
511 }
512
format(double number,UnicodeString & appendTo,FieldPosition & pos) const513 UnicodeString& DecimalFormat::format(double number, UnicodeString& appendTo, FieldPosition& pos) const {
514 if (fields == nullptr) {
515 appendTo.setToBogus();
516 return appendTo;
517 }
518 if (pos.getField() == FieldPosition::DONT_CARE && fastFormatDouble(number, appendTo)) {
519 return appendTo;
520 }
521 UErrorCode localStatus = U_ZERO_ERROR;
522 UFormattedNumberData output;
523 output.quantity.setToDouble(number);
524 fields->formatter.formatImpl(&output, localStatus);
525 fieldPositionHelper(output, pos, appendTo.length(), localStatus);
526 auto appendable = UnicodeStringAppendable(appendTo);
527 output.appendTo(appendable, localStatus);
528 return appendTo;
529 }
530
format(double number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const531 UnicodeString& DecimalFormat::format(double number, UnicodeString& appendTo, FieldPosition& pos,
532 UErrorCode& status) const {
533 if (U_FAILURE(status)) {
534 return appendTo; // don't overwrite status if it's already a failure.
535 }
536 if (fields == nullptr) {
537 // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
538 status = U_MEMORY_ALLOCATION_ERROR;
539 appendTo.setToBogus();
540 return appendTo;
541 }
542 if (pos.getField() == FieldPosition::DONT_CARE && fastFormatDouble(number, appendTo)) {
543 return appendTo;
544 }
545 UFormattedNumberData output;
546 output.quantity.setToDouble(number);
547 fields->formatter.formatImpl(&output, status);
548 fieldPositionHelper(output, pos, appendTo.length(), status);
549 auto appendable = UnicodeStringAppendable(appendTo);
550 output.appendTo(appendable, status);
551 return appendTo;
552 }
553
554 UnicodeString&
format(double number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const555 DecimalFormat::format(double number, UnicodeString& appendTo, FieldPositionIterator* posIter,
556 UErrorCode& status) const {
557 if (U_FAILURE(status)) {
558 return appendTo; // don't overwrite status if it's already a failure.
559 }
560 if (fields == nullptr) {
561 // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
562 status = U_MEMORY_ALLOCATION_ERROR;
563 appendTo.setToBogus();
564 return appendTo;
565 }
566 if (posIter == nullptr && fastFormatDouble(number, appendTo)) {
567 return appendTo;
568 }
569 UFormattedNumberData output;
570 output.quantity.setToDouble(number);
571 fields->formatter.formatImpl(&output, status);
572 fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
573 auto appendable = UnicodeStringAppendable(appendTo);
574 output.appendTo(appendable, status);
575 return appendTo;
576 }
577
format(int32_t number,UnicodeString & appendTo,FieldPosition & pos) const578 UnicodeString& DecimalFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& pos) const {
579 return format(static_cast<int64_t> (number), appendTo, pos);
580 }
581
format(int32_t number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const582 UnicodeString& DecimalFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& pos,
583 UErrorCode& status) const {
584 return format(static_cast<int64_t> (number), appendTo, pos, status);
585 }
586
587 UnicodeString&
format(int32_t number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const588 DecimalFormat::format(int32_t number, UnicodeString& appendTo, FieldPositionIterator* posIter,
589 UErrorCode& status) const {
590 return format(static_cast<int64_t> (number), appendTo, posIter, status);
591 }
592
format(int64_t number,UnicodeString & appendTo,FieldPosition & pos) const593 UnicodeString& DecimalFormat::format(int64_t number, UnicodeString& appendTo, FieldPosition& pos) const {
594 if (fields == nullptr) {
595 appendTo.setToBogus();
596 return appendTo;
597 }
598 if (pos.getField() == FieldPosition::DONT_CARE && fastFormatInt64(number, appendTo)) {
599 return appendTo;
600 }
601 UErrorCode localStatus = U_ZERO_ERROR;
602 UFormattedNumberData output;
603 output.quantity.setToLong(number);
604 fields->formatter.formatImpl(&output, localStatus);
605 fieldPositionHelper(output, pos, appendTo.length(), localStatus);
606 auto appendable = UnicodeStringAppendable(appendTo);
607 output.appendTo(appendable, localStatus);
608 return appendTo;
609 }
610
format(int64_t number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const611 UnicodeString& DecimalFormat::format(int64_t number, UnicodeString& appendTo, FieldPosition& pos,
612 UErrorCode& status) const {
613 if (U_FAILURE(status)) {
614 return appendTo; // don't overwrite status if it's already a failure.
615 }
616 if (fields == nullptr) {
617 // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
618 status = U_MEMORY_ALLOCATION_ERROR;
619 appendTo.setToBogus();
620 return appendTo;
621 }
622 if (pos.getField() == FieldPosition::DONT_CARE && fastFormatInt64(number, appendTo)) {
623 return appendTo;
624 }
625 UFormattedNumberData output;
626 output.quantity.setToLong(number);
627 fields->formatter.formatImpl(&output, 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 happened 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 UFormattedNumberData output;
650 output.quantity.setToLong(number);
651 fields->formatter.formatImpl(&output, status);
652 fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
653 auto appendable = UnicodeStringAppendable(appendTo);
654 output.appendTo(appendable, status);
655 return appendTo;
656 }
657
658 UnicodeString&
format(StringPiece number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const659 DecimalFormat::format(StringPiece number, UnicodeString& appendTo, FieldPositionIterator* posIter,
660 UErrorCode& status) const {
661 if (U_FAILURE(status)) {
662 return appendTo; // don't overwrite status if it's already a failure.
663 }
664 if (fields == nullptr) {
665 // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
666 status = U_MEMORY_ALLOCATION_ERROR;
667 appendTo.setToBogus();
668 return appendTo;
669 }
670 UFormattedNumberData output;
671 output.quantity.setToDecNumber(number, status);
672 fields->formatter.formatImpl(&output, status);
673 fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
674 auto appendable = UnicodeStringAppendable(appendTo);
675 output.appendTo(appendable, status);
676 return appendTo;
677 }
678
format(const DecimalQuantity & number,UnicodeString & appendTo,FieldPositionIterator * posIter,UErrorCode & status) const679 UnicodeString& DecimalFormat::format(const DecimalQuantity& number, UnicodeString& appendTo,
680 FieldPositionIterator* posIter, UErrorCode& status) const {
681 if (U_FAILURE(status)) {
682 return appendTo; // don't overwrite status if it's already a failure.
683 }
684 if (fields == nullptr) {
685 // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
686 status = U_MEMORY_ALLOCATION_ERROR;
687 appendTo.setToBogus();
688 return appendTo;
689 }
690 UFormattedNumberData output;
691 output.quantity = number;
692 fields->formatter.formatImpl(&output, status);
693 fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
694 auto appendable = UnicodeStringAppendable(appendTo);
695 output.appendTo(appendable, status);
696 return appendTo;
697 }
698
699 UnicodeString&
format(const DecimalQuantity & number,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const700 DecimalFormat::format(const DecimalQuantity& number, UnicodeString& appendTo, FieldPosition& pos,
701 UErrorCode& status) const {
702 if (U_FAILURE(status)) {
703 return appendTo; // don't overwrite status if it's already a failure.
704 }
705 if (fields == nullptr) {
706 // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
707 status = U_MEMORY_ALLOCATION_ERROR;
708 appendTo.setToBogus();
709 return appendTo;
710 }
711 UFormattedNumberData output;
712 output.quantity = number;
713 fields->formatter.formatImpl(&output, status);
714 fieldPositionHelper(output, pos, appendTo.length(), status);
715 auto appendable = UnicodeStringAppendable(appendTo);
716 output.appendTo(appendable, status);
717 return appendTo;
718 }
719
parse(const UnicodeString & text,Formattable & output,ParsePosition & parsePosition) const720 void DecimalFormat::parse(const UnicodeString& text, Formattable& output,
721 ParsePosition& parsePosition) const {
722 if (fields == nullptr) {
723 return;
724 }
725 if (parsePosition.getIndex() < 0 || parsePosition.getIndex() >= text.length()) {
726 if (parsePosition.getIndex() == text.length()) {
727 // If there is nothing to parse, it is an error
728 parsePosition.setErrorIndex(parsePosition.getIndex());
729 }
730 return;
731 }
732
733 ErrorCode status;
734 ParsedNumber result;
735 // Note: if this is a currency instance, currencies will be matched despite the fact that we are not in the
736 // parseCurrency method (backwards compatibility)
737 int32_t startIndex = parsePosition.getIndex();
738 const NumberParserImpl* parser = getParser(status);
739 if (U_FAILURE(status)) {
740 return; // unfortunately no way to report back the error.
741 }
742 parser->parse(text, startIndex, true, result, status);
743 if (U_FAILURE(status)) {
744 return; // unfortunately no way to report back the error.
745 }
746 // TODO: Do we need to check for fImpl->properties->parseAllInput (UCONFIG_HAVE_PARSEALLINPUT) here?
747 if (result.success()) {
748 parsePosition.setIndex(result.charEnd);
749 result.populateFormattable(output, parser->getParseFlags());
750 } else {
751 parsePosition.setErrorIndex(startIndex + result.charEnd);
752 }
753 }
754
parseCurrency(const UnicodeString & text,ParsePosition & parsePosition) const755 CurrencyAmount* DecimalFormat::parseCurrency(const UnicodeString& text, ParsePosition& parsePosition) const {
756 if (fields == nullptr) {
757 return nullptr;
758 }
759 if (parsePosition.getIndex() < 0 || parsePosition.getIndex() >= text.length()) {
760 return nullptr;
761 }
762
763 ErrorCode status;
764 ParsedNumber result;
765 // Note: if this is a currency instance, currencies will be matched despite the fact that we are not in the
766 // parseCurrency method (backwards compatibility)
767 int32_t startIndex = parsePosition.getIndex();
768 const NumberParserImpl* parser = getCurrencyParser(status);
769 if (U_FAILURE(status)) {
770 return nullptr;
771 }
772 parser->parse(text, startIndex, true, result, status);
773 if (U_FAILURE(status)) {
774 return nullptr;
775 }
776 // TODO: Do we need to check for fImpl->properties->parseAllInput (UCONFIG_HAVE_PARSEALLINPUT) here?
777 if (result.success()) {
778 parsePosition.setIndex(result.charEnd);
779 Formattable formattable;
780 result.populateFormattable(formattable, parser->getParseFlags());
781 LocalPointer<CurrencyAmount> currencyAmount(
782 new CurrencyAmount(formattable, result.currencyCode, status), status);
783 if (U_FAILURE(status)) {
784 return nullptr;
785 }
786 return currencyAmount.orphan();
787 } else {
788 parsePosition.setErrorIndex(startIndex + result.charEnd);
789 return nullptr;
790 }
791 }
792
getDecimalFormatSymbols(void) const793 const DecimalFormatSymbols* DecimalFormat::getDecimalFormatSymbols(void) const {
794 if (fields == nullptr) {
795 return nullptr;
796 }
797 if (!fields->symbols.isNull()) {
798 return fields->symbols.getAlias();
799 } else {
800 return fields->formatter.getDecimalFormatSymbols();
801 }
802 }
803
adoptDecimalFormatSymbols(DecimalFormatSymbols * symbolsToAdopt)804 void DecimalFormat::adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt) {
805 if (symbolsToAdopt == nullptr) {
806 return; // do not allow caller to set fields->symbols to NULL
807 }
808 // we must take ownership of symbolsToAdopt, even in a failure case.
809 LocalPointer<DecimalFormatSymbols> dfs(symbolsToAdopt);
810 if (fields == nullptr) {
811 return;
812 }
813 fields->symbols.adoptInstead(dfs.orphan());
814 touchNoError();
815 }
816
setDecimalFormatSymbols(const DecimalFormatSymbols & symbols)817 void DecimalFormat::setDecimalFormatSymbols(const DecimalFormatSymbols& symbols) {
818 if (fields == nullptr) {
819 return;
820 }
821 UErrorCode status = U_ZERO_ERROR;
822 LocalPointer<DecimalFormatSymbols> dfs(new DecimalFormatSymbols(symbols), status);
823 if (U_FAILURE(status)) {
824 // We failed to allocate DecimalFormatSymbols, release fields and its members.
825 // We must have a fully complete fields object, we cannot have partially populated members.
826 delete fields;
827 fields = nullptr;
828 return;
829 }
830 fields->symbols.adoptInstead(dfs.orphan());
831 touchNoError();
832 }
833
getCurrencyPluralInfo(void) const834 const CurrencyPluralInfo* DecimalFormat::getCurrencyPluralInfo(void) const {
835 if (fields == nullptr) {
836 return nullptr;
837 }
838 return fields->properties.currencyPluralInfo.fPtr.getAlias();
839 }
840
adoptCurrencyPluralInfo(CurrencyPluralInfo * toAdopt)841 void DecimalFormat::adoptCurrencyPluralInfo(CurrencyPluralInfo* toAdopt) {
842 // TODO: should we guard against nullptr input, like in adoptDecimalFormatSymbols?
843 // we must take ownership of toAdopt, even in a failure case.
844 LocalPointer<CurrencyPluralInfo> cpi(toAdopt);
845 if (fields == nullptr) {
846 return;
847 }
848 fields->properties.currencyPluralInfo.fPtr.adoptInstead(cpi.orphan());
849 touchNoError();
850 }
851
setCurrencyPluralInfo(const CurrencyPluralInfo & info)852 void DecimalFormat::setCurrencyPluralInfo(const CurrencyPluralInfo& info) {
853 if (fields == nullptr) {
854 return;
855 }
856 if (fields->properties.currencyPluralInfo.fPtr.isNull()) {
857 // Note: clone() can fail with OOM error, but we have no way to report it. :(
858 fields->properties.currencyPluralInfo.fPtr.adoptInstead(info.clone());
859 } else {
860 *fields->properties.currencyPluralInfo.fPtr = info; // copy-assignment operator
861 }
862 touchNoError();
863 }
864
getPositivePrefix(UnicodeString & result) const865 UnicodeString& DecimalFormat::getPositivePrefix(UnicodeString& result) const {
866 if (fields == nullptr) {
867 result.setToBogus();
868 return result;
869 }
870 UErrorCode status = U_ZERO_ERROR;
871 fields->formatter.getAffixImpl(true, false, result, status);
872 if (U_FAILURE(status)) { result.setToBogus(); }
873 return result;
874 }
875
setPositivePrefix(const UnicodeString & newValue)876 void DecimalFormat::setPositivePrefix(const UnicodeString& newValue) {
877 if (fields == nullptr) {
878 return;
879 }
880 if (newValue == fields->properties.positivePrefix) { return; }
881 fields->properties.positivePrefix = newValue;
882 touchNoError();
883 }
884
getNegativePrefix(UnicodeString & result) const885 UnicodeString& DecimalFormat::getNegativePrefix(UnicodeString& result) const {
886 if (fields == nullptr) {
887 result.setToBogus();
888 return result;
889 }
890 UErrorCode status = U_ZERO_ERROR;
891 fields->formatter.getAffixImpl(true, true, result, status);
892 if (U_FAILURE(status)) { result.setToBogus(); }
893 return result;
894 }
895
setNegativePrefix(const UnicodeString & newValue)896 void DecimalFormat::setNegativePrefix(const UnicodeString& newValue) {
897 if (fields == nullptr) {
898 return;
899 }
900 if (newValue == fields->properties.negativePrefix) { return; }
901 fields->properties.negativePrefix = newValue;
902 touchNoError();
903 }
904
getPositiveSuffix(UnicodeString & result) const905 UnicodeString& DecimalFormat::getPositiveSuffix(UnicodeString& result) const {
906 if (fields == nullptr) {
907 result.setToBogus();
908 return result;
909 }
910 UErrorCode status = U_ZERO_ERROR;
911 fields->formatter.getAffixImpl(false, false, result, status);
912 if (U_FAILURE(status)) { result.setToBogus(); }
913 return result;
914 }
915
setPositiveSuffix(const UnicodeString & newValue)916 void DecimalFormat::setPositiveSuffix(const UnicodeString& newValue) {
917 if (fields == nullptr) {
918 return;
919 }
920 if (newValue == fields->properties.positiveSuffix) { return; }
921 fields->properties.positiveSuffix = newValue;
922 touchNoError();
923 }
924
getNegativeSuffix(UnicodeString & result) const925 UnicodeString& DecimalFormat::getNegativeSuffix(UnicodeString& result) const {
926 if (fields == nullptr) {
927 result.setToBogus();
928 return result;
929 }
930 UErrorCode status = U_ZERO_ERROR;
931 fields->formatter.getAffixImpl(false, true, result, status);
932 if (U_FAILURE(status)) { result.setToBogus(); }
933 return result;
934 }
935
setNegativeSuffix(const UnicodeString & newValue)936 void DecimalFormat::setNegativeSuffix(const UnicodeString& newValue) {
937 if (fields == nullptr) {
938 return;
939 }
940 if (newValue == fields->properties.negativeSuffix) { return; }
941 fields->properties.negativeSuffix = newValue;
942 touchNoError();
943 }
944
isSignAlwaysShown() const945 UBool DecimalFormat::isSignAlwaysShown() const {
946 // Not much we can do to report an error.
947 if (fields == nullptr) {
948 return DecimalFormatProperties::getDefault().signAlwaysShown;
949 }
950 return fields->properties.signAlwaysShown;
951 }
952
setSignAlwaysShown(UBool value)953 void DecimalFormat::setSignAlwaysShown(UBool value) {
954 if (fields == nullptr) { return; }
955 if (UBOOL_TO_BOOL(value) == fields->properties.signAlwaysShown) { return; }
956 fields->properties.signAlwaysShown = value;
957 touchNoError();
958 }
959
getMultiplier(void) const960 int32_t DecimalFormat::getMultiplier(void) const {
961 const DecimalFormatProperties *dfp;
962 // Not much we can do to report an error.
963 if (fields == nullptr) {
964 // Fallback to using the default instance of DecimalFormatProperties.
965 dfp = &(DecimalFormatProperties::getDefault());
966 } else {
967 dfp = &fields->properties;
968 }
969 if (dfp->multiplier != 1) {
970 return dfp->multiplier;
971 } else if (dfp->magnitudeMultiplier != 0) {
972 return static_cast<int32_t>(uprv_pow10(dfp->magnitudeMultiplier));
973 } else {
974 return 1;
975 }
976 }
977
setMultiplier(int32_t multiplier)978 void DecimalFormat::setMultiplier(int32_t multiplier) {
979 if (fields == nullptr) {
980 return;
981 }
982 if (multiplier == 0) {
983 multiplier = 1; // one being the benign default value for a multiplier.
984 }
985
986 // Try to convert to a magnitude multiplier first
987 int delta = 0;
988 int value = multiplier;
989 while (value != 1) {
990 delta++;
991 int temp = value / 10;
992 if (temp * 10 != value) {
993 delta = -1;
994 break;
995 }
996 value = temp;
997 }
998 if (delta != -1) {
999 fields->properties.magnitudeMultiplier = delta;
1000 fields->properties.multiplier = 1;
1001 } else {
1002 fields->properties.magnitudeMultiplier = 0;
1003 fields->properties.multiplier = multiplier;
1004 }
1005 touchNoError();
1006 }
1007
getMultiplierScale() const1008 int32_t DecimalFormat::getMultiplierScale() const {
1009 // Not much we can do to report an error.
1010 if (fields == nullptr) {
1011 // Fallback to using the default instance of DecimalFormatProperties.
1012 return DecimalFormatProperties::getDefault().multiplierScale;
1013 }
1014 return fields->properties.multiplierScale;
1015 }
1016
setMultiplierScale(int32_t newValue)1017 void DecimalFormat::setMultiplierScale(int32_t newValue) {
1018 if (fields == nullptr) { return; }
1019 if (newValue == fields->properties.multiplierScale) { return; }
1020 fields->properties.multiplierScale = newValue;
1021 touchNoError();
1022 }
1023
getRoundingIncrement(void) const1024 double DecimalFormat::getRoundingIncrement(void) const {
1025 // Not much we can do to report an error.
1026 if (fields == nullptr) {
1027 // Fallback to using the default instance of DecimalFormatProperties.
1028 return DecimalFormatProperties::getDefault().roundingIncrement;
1029 }
1030 return fields->exportedProperties.roundingIncrement;
1031 }
1032
setRoundingIncrement(double newValue)1033 void DecimalFormat::setRoundingIncrement(double newValue) {
1034 if (fields == nullptr) { return; }
1035 if (newValue == fields->properties.roundingIncrement) { return; }
1036 fields->properties.roundingIncrement = newValue;
1037 touchNoError();
1038 }
1039
getRoundingMode(void) const1040 ERoundingMode DecimalFormat::getRoundingMode(void) const {
1041 // Not much we can do to report an error.
1042 if (fields == nullptr) {
1043 // Fallback to using the default instance of DecimalFormatProperties.
1044 return static_cast<ERoundingMode>(DecimalFormatProperties::getDefault().roundingMode.getNoError());
1045 }
1046 // UNumberFormatRoundingMode and ERoundingMode have the same values.
1047 return static_cast<ERoundingMode>(fields->exportedProperties.roundingMode.getNoError());
1048 }
1049
setRoundingMode(ERoundingMode roundingMode)1050 void DecimalFormat::setRoundingMode(ERoundingMode roundingMode) {
1051 if (fields == nullptr) { return; }
1052 auto uRoundingMode = static_cast<UNumberFormatRoundingMode>(roundingMode);
1053 if (!fields->properties.roundingMode.isNull() && uRoundingMode == fields->properties.roundingMode.getNoError()) {
1054 return;
1055 }
1056 NumberFormat::setMaximumIntegerDigits(roundingMode); // to set field for compatibility
1057 fields->properties.roundingMode = uRoundingMode;
1058 touchNoError();
1059 }
1060
getFormatWidth(void) const1061 int32_t DecimalFormat::getFormatWidth(void) const {
1062 // Not much we can do to report an error.
1063 if (fields == nullptr) {
1064 // Fallback to using the default instance of DecimalFormatProperties.
1065 return DecimalFormatProperties::getDefault().formatWidth;
1066 }
1067 return fields->properties.formatWidth;
1068 }
1069
setFormatWidth(int32_t width)1070 void DecimalFormat::setFormatWidth(int32_t width) {
1071 if (fields == nullptr) { return; }
1072 if (width == fields->properties.formatWidth) { return; }
1073 fields->properties.formatWidth = width;
1074 touchNoError();
1075 }
1076
getPadCharacterString() const1077 UnicodeString DecimalFormat::getPadCharacterString() const {
1078 if (fields == nullptr || fields->properties.padString.isBogus()) {
1079 // Readonly-alias the static string kFallbackPaddingString
1080 return {true, kFallbackPaddingString, -1};
1081 } else {
1082 return fields->properties.padString;
1083 }
1084 }
1085
setPadCharacter(const UnicodeString & padChar)1086 void DecimalFormat::setPadCharacter(const UnicodeString& padChar) {
1087 if (fields == nullptr) { return; }
1088 if (padChar == fields->properties.padString) { return; }
1089 if (padChar.length() > 0) {
1090 fields->properties.padString = UnicodeString(padChar.char32At(0));
1091 } else {
1092 fields->properties.padString.setToBogus();
1093 }
1094 touchNoError();
1095 }
1096
getPadPosition(void) const1097 EPadPosition DecimalFormat::getPadPosition(void) const {
1098 if (fields == nullptr || fields->properties.padPosition.isNull()) {
1099 return EPadPosition::kPadBeforePrefix;
1100 } else {
1101 // UNumberFormatPadPosition and EPadPosition have the same values.
1102 return static_cast<EPadPosition>(fields->properties.padPosition.getNoError());
1103 }
1104 }
1105
setPadPosition(EPadPosition padPos)1106 void DecimalFormat::setPadPosition(EPadPosition padPos) {
1107 if (fields == nullptr) { return; }
1108 auto uPadPos = static_cast<UNumberFormatPadPosition>(padPos);
1109 if (!fields->properties.padPosition.isNull() && uPadPos == fields->properties.padPosition.getNoError()) {
1110 return;
1111 }
1112 fields->properties.padPosition = uPadPos;
1113 touchNoError();
1114 }
1115
isScientificNotation(void) const1116 UBool DecimalFormat::isScientificNotation(void) const {
1117 // Not much we can do to report an error.
1118 if (fields == nullptr) {
1119 // Fallback to using the default instance of DecimalFormatProperties.
1120 return (DecimalFormatProperties::getDefault().minimumExponentDigits != -1);
1121 }
1122 return (fields->properties.minimumExponentDigits != -1);
1123 }
1124
setScientificNotation(UBool useScientific)1125 void DecimalFormat::setScientificNotation(UBool useScientific) {
1126 if (fields == nullptr) { return; }
1127 int32_t minExp = useScientific ? 1 : -1;
1128 if (fields->properties.minimumExponentDigits == minExp) { return; }
1129 if (useScientific) {
1130 fields->properties.minimumExponentDigits = 1;
1131 } else {
1132 fields->properties.minimumExponentDigits = -1;
1133 }
1134 touchNoError();
1135 }
1136
getMinimumExponentDigits(void) const1137 int8_t DecimalFormat::getMinimumExponentDigits(void) const {
1138 // Not much we can do to report an error.
1139 if (fields == nullptr) {
1140 // Fallback to using the default instance of DecimalFormatProperties.
1141 return static_cast<int8_t>(DecimalFormatProperties::getDefault().minimumExponentDigits);
1142 }
1143 return static_cast<int8_t>(fields->properties.minimumExponentDigits);
1144 }
1145
setMinimumExponentDigits(int8_t minExpDig)1146 void DecimalFormat::setMinimumExponentDigits(int8_t minExpDig) {
1147 if (fields == nullptr) { return; }
1148 if (minExpDig == fields->properties.minimumExponentDigits) { return; }
1149 fields->properties.minimumExponentDigits = minExpDig;
1150 touchNoError();
1151 }
1152
isExponentSignAlwaysShown(void) const1153 UBool DecimalFormat::isExponentSignAlwaysShown(void) const {
1154 // Not much we can do to report an error.
1155 if (fields == nullptr) {
1156 // Fallback to using the default instance of DecimalFormatProperties.
1157 return DecimalFormatProperties::getDefault().exponentSignAlwaysShown;
1158 }
1159 return fields->properties.exponentSignAlwaysShown;
1160 }
1161
setExponentSignAlwaysShown(UBool expSignAlways)1162 void DecimalFormat::setExponentSignAlwaysShown(UBool expSignAlways) {
1163 if (fields == nullptr) { return; }
1164 if (UBOOL_TO_BOOL(expSignAlways) == fields->properties.exponentSignAlwaysShown) { return; }
1165 fields->properties.exponentSignAlwaysShown = expSignAlways;
1166 touchNoError();
1167 }
1168
getGroupingSize(void) const1169 int32_t DecimalFormat::getGroupingSize(void) const {
1170 int32_t groupingSize;
1171 // Not much we can do to report an error.
1172 if (fields == nullptr) {
1173 // Fallback to using the default instance of DecimalFormatProperties.
1174 groupingSize = DecimalFormatProperties::getDefault().groupingSize;
1175 } else {
1176 groupingSize = fields->properties.groupingSize;
1177 }
1178 if (groupingSize < 0) {
1179 return 0;
1180 }
1181 return groupingSize;
1182 }
1183
setGroupingSize(int32_t newValue)1184 void DecimalFormat::setGroupingSize(int32_t newValue) {
1185 if (fields == nullptr) { return; }
1186 if (newValue == fields->properties.groupingSize) { return; }
1187 fields->properties.groupingSize = newValue;
1188 touchNoError();
1189 }
1190
getSecondaryGroupingSize(void) const1191 int32_t DecimalFormat::getSecondaryGroupingSize(void) const {
1192 int32_t grouping2;
1193 // Not much we can do to report an error.
1194 if (fields == nullptr) {
1195 // Fallback to using the default instance of DecimalFormatProperties.
1196 grouping2 = DecimalFormatProperties::getDefault().secondaryGroupingSize;
1197 } else {
1198 grouping2 = fields->properties.secondaryGroupingSize;
1199 }
1200 if (grouping2 < 0) {
1201 return 0;
1202 }
1203 return grouping2;
1204 }
1205
setSecondaryGroupingSize(int32_t newValue)1206 void DecimalFormat::setSecondaryGroupingSize(int32_t newValue) {
1207 if (fields == nullptr) { return; }
1208 if (newValue == fields->properties.secondaryGroupingSize) { return; }
1209 fields->properties.secondaryGroupingSize = newValue;
1210 touchNoError();
1211 }
1212
getMinimumGroupingDigits() const1213 int32_t DecimalFormat::getMinimumGroupingDigits() const {
1214 // Not much we can do to report an error.
1215 if (fields == nullptr) {
1216 // Fallback to using the default instance of DecimalFormatProperties.
1217 return DecimalFormatProperties::getDefault().minimumGroupingDigits;
1218 }
1219 return fields->properties.minimumGroupingDigits;
1220 }
1221
setMinimumGroupingDigits(int32_t newValue)1222 void DecimalFormat::setMinimumGroupingDigits(int32_t newValue) {
1223 if (fields == nullptr) { return; }
1224 if (newValue == fields->properties.minimumGroupingDigits) { return; }
1225 fields->properties.minimumGroupingDigits = newValue;
1226 touchNoError();
1227 }
1228
isDecimalSeparatorAlwaysShown(void) const1229 UBool DecimalFormat::isDecimalSeparatorAlwaysShown(void) const {
1230 // Not much we can do to report an error.
1231 if (fields == nullptr) {
1232 // Fallback to using the default instance of DecimalFormatProperties.
1233 return DecimalFormatProperties::getDefault().decimalSeparatorAlwaysShown;
1234 }
1235 return fields->properties.decimalSeparatorAlwaysShown;
1236 }
1237
setDecimalSeparatorAlwaysShown(UBool newValue)1238 void DecimalFormat::setDecimalSeparatorAlwaysShown(UBool newValue) {
1239 if (fields == nullptr) { return; }
1240 if (UBOOL_TO_BOOL(newValue) == fields->properties.decimalSeparatorAlwaysShown) { return; }
1241 fields->properties.decimalSeparatorAlwaysShown = newValue;
1242 touchNoError();
1243 }
1244
isDecimalPatternMatchRequired(void) const1245 UBool DecimalFormat::isDecimalPatternMatchRequired(void) const {
1246 // Not much we can do to report an error.
1247 if (fields == nullptr) {
1248 // Fallback to using the default instance of DecimalFormatProperties.
1249 return DecimalFormatProperties::getDefault().decimalPatternMatchRequired;
1250 }
1251 return fields->properties.decimalPatternMatchRequired;
1252 }
1253
setDecimalPatternMatchRequired(UBool newValue)1254 void DecimalFormat::setDecimalPatternMatchRequired(UBool newValue) {
1255 if (fields == nullptr) { return; }
1256 if (UBOOL_TO_BOOL(newValue) == fields->properties.decimalPatternMatchRequired) { return; }
1257 fields->properties.decimalPatternMatchRequired = newValue;
1258 touchNoError();
1259 }
1260
isParseNoExponent() const1261 UBool DecimalFormat::isParseNoExponent() const {
1262 // Not much we can do to report an error.
1263 if (fields == nullptr) {
1264 // Fallback to using the default instance of DecimalFormatProperties.
1265 return DecimalFormatProperties::getDefault().parseNoExponent;
1266 }
1267 return fields->properties.parseNoExponent;
1268 }
1269
setParseNoExponent(UBool value)1270 void DecimalFormat::setParseNoExponent(UBool value) {
1271 if (fields == nullptr) { return; }
1272 if (UBOOL_TO_BOOL(value) == fields->properties.parseNoExponent) { return; }
1273 fields->properties.parseNoExponent = value;
1274 touchNoError();
1275 }
1276
isParseCaseSensitive() const1277 UBool DecimalFormat::isParseCaseSensitive() const {
1278 // Not much we can do to report an error.
1279 if (fields == nullptr) {
1280 // Fallback to using the default instance of DecimalFormatProperties.
1281 return DecimalFormatProperties::getDefault().parseCaseSensitive;
1282 }
1283 return fields->properties.parseCaseSensitive;
1284 }
1285
setParseCaseSensitive(UBool value)1286 void DecimalFormat::setParseCaseSensitive(UBool value) {
1287 if (fields == nullptr) { return; }
1288 if (UBOOL_TO_BOOL(value) == fields->properties.parseCaseSensitive) { return; }
1289 fields->properties.parseCaseSensitive = value;
1290 touchNoError();
1291 }
1292
isFormatFailIfMoreThanMaxDigits() const1293 UBool DecimalFormat::isFormatFailIfMoreThanMaxDigits() const {
1294 // Not much we can do to report an error.
1295 if (fields == nullptr) {
1296 // Fallback to using the default instance of DecimalFormatProperties.
1297 return DecimalFormatProperties::getDefault().formatFailIfMoreThanMaxDigits;
1298 }
1299 return fields->properties.formatFailIfMoreThanMaxDigits;
1300 }
1301
setFormatFailIfMoreThanMaxDigits(UBool value)1302 void DecimalFormat::setFormatFailIfMoreThanMaxDigits(UBool value) {
1303 if (fields == nullptr) { return; }
1304 if (UBOOL_TO_BOOL(value) == fields->properties.formatFailIfMoreThanMaxDigits) { return; }
1305 fields->properties.formatFailIfMoreThanMaxDigits = value;
1306 touchNoError();
1307 }
1308
toPattern(UnicodeString & result) const1309 UnicodeString& DecimalFormat::toPattern(UnicodeString& result) const {
1310 if (fields == nullptr) {
1311 // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
1312 result.setToBogus();
1313 return result;
1314 }
1315 // Pull some properties from exportedProperties and others from properties
1316 // to keep affix patterns intact. In particular, pull rounding properties
1317 // so that CurrencyUsage is reflected properly.
1318 // TODO: Consider putting this logic in number_patternstring.cpp instead.
1319 ErrorCode localStatus;
1320 DecimalFormatProperties tprops(fields->properties);
1321 bool useCurrency = (
1322 !tprops.currency.isNull() ||
1323 !tprops.currencyPluralInfo.fPtr.isNull() ||
1324 !tprops.currencyUsage.isNull() ||
1325 tprops.currencyAsDecimal ||
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 happened 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, *getDecimalFormatSymbols(), 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 happened 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 happened during construction, copy construction, assignment, or modification.
1379 status = U_MEMORY_ALLOCATION_ERROR;
1380 return;
1381 }
1382 UnicodeString pattern = PatternStringUtils::convertLocalized(
1383 localizedPattern, *getDecimalFormatSymbols(), 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 happened 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(*getDecimalFormatSymbols()), 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 happened 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 happened 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 happened 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 happened 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 happened 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 (or, if it's null, the DecimalFormatSymbols owned by the underlying LocalizedNumberFormatter)
1617 // is the source of truth for the locale.
1618 const DecimalFormatSymbols* symbols = getDecimalFormatSymbols();
1619 Locale locale = symbols->getLocale();
1620
1621 // Note: The formatter is relatively cheap to create, and we need it to populate fields->exportedProperties,
1622 // so automatically recompute it here. The parser is a bit more expensive and is not needed until the
1623 // parse method is called, so defer that until needed.
1624 // TODO: Only update the pieces that changed instead of re-computing the whole formatter?
1625
1626 // Since memory has already been allocated for the formatter, we can move assign a stack-allocated object
1627 // and don't need to call new. (Which is slower and could possibly fail).
1628 // [Note that "symbols" above might point to the DecimalFormatSymbols object owned by fields->formatter.
1629 // That's okay, because NumberPropertyMapper::create() will clone it before fields->formatter's assignment
1630 // operator deletes it. But it does mean that "symbols" can't be counted on to be good after this line.]
1631 fields->formatter = NumberPropertyMapper::create(
1632 fields->properties, *symbols, fields->warehouse, fields->exportedProperties, status
1633 ).locale(locale);
1634 fields->symbols.adoptInstead(nullptr); // the fields->symbols property is only temporary, until we can copy it into a new LocalizedNumberFormatter
1635
1636 // Do this after fields->exportedProperties are set up
1637 setupFastFormat();
1638
1639 // Delete the parsers if they were made previously
1640 delete fields->atomicParser.exchange(nullptr);
1641 delete fields->atomicCurrencyParser.exchange(nullptr);
1642
1643 // In order for the getters to work, we need to populate some fields in NumberFormat.
1644 NumberFormat::setCurrency(fields->exportedProperties.currency.get(status).getISOCurrency(), status);
1645 NumberFormat::setMaximumIntegerDigits(fields->exportedProperties.maximumIntegerDigits);
1646 NumberFormat::setMinimumIntegerDigits(fields->exportedProperties.minimumIntegerDigits);
1647 NumberFormat::setMaximumFractionDigits(fields->exportedProperties.maximumFractionDigits);
1648 NumberFormat::setMinimumFractionDigits(fields->exportedProperties.minimumFractionDigits);
1649 // fImpl->properties, not fields->exportedProperties, since this information comes from the pattern:
1650 NumberFormat::setGroupingUsed(fields->properties.groupingUsed);
1651 }
1652
touchNoError()1653 void DecimalFormat::touchNoError() {
1654 UErrorCode localStatus = U_ZERO_ERROR;
1655 touch(localStatus);
1656 }
1657
setPropertiesFromPattern(const UnicodeString & pattern,int32_t ignoreRounding,UErrorCode & status)1658 void DecimalFormat::setPropertiesFromPattern(const UnicodeString& pattern, int32_t ignoreRounding,
1659 UErrorCode& status) {
1660 if (U_SUCCESS(status)) {
1661 // Cast workaround to get around putting the enum in the public header file
1662 auto actualIgnoreRounding = static_cast<IgnoreRounding>(ignoreRounding);
1663 PatternParser::parseToExistingProperties(pattern, fields->properties, actualIgnoreRounding, status);
1664 }
1665 }
1666
getParser(UErrorCode & status) const1667 const numparse::impl::NumberParserImpl* DecimalFormat::getParser(UErrorCode& status) const {
1668 // TODO: Move this into umutex.h? (similar logic also in numrange_fluent.cpp)
1669 // See ICU-20146
1670
1671 if (U_FAILURE(status)) {
1672 return nullptr;
1673 }
1674
1675 // First try to get the pre-computed parser
1676 auto* ptr = fields->atomicParser.load();
1677 if (ptr != nullptr) {
1678 return ptr;
1679 }
1680
1681 // Try computing the parser on our own
1682 auto* temp = NumberParserImpl::createParserFromProperties(fields->properties, *getDecimalFormatSymbols(), false, status);
1683 if (U_FAILURE(status)) {
1684 return nullptr;
1685 }
1686 if (temp == nullptr) {
1687 status = U_MEMORY_ALLOCATION_ERROR;
1688 return nullptr;
1689 }
1690
1691 // Note: ptr starts as nullptr; during compare_exchange,
1692 // it is set to what is actually stored in the atomic
1693 // if another thread beat us to computing the parser object.
1694 auto* nonConstThis = const_cast<DecimalFormat*>(this);
1695 if (!nonConstThis->fields->atomicParser.compare_exchange_strong(ptr, temp)) {
1696 // Another thread beat us to computing the parser
1697 delete temp;
1698 return ptr;
1699 } else {
1700 // Our copy of the parser got stored in the atomic
1701 return temp;
1702 }
1703 }
1704
getCurrencyParser(UErrorCode & status) const1705 const numparse::impl::NumberParserImpl* DecimalFormat::getCurrencyParser(UErrorCode& status) const {
1706 if (U_FAILURE(status)) { return nullptr; }
1707
1708 // First try to get the pre-computed parser
1709 auto* ptr = fields->atomicCurrencyParser.load();
1710 if (ptr != nullptr) {
1711 return ptr;
1712 }
1713
1714 // Try computing the parser on our own
1715 auto* temp = NumberParserImpl::createParserFromProperties(fields->properties, *getDecimalFormatSymbols(), true, status);
1716 if (temp == nullptr) {
1717 status = U_MEMORY_ALLOCATION_ERROR;
1718 // although we may still dereference, call sites should be guarded
1719 }
1720
1721 // Note: ptr starts as nullptr; during compare_exchange, it is set to what is actually stored in the
1722 // atomic if another thread beat us to computing the parser object.
1723 auto* nonConstThis = const_cast<DecimalFormat*>(this);
1724 if (!nonConstThis->fields->atomicCurrencyParser.compare_exchange_strong(ptr, temp)) {
1725 // Another thread beat us to computing the parser
1726 delete temp;
1727 return ptr;
1728 } else {
1729 // Our copy of the parser got stored in the atomic
1730 return temp;
1731 }
1732 }
1733
1734 void
fieldPositionHelper(const UFormattedNumberData & formatted,FieldPosition & fieldPosition,int32_t offset,UErrorCode & status)1735 DecimalFormat::fieldPositionHelper(
1736 const UFormattedNumberData& formatted,
1737 FieldPosition& fieldPosition,
1738 int32_t offset,
1739 UErrorCode& status) {
1740 if (U_FAILURE(status)) { return; }
1741 // always return first occurrence:
1742 fieldPosition.setBeginIndex(0);
1743 fieldPosition.setEndIndex(0);
1744 bool found = formatted.nextFieldPosition(fieldPosition, status);
1745 if (found && offset != 0) {
1746 FieldPositionOnlyHandler fpoh(fieldPosition);
1747 fpoh.shiftLast(offset);
1748 }
1749 }
1750
1751 void
fieldPositionIteratorHelper(const UFormattedNumberData & formatted,FieldPositionIterator * fpi,int32_t offset,UErrorCode & status)1752 DecimalFormat::fieldPositionIteratorHelper(
1753 const UFormattedNumberData& formatted,
1754 FieldPositionIterator* fpi,
1755 int32_t offset,
1756 UErrorCode& status) {
1757 if (U_SUCCESS(status) && (fpi != nullptr)) {
1758 FieldPositionIteratorHandler fpih(fpi, status);
1759 fpih.setShift(offset);
1760 formatted.getAllFieldPositions(fpih, status);
1761 }
1762 }
1763
1764 // To debug fast-format, change void(x) to printf(x)
1765 #define trace(x) void(x)
1766
setupFastFormat()1767 void DecimalFormat::setupFastFormat() {
1768 // Check the majority of properties:
1769 if (!fields->properties.equalsDefaultExceptFastFormat()) {
1770 trace("no fast format: equality\n");
1771 fields->canUseFastFormat = false;
1772 return;
1773 }
1774
1775 // Now check the remaining properties.
1776 // Nontrivial affixes:
1777 UBool trivialPP = fields->properties.positivePrefixPattern.isEmpty();
1778 UBool trivialPS = fields->properties.positiveSuffixPattern.isEmpty();
1779 UBool trivialNP = fields->properties.negativePrefixPattern.isBogus() || (
1780 fields->properties.negativePrefixPattern.length() == 1 &&
1781 fields->properties.negativePrefixPattern.charAt(0) == u'-');
1782 UBool trivialNS = fields->properties.negativeSuffixPattern.isEmpty();
1783 if (!trivialPP || !trivialPS || !trivialNP || !trivialNS) {
1784 trace("no fast format: affixes\n");
1785 fields->canUseFastFormat = false;
1786 return;
1787 }
1788
1789 const DecimalFormatSymbols* symbols = getDecimalFormatSymbols();
1790
1791 // Grouping (secondary grouping is forbidden in equalsDefaultExceptFastFormat):
1792 bool groupingUsed = fields->properties.groupingUsed;
1793 int32_t groupingSize = fields->properties.groupingSize;
1794 bool unusualGroupingSize = groupingSize > 0 && groupingSize != 3;
1795 const UnicodeString& groupingString = symbols->getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
1796 if (groupingUsed && (unusualGroupingSize || groupingString.length() != 1)) {
1797 trace("no fast format: grouping\n");
1798 fields->canUseFastFormat = false;
1799 return;
1800 }
1801
1802 // Integer length:
1803 int32_t minInt = fields->exportedProperties.minimumIntegerDigits;
1804 int32_t maxInt = fields->exportedProperties.maximumIntegerDigits;
1805 // Fastpath supports up to only 10 digits (length of INT32_MIN)
1806 if (minInt > 10) {
1807 trace("no fast format: integer\n");
1808 fields->canUseFastFormat = false;
1809 return;
1810 }
1811
1812 // Fraction length (no fraction part allowed in fast path):
1813 int32_t minFrac = fields->exportedProperties.minimumFractionDigits;
1814 if (minFrac > 0) {
1815 trace("no fast format: fraction\n");
1816 fields->canUseFastFormat = false;
1817 return;
1818 }
1819
1820 // Other symbols:
1821 const UnicodeString& minusSignString = symbols->getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
1822 UChar32 codePointZero = symbols->getCodePointZero();
1823 if (minusSignString.length() != 1 || U16_LENGTH(codePointZero) != 1) {
1824 trace("no fast format: symbols\n");
1825 fields->canUseFastFormat = false;
1826 return;
1827 }
1828
1829 // Good to go!
1830 trace("can use fast format!\n");
1831 fields->canUseFastFormat = true;
1832 fields->fastData.cpZero = static_cast<char16_t>(codePointZero);
1833 fields->fastData.cpGroupingSeparator = groupingUsed && groupingSize == 3 ? groupingString.charAt(0) : 0;
1834 fields->fastData.cpMinusSign = minusSignString.charAt(0);
1835 fields->fastData.minInt = (minInt < 0 || minInt > 127) ? 0 : static_cast<int8_t>(minInt);
1836 fields->fastData.maxInt = (maxInt < 0 || maxInt > 127) ? 127 : static_cast<int8_t>(maxInt);
1837 }
1838
fastFormatDouble(double input,UnicodeString & output) const1839 bool DecimalFormat::fastFormatDouble(double input, UnicodeString& output) const {
1840 if (!fields->canUseFastFormat) {
1841 return false;
1842 }
1843 if (std::isnan(input)
1844 || uprv_trunc(input) != input
1845 || input <= INT32_MIN
1846 || input > INT32_MAX) {
1847 return false;
1848 }
1849 doFastFormatInt32(static_cast<int32_t>(input), std::signbit(input), output);
1850 return true;
1851 }
1852
fastFormatInt64(int64_t input,UnicodeString & output) const1853 bool DecimalFormat::fastFormatInt64(int64_t input, UnicodeString& output) const {
1854 if (!fields->canUseFastFormat) {
1855 return false;
1856 }
1857 if (input <= INT32_MIN || input > INT32_MAX) {
1858 return false;
1859 }
1860 doFastFormatInt32(static_cast<int32_t>(input), input < 0, output);
1861 return true;
1862 }
1863
doFastFormatInt32(int32_t input,bool isNegative,UnicodeString & output) const1864 void DecimalFormat::doFastFormatInt32(int32_t input, bool isNegative, UnicodeString& output) const {
1865 U_ASSERT(fields->canUseFastFormat);
1866 if (isNegative) {
1867 output.append(fields->fastData.cpMinusSign);
1868 U_ASSERT(input != INT32_MIN); // handled by callers
1869 input = -input;
1870 }
1871 // Cap at int32_t to make the buffer small and operations fast.
1872 // Longest string: "2,147,483,648" (13 chars in length)
1873 static constexpr int32_t localCapacity = 13;
1874 char16_t localBuffer[localCapacity];
1875 char16_t* ptr = localBuffer + localCapacity;
1876 int8_t group = 0;
1877 int8_t minInt = (fields->fastData.minInt < 1)? 1: fields->fastData.minInt;
1878 for (int8_t i = 0; i < fields->fastData.maxInt && (input != 0 || i < minInt); i++) {
1879 if (group++ == 3 && fields->fastData.cpGroupingSeparator != 0) {
1880 *(--ptr) = fields->fastData.cpGroupingSeparator;
1881 group = 1;
1882 }
1883 std::div_t res = std::div(input, 10);
1884 *(--ptr) = static_cast<char16_t>(fields->fastData.cpZero + res.rem);
1885 input = res.quot;
1886 }
1887 int32_t len = localCapacity - static_cast<int32_t>(ptr - localBuffer);
1888 output.append(ptr, len);
1889 }
1890
1891
1892 #endif /* #if !UCONFIG_NO_FORMATTING */
1893