tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

decimfmt.cpp (71522B)


      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 
     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 
     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 
     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 
     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 
    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 
    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&
    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(static_cast<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(static_cast<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(static_cast<UNumberFormatAttributeValue>(newValue));
    232            break;
    233 #endif
    234 
    235        case UNUM_PARSE_NO_EXPONENT:
    236            setParseNoExponent(static_cast<UBool>(newValue));
    237            break;
    238 
    239        case UNUM_PARSE_DECIMAL_MARK_REQUIRED:
    240            setDecimalPatternMatchRequired(static_cast<UBool>(newValue));
    241            break;
    242 
    243        case UNUM_CURRENCY_USAGE:
    244            setCurrencyUsage(static_cast<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 
    270 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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    480 DecimalFormat::~DecimalFormat() {
    481    if (fields == nullptr) { return; }
    482 
    483 #ifndef __wasi__
    484    delete fields->atomicParser.exchange(nullptr);
    485    delete fields->atomicCurrencyParser.exchange(nullptr);
    486 #else
    487    delete fields->atomicParser;
    488    delete fields->atomicCurrencyParser;
    489 #endif
    490    delete fields;
    491 }
    492 
    493 DecimalFormat* DecimalFormat::clone() const {
    494    // can only clone valid objects.
    495    if (fields == nullptr) {
    496        return nullptr;
    497    }
    498    LocalPointer<DecimalFormat> df(new DecimalFormat(*this));
    499    if (df.isValid() && df->fields != nullptr) {
    500        return df.orphan();
    501    }
    502    return nullptr;
    503 }
    504 
    505 bool DecimalFormat::operator==(const Format& other) const {
    506    const auto* otherDF = dynamic_cast<const DecimalFormat*>(&other);
    507    if (otherDF == nullptr) {
    508        return false;
    509    }
    510    // If either object is in an invalid state, prevent dereferencing nullptr below.
    511    // Additionally, invalid objects should not be considered equal to anything.
    512    if (fields == nullptr || otherDF->fields == nullptr) {
    513        return false;
    514    }
    515    return fields->properties == otherDF->fields->properties && *getDecimalFormatSymbols() == *otherDF->getDecimalFormatSymbols();
    516 }
    517 
    518 UnicodeString& DecimalFormat::format(double number, UnicodeString& appendTo, FieldPosition& pos) const {
    519    if (fields == nullptr) {
    520        appendTo.setToBogus();
    521        return appendTo;
    522    }
    523    if (pos.getField() == FieldPosition::DONT_CARE && fastFormatDouble(number, appendTo)) {
    524        return appendTo;
    525    }
    526    UErrorCode localStatus = U_ZERO_ERROR;
    527    UFormattedNumberData output;
    528    output.quantity.setToDouble(number);
    529    fields->formatter.formatImpl(&output, localStatus);
    530    fieldPositionHelper(output, pos, appendTo.length(), localStatus);
    531    auto appendable = UnicodeStringAppendable(appendTo);
    532    output.appendTo(appendable, localStatus);
    533    return appendTo;
    534 }
    535 
    536 UnicodeString& DecimalFormat::format(double number, UnicodeString& appendTo, FieldPosition& pos,
    537                                     UErrorCode& status) const {
    538    if (U_FAILURE(status)) {
    539        return appendTo; // don't overwrite status if it's already a failure.
    540    }
    541    if (fields == nullptr) {
    542        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
    543        status = U_MEMORY_ALLOCATION_ERROR;
    544        appendTo.setToBogus();
    545        return appendTo;
    546    }
    547    if (pos.getField() == FieldPosition::DONT_CARE && fastFormatDouble(number, appendTo)) {
    548        return appendTo;
    549    }
    550    UFormattedNumberData output;
    551    output.quantity.setToDouble(number);
    552    fields->formatter.formatImpl(&output, status);
    553    fieldPositionHelper(output, pos, appendTo.length(), status);
    554    auto appendable = UnicodeStringAppendable(appendTo);
    555    output.appendTo(appendable, status);
    556    return appendTo;
    557 }
    558 
    559 UnicodeString&
    560 DecimalFormat::format(double number, UnicodeString& appendTo, FieldPositionIterator* posIter,
    561                      UErrorCode& status) const {
    562    if (U_FAILURE(status)) {
    563        return appendTo; // don't overwrite status if it's already a failure.
    564    }
    565    if (fields == nullptr) {
    566        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
    567        status = U_MEMORY_ALLOCATION_ERROR;
    568        appendTo.setToBogus();
    569        return appendTo;
    570    }
    571    if (posIter == nullptr && fastFormatDouble(number, appendTo)) {
    572        return appendTo;
    573    }
    574    UFormattedNumberData output;
    575    output.quantity.setToDouble(number);
    576    fields->formatter.formatImpl(&output, status);
    577    fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
    578    auto appendable = UnicodeStringAppendable(appendTo);
    579    output.appendTo(appendable, status);
    580    return appendTo;
    581 }
    582 
    583 UnicodeString& DecimalFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& pos) const {
    584    return format(static_cast<int64_t> (number), appendTo, pos);
    585 }
    586 
    587 UnicodeString& DecimalFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& pos,
    588                                     UErrorCode& status) const {
    589    return format(static_cast<int64_t> (number), appendTo, pos, status);
    590 }
    591 
    592 UnicodeString&
    593 DecimalFormat::format(int32_t number, UnicodeString& appendTo, FieldPositionIterator* posIter,
    594                      UErrorCode& status) const {
    595    return format(static_cast<int64_t> (number), appendTo, posIter, status);
    596 }
    597 
    598 UnicodeString& DecimalFormat::format(int64_t number, UnicodeString& appendTo, FieldPosition& pos) const {
    599    if (fields == nullptr) {
    600        appendTo.setToBogus();
    601        return appendTo;
    602    }
    603    if (pos.getField() == FieldPosition::DONT_CARE && fastFormatInt64(number, appendTo)) {
    604        return appendTo;
    605    }
    606    UErrorCode localStatus = U_ZERO_ERROR;
    607    UFormattedNumberData output;
    608    output.quantity.setToLong(number);
    609    fields->formatter.formatImpl(&output, localStatus);
    610    fieldPositionHelper(output, pos, appendTo.length(), localStatus);
    611    auto appendable = UnicodeStringAppendable(appendTo);
    612    output.appendTo(appendable, localStatus);
    613    return appendTo;
    614 }
    615 
    616 UnicodeString& DecimalFormat::format(int64_t number, UnicodeString& appendTo, FieldPosition& pos,
    617                                     UErrorCode& status) const {
    618    if (U_FAILURE(status)) {
    619        return appendTo; // don't overwrite status if it's already a failure.
    620    }
    621    if (fields == nullptr) {
    622        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
    623        status = U_MEMORY_ALLOCATION_ERROR;
    624        appendTo.setToBogus();
    625        return appendTo;
    626    }
    627    if (pos.getField() == FieldPosition::DONT_CARE && fastFormatInt64(number, appendTo)) {
    628        return appendTo;
    629    }
    630    UFormattedNumberData output;
    631    output.quantity.setToLong(number);
    632    fields->formatter.formatImpl(&output, status);
    633    fieldPositionHelper(output, pos, appendTo.length(), status);
    634    auto appendable = UnicodeStringAppendable(appendTo);
    635    output.appendTo(appendable, status);
    636    return appendTo;
    637 }
    638 
    639 UnicodeString&
    640 DecimalFormat::format(int64_t number, UnicodeString& appendTo, FieldPositionIterator* posIter,
    641                      UErrorCode& status) const {
    642    if (U_FAILURE(status)) {
    643        return appendTo; // don't overwrite status if it's already a failure.
    644    }
    645    if (fields == nullptr) {
    646        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
    647        status = U_MEMORY_ALLOCATION_ERROR;
    648        appendTo.setToBogus();
    649        return appendTo;
    650    }
    651    if (posIter == nullptr && fastFormatInt64(number, appendTo)) {
    652        return appendTo;
    653    }
    654    UFormattedNumberData output;
    655    output.quantity.setToLong(number);
    656    fields->formatter.formatImpl(&output, status);
    657    fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
    658    auto appendable = UnicodeStringAppendable(appendTo);
    659    output.appendTo(appendable, status);
    660    return appendTo;
    661 }
    662 
    663 UnicodeString&
    664 DecimalFormat::format(StringPiece number, UnicodeString& appendTo, FieldPositionIterator* posIter,
    665                      UErrorCode& status) const {
    666    if (U_FAILURE(status)) {
    667        return appendTo; // don't overwrite status if it's already a failure.
    668    }
    669    if (fields == nullptr) {
    670        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
    671        status = U_MEMORY_ALLOCATION_ERROR;
    672        appendTo.setToBogus();
    673        return appendTo;
    674    }
    675    UFormattedNumberData output;
    676    output.quantity.setToDecNumber(number, status);
    677    fields->formatter.formatImpl(&output, status);
    678    fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
    679    auto appendable = UnicodeStringAppendable(appendTo);
    680    output.appendTo(appendable, status);
    681    return appendTo;
    682 }
    683 
    684 UnicodeString& DecimalFormat::format(const DecimalQuantity& number, UnicodeString& appendTo,
    685                                     FieldPositionIterator* posIter, UErrorCode& status) const {
    686    if (U_FAILURE(status)) {
    687        return appendTo; // don't overwrite status if it's already a failure.
    688    }
    689    if (fields == nullptr) {
    690        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
    691        status = U_MEMORY_ALLOCATION_ERROR;
    692        appendTo.setToBogus();
    693        return appendTo;
    694    }
    695    UFormattedNumberData output;
    696    output.quantity = number;
    697    fields->formatter.formatImpl(&output, status);
    698    fieldPositionIteratorHelper(output, posIter, appendTo.length(), status);
    699    auto appendable = UnicodeStringAppendable(appendTo);
    700    output.appendTo(appendable, status);
    701    return appendTo;
    702 }
    703 
    704 UnicodeString&
    705 DecimalFormat::format(const DecimalQuantity& number, UnicodeString& appendTo, FieldPosition& pos,
    706                      UErrorCode& status) const {
    707    if (U_FAILURE(status)) {
    708        return appendTo; // don't overwrite status if it's already a failure.
    709    }
    710    if (fields == nullptr) {
    711        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
    712        status = U_MEMORY_ALLOCATION_ERROR;
    713        appendTo.setToBogus();
    714        return appendTo;
    715    }
    716    UFormattedNumberData output;
    717    output.quantity = number;
    718    fields->formatter.formatImpl(&output, status);
    719    fieldPositionHelper(output, pos, appendTo.length(), status);
    720    auto appendable = UnicodeStringAppendable(appendTo);
    721    output.appendTo(appendable, status);
    722    return appendTo;
    723 }
    724 
    725 void DecimalFormat::parse(const UnicodeString& text, Formattable& output,
    726                          ParsePosition& parsePosition) const {
    727    if (fields == nullptr) {
    728        return;
    729    }
    730    if (parsePosition.getIndex() < 0 || parsePosition.getIndex() >= text.length()) {
    731        if (parsePosition.getIndex() == text.length()) {
    732            // If there is nothing to parse, it is an error
    733            parsePosition.setErrorIndex(parsePosition.getIndex());
    734        }
    735        return;
    736    }
    737 
    738    ErrorCode status;
    739    ParsedNumber result;
    740    // Note: if this is a currency instance, currencies will be matched despite the fact that we are not in the
    741    // parseCurrency method (backwards compatibility)
    742    int32_t startIndex = parsePosition.getIndex();
    743    const NumberParserImpl* parser = getParser(status);
    744    if (U_FAILURE(status)) {
    745        return; // unfortunately no way to report back the error.
    746    }
    747    parser->parse(text, startIndex, true, result, status);
    748    if (U_FAILURE(status)) {
    749        return; // unfortunately no way to report back the error.
    750    }
    751    // TODO: Do we need to check for fImpl->properties->parseAllInput (UCONFIG_HAVE_PARSEALLINPUT) here?
    752    if (result.success()) {
    753        parsePosition.setIndex(result.charEnd);
    754        result.populateFormattable(output, parser->getParseFlags());
    755    } else {
    756        parsePosition.setErrorIndex(startIndex + result.charEnd);
    757    }
    758 }
    759 
    760 CurrencyAmount* DecimalFormat::parseCurrency(const UnicodeString& text, ParsePosition& parsePosition) const {
    761    if (fields == nullptr) {
    762        return nullptr;
    763    }
    764    if (parsePosition.getIndex() < 0 || parsePosition.getIndex() >= text.length()) {
    765        return nullptr;
    766    }
    767 
    768    ErrorCode status;
    769    ParsedNumber result;
    770    // Note: if this is a currency instance, currencies will be matched despite the fact that we are not in the
    771    // parseCurrency method (backwards compatibility)
    772    int32_t startIndex = parsePosition.getIndex();
    773    const NumberParserImpl* parser = getCurrencyParser(status);
    774    if (U_FAILURE(status)) {
    775        return nullptr;
    776    }
    777    parser->parse(text, startIndex, true, result, status);
    778    if (U_FAILURE(status)) {
    779        return nullptr;
    780    }
    781    // TODO: Do we need to check for fImpl->properties->parseAllInput (UCONFIG_HAVE_PARSEALLINPUT) here?
    782    if (result.success()) {
    783        parsePosition.setIndex(result.charEnd);
    784        Formattable formattable;
    785        result.populateFormattable(formattable, parser->getParseFlags());
    786        LocalPointer<CurrencyAmount> currencyAmount(
    787            new CurrencyAmount(formattable, result.currencyCode, status), status);
    788        if (U_FAILURE(status)) {
    789            return nullptr;
    790        }
    791        return currencyAmount.orphan();
    792    } else {
    793        parsePosition.setErrorIndex(startIndex + result.charEnd);
    794        return nullptr;
    795    }
    796 }
    797 
    798 const DecimalFormatSymbols* DecimalFormat::getDecimalFormatSymbols() const {
    799    if (fields == nullptr) {
    800        return nullptr;
    801    }
    802    if (!fields->symbols.isNull()) {
    803        return fields->symbols.getAlias();
    804    } else {
    805        return fields->formatter.getDecimalFormatSymbols();
    806    }
    807 }
    808 
    809 void DecimalFormat::adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt) {
    810    if (symbolsToAdopt == nullptr) {
    811        return; // do not allow caller to set fields->symbols to nullptr
    812    }
    813    // we must take ownership of symbolsToAdopt, even in a failure case.
    814    LocalPointer<DecimalFormatSymbols> dfs(symbolsToAdopt);
    815    if (fields == nullptr) {
    816        return;
    817    }
    818    fields->symbols.adoptInstead(dfs.orphan());
    819    touchNoError();
    820 }
    821 
    822 void DecimalFormat::setDecimalFormatSymbols(const DecimalFormatSymbols& symbols) {
    823    if (fields == nullptr) {
    824        return;
    825    }
    826    UErrorCode status = U_ZERO_ERROR;
    827    LocalPointer<DecimalFormatSymbols> dfs(new DecimalFormatSymbols(symbols), status);
    828    if (U_FAILURE(status)) {
    829        // We failed to allocate DecimalFormatSymbols, release fields and its members.
    830        // We must have a fully complete fields object, we cannot have partially populated members.
    831        delete fields;
    832        fields = nullptr;
    833        return;
    834    }
    835    fields->symbols.adoptInstead(dfs.orphan());
    836    touchNoError();
    837 }
    838 
    839 const CurrencyPluralInfo* DecimalFormat::getCurrencyPluralInfo() const {
    840    if (fields == nullptr) {
    841        return nullptr;
    842    }
    843    return fields->properties.currencyPluralInfo.fPtr.getAlias();
    844 }
    845 
    846 void DecimalFormat::adoptCurrencyPluralInfo(CurrencyPluralInfo* toAdopt) {
    847    // TODO: should we guard against nullptr input, like in adoptDecimalFormatSymbols?
    848    // we must take ownership of toAdopt, even in a failure case.
    849    LocalPointer<CurrencyPluralInfo> cpi(toAdopt);
    850    if (fields == nullptr) {
    851        return;
    852    }
    853    fields->properties.currencyPluralInfo.fPtr.adoptInstead(cpi.orphan());
    854    touchNoError();
    855 }
    856 
    857 void DecimalFormat::setCurrencyPluralInfo(const CurrencyPluralInfo& info) {
    858    if (fields == nullptr) {
    859        return;
    860    }
    861    if (fields->properties.currencyPluralInfo.fPtr.isNull()) {
    862        // Note: clone() can fail with OOM error, but we have no way to report it. :(
    863        fields->properties.currencyPluralInfo.fPtr.adoptInstead(info.clone());
    864    } else {
    865        *fields->properties.currencyPluralInfo.fPtr = info; // copy-assignment operator
    866    }
    867    touchNoError();
    868 }
    869 
    870 UnicodeString& DecimalFormat::getPositivePrefix(UnicodeString& result) const {
    871    if (fields == nullptr) {
    872        result.setToBogus();
    873        return result;
    874    }
    875    UErrorCode status = U_ZERO_ERROR;
    876    fields->formatter.getAffixImpl(true, false, result, status);
    877    if (U_FAILURE(status)) { result.setToBogus(); }
    878    return result;
    879 }
    880 
    881 void DecimalFormat::setPositivePrefix(const UnicodeString& newValue) {
    882    if (fields == nullptr) {
    883        return;
    884    }
    885    if (newValue == fields->properties.positivePrefix) { return; }
    886    fields->properties.positivePrefix = newValue;
    887    touchNoError();
    888 }
    889 
    890 UnicodeString& DecimalFormat::getNegativePrefix(UnicodeString& result) const {
    891    if (fields == nullptr) {
    892        result.setToBogus();
    893        return result;
    894    }
    895    UErrorCode status = U_ZERO_ERROR;
    896    fields->formatter.getAffixImpl(true, true, result, status);
    897    if (U_FAILURE(status)) { result.setToBogus(); }
    898    return result;
    899 }
    900 
    901 void DecimalFormat::setNegativePrefix(const UnicodeString& newValue) {
    902    if (fields == nullptr) {
    903        return;
    904    }
    905    if (newValue == fields->properties.negativePrefix) { return; }
    906    fields->properties.negativePrefix = newValue;
    907    touchNoError();
    908 }
    909 
    910 UnicodeString& DecimalFormat::getPositiveSuffix(UnicodeString& result) const {
    911    if (fields == nullptr) {
    912        result.setToBogus();
    913        return result;
    914    }
    915    UErrorCode status = U_ZERO_ERROR;
    916    fields->formatter.getAffixImpl(false, false, result, status);
    917    if (U_FAILURE(status)) { result.setToBogus(); }
    918    return result;
    919 }
    920 
    921 void DecimalFormat::setPositiveSuffix(const UnicodeString& newValue) {
    922    if (fields == nullptr) {
    923        return;
    924    }
    925    if (newValue == fields->properties.positiveSuffix) { return; }
    926    fields->properties.positiveSuffix = newValue;
    927    touchNoError();
    928 }
    929 
    930 UnicodeString& DecimalFormat::getNegativeSuffix(UnicodeString& result) const {
    931    if (fields == nullptr) {
    932        result.setToBogus();
    933        return result;
    934    }
    935    UErrorCode status = U_ZERO_ERROR;
    936    fields->formatter.getAffixImpl(false, true, result, status);
    937    if (U_FAILURE(status)) { result.setToBogus(); }
    938    return result;
    939 }
    940 
    941 void DecimalFormat::setNegativeSuffix(const UnicodeString& newValue) {
    942    if (fields == nullptr) {
    943        return;
    944    }
    945    if (newValue == fields->properties.negativeSuffix) { return; }
    946    fields->properties.negativeSuffix = newValue;
    947    touchNoError();
    948 }
    949 
    950 UBool DecimalFormat::isSignAlwaysShown() const {
    951    // Not much we can do to report an error.
    952    if (fields == nullptr) {
    953        return DecimalFormatProperties::getDefault().signAlwaysShown;
    954    }
    955    return fields->properties.signAlwaysShown;
    956 }
    957 
    958 void DecimalFormat::setSignAlwaysShown(UBool value) {
    959    if (fields == nullptr) { return; }
    960    if (UBOOL_TO_BOOL(value) == fields->properties.signAlwaysShown) { return; }
    961    fields->properties.signAlwaysShown = value;
    962    touchNoError();
    963 }
    964 
    965 int32_t DecimalFormat::getMultiplier() const {
    966    const DecimalFormatProperties *dfp;
    967    // Not much we can do to report an error.
    968    if (fields == nullptr) {
    969        // Fallback to using the default instance of DecimalFormatProperties.
    970        dfp = &(DecimalFormatProperties::getDefault());
    971    } else {
    972        dfp = &fields->properties;
    973    }
    974    if (dfp->multiplier != 1) {
    975        return dfp->multiplier;
    976    } else if (dfp->magnitudeMultiplier != 0) {
    977        return static_cast<int32_t>(uprv_pow10(dfp->magnitudeMultiplier));
    978    } else {
    979        return 1;
    980    }
    981 }
    982 
    983 void DecimalFormat::setMultiplier(int32_t multiplier) {
    984    if (fields == nullptr) {
    985         return;
    986    }
    987    if (multiplier == 0) {
    988        multiplier = 1;     // one being the benign default value for a multiplier.
    989    }
    990 
    991    // Try to convert to a magnitude multiplier first
    992    int delta = 0;
    993    int value = multiplier;
    994    while (value != 1) {
    995        delta++;
    996        int temp = value / 10;
    997        if (temp * 10 != value) {
    998            delta = -1;
    999            break;
   1000        }
   1001        value = temp;
   1002    }
   1003    if (delta != -1) {
   1004        fields->properties.magnitudeMultiplier = delta;
   1005        fields->properties.multiplier = 1;
   1006    } else {
   1007        fields->properties.magnitudeMultiplier = 0;
   1008        fields->properties.multiplier = multiplier;
   1009    }
   1010    touchNoError();
   1011 }
   1012 
   1013 int32_t DecimalFormat::getMultiplierScale() const {
   1014    // Not much we can do to report an error.
   1015    if (fields == nullptr) {
   1016        // Fallback to using the default instance of DecimalFormatProperties.
   1017        return DecimalFormatProperties::getDefault().multiplierScale;
   1018    }
   1019    return fields->properties.multiplierScale;
   1020 }
   1021 
   1022 void DecimalFormat::setMultiplierScale(int32_t newValue) {
   1023    if (fields == nullptr) { return; }
   1024    if (newValue == fields->properties.multiplierScale) { return; }
   1025    fields->properties.multiplierScale = newValue;
   1026    touchNoError();
   1027 }
   1028 
   1029 double DecimalFormat::getRoundingIncrement() const {
   1030    // Not much we can do to report an error.
   1031    if (fields == nullptr) {
   1032        // Fallback to using the default instance of DecimalFormatProperties.
   1033        return DecimalFormatProperties::getDefault().roundingIncrement;
   1034    }
   1035    return fields->exportedProperties.roundingIncrement;
   1036 }
   1037 
   1038 void DecimalFormat::setRoundingIncrement(double newValue) {
   1039    if (fields == nullptr) { return; }
   1040    if (newValue == fields->properties.roundingIncrement) { return; }
   1041    fields->properties.roundingIncrement = newValue;
   1042    touchNoError();
   1043 }
   1044 
   1045 ERoundingMode DecimalFormat::getRoundingMode() const {
   1046    // Not much we can do to report an error.
   1047    if (fields == nullptr) {
   1048        // Fallback to using the default instance of DecimalFormatProperties.
   1049        return static_cast<ERoundingMode>(DecimalFormatProperties::getDefault().roundingMode.getNoError());
   1050    }
   1051    // UNumberFormatRoundingMode and ERoundingMode have the same values.
   1052    return static_cast<ERoundingMode>(fields->exportedProperties.roundingMode.getNoError());
   1053 }
   1054 
   1055 void DecimalFormat::setRoundingMode(ERoundingMode roundingMode) UPRV_NO_SANITIZE_UNDEFINED {
   1056    if (fields == nullptr) { return; }
   1057    auto uRoundingMode = static_cast<UNumberFormatRoundingMode>(roundingMode);
   1058    if (!fields->properties.roundingMode.isNull() && uRoundingMode == fields->properties.roundingMode.getNoError()) {
   1059        return;
   1060    }
   1061    NumberFormat::setMaximumIntegerDigits(roundingMode); // to set field for compatibility
   1062    fields->properties.roundingMode = uRoundingMode;
   1063    touchNoError();
   1064 }
   1065 
   1066 int32_t DecimalFormat::getFormatWidth() const {
   1067    // Not much we can do to report an error.
   1068    if (fields == nullptr) {
   1069        // Fallback to using the default instance of DecimalFormatProperties.
   1070        return DecimalFormatProperties::getDefault().formatWidth;
   1071    }
   1072    return fields->properties.formatWidth;
   1073 }
   1074 
   1075 void DecimalFormat::setFormatWidth(int32_t width) {
   1076    if (fields == nullptr) { return; }
   1077    if (width == fields->properties.formatWidth) { return; }
   1078    fields->properties.formatWidth = width;
   1079    touchNoError();
   1080 }
   1081 
   1082 UnicodeString DecimalFormat::getPadCharacterString() const {
   1083    if (fields == nullptr || fields->properties.padString.isBogus()) {
   1084        // Readonly-alias the static string kFallbackPaddingString
   1085        return {true, kFallbackPaddingString, -1};
   1086    } else {
   1087        return fields->properties.padString;
   1088    }
   1089 }
   1090 
   1091 void DecimalFormat::setPadCharacter(const UnicodeString& padChar) {
   1092    if (fields == nullptr) { return; }
   1093    if (padChar == fields->properties.padString) { return; }
   1094    if (padChar.length() > 0) {
   1095        fields->properties.padString = UnicodeString(padChar.char32At(0));
   1096    } else {
   1097        fields->properties.padString.setToBogus();
   1098    }
   1099    touchNoError();
   1100 }
   1101 
   1102 EPadPosition DecimalFormat::getPadPosition() const {
   1103    if (fields == nullptr || fields->properties.padPosition.isNull()) {
   1104        return EPadPosition::kPadBeforePrefix;
   1105    } else {
   1106        // UNumberFormatPadPosition and EPadPosition have the same values.
   1107        return static_cast<EPadPosition>(fields->properties.padPosition.getNoError());
   1108    }
   1109 }
   1110 
   1111 void DecimalFormat::setPadPosition(EPadPosition padPos) {
   1112    if (fields == nullptr) { return; }
   1113    auto uPadPos = static_cast<UNumberFormatPadPosition>(padPos);
   1114    if (!fields->properties.padPosition.isNull() && uPadPos == fields->properties.padPosition.getNoError()) {
   1115        return;
   1116    }
   1117    fields->properties.padPosition = uPadPos;
   1118    touchNoError();
   1119 }
   1120 
   1121 UBool DecimalFormat::isScientificNotation() const {
   1122    // Not much we can do to report an error.
   1123    if (fields == nullptr) {
   1124        // Fallback to using the default instance of DecimalFormatProperties.
   1125        return (DecimalFormatProperties::getDefault().minimumExponentDigits != -1);
   1126    }
   1127    return (fields->properties.minimumExponentDigits != -1);
   1128 }
   1129 
   1130 void DecimalFormat::setScientificNotation(UBool useScientific) {
   1131    if (fields == nullptr) { return; }
   1132    int32_t minExp = useScientific ? 1 : -1;
   1133    if (fields->properties.minimumExponentDigits == minExp) { return; }
   1134    if (useScientific) {
   1135        fields->properties.minimumExponentDigits = 1;
   1136    } else {
   1137        fields->properties.minimumExponentDigits = -1;
   1138    }
   1139    touchNoError();
   1140 }
   1141 
   1142 int8_t DecimalFormat::getMinimumExponentDigits() const {
   1143    // Not much we can do to report an error.
   1144    if (fields == nullptr) {
   1145        // Fallback to using the default instance of DecimalFormatProperties.
   1146        return static_cast<int8_t>(DecimalFormatProperties::getDefault().minimumExponentDigits);
   1147    }
   1148    return static_cast<int8_t>(fields->properties.minimumExponentDigits);
   1149 }
   1150 
   1151 void DecimalFormat::setMinimumExponentDigits(int8_t minExpDig) {
   1152    if (fields == nullptr) { return; }
   1153    if (minExpDig == fields->properties.minimumExponentDigits) { return; }
   1154    fields->properties.minimumExponentDigits = minExpDig;
   1155    touchNoError();
   1156 }
   1157 
   1158 UBool DecimalFormat::isExponentSignAlwaysShown() const {
   1159    // Not much we can do to report an error.
   1160    if (fields == nullptr) {
   1161        // Fallback to using the default instance of DecimalFormatProperties.
   1162        return DecimalFormatProperties::getDefault().exponentSignAlwaysShown;
   1163    }
   1164    return fields->properties.exponentSignAlwaysShown;
   1165 }
   1166 
   1167 void DecimalFormat::setExponentSignAlwaysShown(UBool expSignAlways) {
   1168    if (fields == nullptr) { return; }
   1169    if (UBOOL_TO_BOOL(expSignAlways) == fields->properties.exponentSignAlwaysShown) { return; }
   1170    fields->properties.exponentSignAlwaysShown = expSignAlways;
   1171    touchNoError();
   1172 }
   1173 
   1174 int32_t DecimalFormat::getGroupingSize() const {
   1175    int32_t groupingSize;
   1176    // Not much we can do to report an error.
   1177    if (fields == nullptr) {
   1178        // Fallback to using the default instance of DecimalFormatProperties.
   1179        groupingSize = DecimalFormatProperties::getDefault().groupingSize;
   1180    } else {
   1181        groupingSize = fields->properties.groupingSize;
   1182    }
   1183    if (groupingSize < 0) {
   1184        return 0;
   1185    }
   1186    return groupingSize;
   1187 }
   1188 
   1189 void DecimalFormat::setGroupingSize(int32_t newValue) {
   1190    if (fields == nullptr) { return; }
   1191    if (newValue == fields->properties.groupingSize) { return; }
   1192    fields->properties.groupingSize = newValue;
   1193    touchNoError();
   1194 }
   1195 
   1196 int32_t DecimalFormat::getSecondaryGroupingSize() const {
   1197    int32_t grouping2;
   1198    // Not much we can do to report an error.
   1199    if (fields == nullptr) {
   1200        // Fallback to using the default instance of DecimalFormatProperties.
   1201        grouping2 = DecimalFormatProperties::getDefault().secondaryGroupingSize;
   1202    } else {
   1203        grouping2 = fields->properties.secondaryGroupingSize;
   1204    }
   1205    if (grouping2 < 0) {
   1206        return 0;
   1207    }
   1208    return grouping2;
   1209 }
   1210 
   1211 void DecimalFormat::setSecondaryGroupingSize(int32_t newValue) {
   1212    if (fields == nullptr) { return; }
   1213    if (newValue == fields->properties.secondaryGroupingSize) { return; }
   1214    fields->properties.secondaryGroupingSize = newValue;
   1215    touchNoError();
   1216 }
   1217 
   1218 int32_t DecimalFormat::getMinimumGroupingDigits() const {
   1219    // Not much we can do to report an error.
   1220    if (fields == nullptr) {
   1221        // Fallback to using the default instance of DecimalFormatProperties.
   1222        return DecimalFormatProperties::getDefault().minimumGroupingDigits;
   1223    }
   1224    return fields->properties.minimumGroupingDigits;
   1225 }
   1226 
   1227 void DecimalFormat::setMinimumGroupingDigits(int32_t newValue) {
   1228    if (fields == nullptr) { return; }
   1229    if (newValue == fields->properties.minimumGroupingDigits) { return; }
   1230    fields->properties.minimumGroupingDigits = newValue;
   1231    touchNoError();
   1232 }
   1233 
   1234 UBool DecimalFormat::isDecimalSeparatorAlwaysShown() const {
   1235    // Not much we can do to report an error.
   1236    if (fields == nullptr) {
   1237        // Fallback to using the default instance of DecimalFormatProperties.
   1238        return DecimalFormatProperties::getDefault().decimalSeparatorAlwaysShown;
   1239    }
   1240    return fields->properties.decimalSeparatorAlwaysShown;
   1241 }
   1242 
   1243 void DecimalFormat::setDecimalSeparatorAlwaysShown(UBool newValue) {
   1244    if (fields == nullptr) { return; }
   1245    if (UBOOL_TO_BOOL(newValue) == fields->properties.decimalSeparatorAlwaysShown) { return; }
   1246    fields->properties.decimalSeparatorAlwaysShown = newValue;
   1247    touchNoError();
   1248 }
   1249 
   1250 UBool DecimalFormat::isDecimalPatternMatchRequired() const {
   1251    // Not much we can do to report an error.
   1252    if (fields == nullptr) {
   1253        // Fallback to using the default instance of DecimalFormatProperties.
   1254        return DecimalFormatProperties::getDefault().decimalPatternMatchRequired;
   1255    }
   1256    return fields->properties.decimalPatternMatchRequired;
   1257 }
   1258 
   1259 void DecimalFormat::setDecimalPatternMatchRequired(UBool newValue) {
   1260    if (fields == nullptr) { return; }
   1261    if (UBOOL_TO_BOOL(newValue) == fields->properties.decimalPatternMatchRequired) { return; }
   1262    fields->properties.decimalPatternMatchRequired = newValue;
   1263    touchNoError();
   1264 }
   1265 
   1266 UBool DecimalFormat::isParseNoExponent() const {
   1267    // Not much we can do to report an error.
   1268    if (fields == nullptr) {
   1269        // Fallback to using the default instance of DecimalFormatProperties.
   1270        return DecimalFormatProperties::getDefault().parseNoExponent;
   1271    }
   1272    return fields->properties.parseNoExponent;
   1273 }
   1274 
   1275 void DecimalFormat::setParseNoExponent(UBool value) {
   1276    if (fields == nullptr) { return; }
   1277    if (UBOOL_TO_BOOL(value) == fields->properties.parseNoExponent) { return; }
   1278    fields->properties.parseNoExponent = value;
   1279    touchNoError();
   1280 }
   1281 
   1282 UBool DecimalFormat::isParseCaseSensitive() const {
   1283    // Not much we can do to report an error.
   1284    if (fields == nullptr) {
   1285        // Fallback to using the default instance of DecimalFormatProperties.
   1286        return DecimalFormatProperties::getDefault().parseCaseSensitive;
   1287    }
   1288    return fields->properties.parseCaseSensitive;
   1289 }
   1290 
   1291 void DecimalFormat::setParseCaseSensitive(UBool value) {
   1292    if (fields == nullptr) { return; }
   1293    if (UBOOL_TO_BOOL(value) == fields->properties.parseCaseSensitive) { return; }
   1294    fields->properties.parseCaseSensitive = value;
   1295    touchNoError();
   1296 }
   1297 
   1298 UBool DecimalFormat::isFormatFailIfMoreThanMaxDigits() const {
   1299    // Not much we can do to report an error.
   1300    if (fields == nullptr) {
   1301        // Fallback to using the default instance of DecimalFormatProperties.
   1302        return DecimalFormatProperties::getDefault().formatFailIfMoreThanMaxDigits;
   1303    }
   1304    return fields->properties.formatFailIfMoreThanMaxDigits;
   1305 }
   1306 
   1307 void DecimalFormat::setFormatFailIfMoreThanMaxDigits(UBool value) {
   1308    if (fields == nullptr) { return; }
   1309    if (UBOOL_TO_BOOL(value) == fields->properties.formatFailIfMoreThanMaxDigits) { return; }
   1310    fields->properties.formatFailIfMoreThanMaxDigits = value;
   1311    touchNoError();
   1312 }
   1313 
   1314 UnicodeString& DecimalFormat::toPattern(UnicodeString& result) const {
   1315    if (fields == nullptr) {
   1316        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
   1317        result.setToBogus();
   1318        return result;
   1319    }
   1320    // Pull some properties from exportedProperties and others from properties
   1321    // to keep affix patterns intact.  In particular, pull rounding properties
   1322    // so that CurrencyUsage is reflected properly.
   1323    // TODO: Consider putting this logic in number_patternstring.cpp instead.
   1324    ErrorCode localStatus;
   1325    DecimalFormatProperties tprops(fields->properties);
   1326    bool useCurrency = (
   1327        !tprops.currency.isNull() ||
   1328        !tprops.currencyPluralInfo.fPtr.isNull() ||
   1329        !tprops.currencyUsage.isNull() ||
   1330        tprops.currencyAsDecimal ||
   1331        AffixUtils::hasCurrencySymbols(tprops.positivePrefixPattern, localStatus) ||
   1332        AffixUtils::hasCurrencySymbols(tprops.positiveSuffixPattern, localStatus) ||
   1333        AffixUtils::hasCurrencySymbols(tprops.negativePrefixPattern, localStatus) ||
   1334        AffixUtils::hasCurrencySymbols(tprops.negativeSuffixPattern, localStatus));
   1335    if (useCurrency) {
   1336        tprops.minimumFractionDigits = fields->exportedProperties.minimumFractionDigits;
   1337        tprops.maximumFractionDigits = fields->exportedProperties.maximumFractionDigits;
   1338        tprops.roundingIncrement = fields->exportedProperties.roundingIncrement;
   1339    }
   1340    result = PatternStringUtils::propertiesToPatternString(tprops, localStatus);
   1341    return result;
   1342 }
   1343 
   1344 UnicodeString& DecimalFormat::toLocalizedPattern(UnicodeString& result) const {
   1345    if (fields == nullptr) {
   1346        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
   1347        result.setToBogus();
   1348        return result;
   1349    }
   1350    ErrorCode localStatus;
   1351    result = toPattern(result);
   1352    result = PatternStringUtils::convertLocalized(result, *getDecimalFormatSymbols(), true, localStatus);
   1353    return result;
   1354 }
   1355 
   1356 void DecimalFormat::applyPattern(const UnicodeString& pattern, UParseError&, UErrorCode& status) {
   1357    // TODO: What is parseError for?
   1358    applyPattern(pattern, status);
   1359 }
   1360 
   1361 void DecimalFormat::applyPattern(const UnicodeString& pattern, 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 happened during construction, copy construction, assignment, or modification.
   1366        status = U_MEMORY_ALLOCATION_ERROR;
   1367        return;
   1368    }
   1369    setPropertiesFromPattern(pattern, IGNORE_ROUNDING_NEVER, status);
   1370    touch(status);
   1371 }
   1372 
   1373 void DecimalFormat::applyLocalizedPattern(const UnicodeString& localizedPattern, UParseError&,
   1374                                          UErrorCode& status) {
   1375    // TODO: What is parseError for?
   1376    applyLocalizedPattern(localizedPattern, status);
   1377 }
   1378 
   1379 void DecimalFormat::applyLocalizedPattern(const UnicodeString& localizedPattern, UErrorCode& status) {
   1380    // don't overwrite status if it's already a failure.
   1381    if (U_FAILURE(status)) { return; }
   1382    if (fields == nullptr) {
   1383        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
   1384        status = U_MEMORY_ALLOCATION_ERROR;
   1385        return;
   1386    }
   1387    UnicodeString pattern = PatternStringUtils::convertLocalized(
   1388            localizedPattern, *getDecimalFormatSymbols(), false, status);
   1389    applyPattern(pattern, status);
   1390 }
   1391 
   1392 void DecimalFormat::setMaximumIntegerDigits(int32_t newValue) {
   1393    if (fields == nullptr) { return; }
   1394    if (newValue == fields->properties.maximumIntegerDigits) { return; }
   1395    // For backwards compatibility, conflicting min/max need to keep the most recent setting.
   1396    int32_t min = fields->properties.minimumIntegerDigits;
   1397    if (min >= 0 && min > newValue) {
   1398        fields->properties.minimumIntegerDigits = newValue;
   1399    }
   1400    fields->properties.maximumIntegerDigits = newValue;
   1401    touchNoError();
   1402 }
   1403 
   1404 void DecimalFormat::setMinimumIntegerDigits(int32_t newValue) {
   1405    if (fields == nullptr) { return; }
   1406    if (newValue == fields->properties.minimumIntegerDigits) { return; }
   1407    // For backwards compatibility, conflicting min/max need to keep the most recent setting.
   1408    int32_t max = fields->properties.maximumIntegerDigits;
   1409    if (max >= 0 && max < newValue) {
   1410        fields->properties.maximumIntegerDigits = newValue;
   1411    }
   1412    fields->properties.minimumIntegerDigits = newValue;
   1413    touchNoError();
   1414 }
   1415 
   1416 void DecimalFormat::setMaximumFractionDigits(int32_t newValue) {
   1417    if (fields == nullptr) { return; }
   1418    if (newValue == fields->properties.maximumFractionDigits) { return; }
   1419    // cap for backward compatibility, formerly 340, now 999
   1420    if (newValue > kMaxIntFracSig) {
   1421        newValue = kMaxIntFracSig;
   1422    }
   1423    // For backwards compatibility, conflicting min/max need to keep the most recent setting.
   1424    int32_t min = fields->properties.minimumFractionDigits;
   1425    if (min >= 0 && min > newValue) {
   1426        fields->properties.minimumFractionDigits = newValue;
   1427    }
   1428    fields->properties.maximumFractionDigits = newValue;
   1429    touchNoError();
   1430 }
   1431 
   1432 void DecimalFormat::setMinimumFractionDigits(int32_t newValue) {
   1433    if (fields == nullptr) { return; }
   1434    if (newValue == fields->properties.minimumFractionDigits) { return; }
   1435    // For backwards compatibility, conflicting min/max need to keep the most recent setting.
   1436    int32_t max = fields->properties.maximumFractionDigits;
   1437    if (max >= 0 && max < newValue) {
   1438        fields->properties.maximumFractionDigits = newValue;
   1439    }
   1440    fields->properties.minimumFractionDigits = newValue;
   1441    touchNoError();
   1442 }
   1443 
   1444 int32_t DecimalFormat::getMinimumSignificantDigits() const {
   1445    // Not much we can do to report an error.
   1446    if (fields == nullptr) {
   1447        // Fallback to using the default instance of DecimalFormatProperties.
   1448        return DecimalFormatProperties::getDefault().minimumSignificantDigits;
   1449    }
   1450    return fields->exportedProperties.minimumSignificantDigits;
   1451 }
   1452 
   1453 int32_t DecimalFormat::getMaximumSignificantDigits() const {
   1454    // Not much we can do to report an error.
   1455    if (fields == nullptr) {
   1456        // Fallback to using the default instance of DecimalFormatProperties.
   1457        return DecimalFormatProperties::getDefault().maximumSignificantDigits;
   1458    }
   1459    return fields->exportedProperties.maximumSignificantDigits;
   1460 }
   1461 
   1462 void DecimalFormat::setMinimumSignificantDigits(int32_t value) {
   1463    if (fields == nullptr) { return; }
   1464    if (value == fields->properties.minimumSignificantDigits) { return; }
   1465    int32_t max = fields->properties.maximumSignificantDigits;
   1466    if (max >= 0 && max < value) {
   1467        fields->properties.maximumSignificantDigits = value;
   1468    }
   1469    fields->properties.minimumSignificantDigits = value;
   1470    touchNoError();
   1471 }
   1472 
   1473 void DecimalFormat::setMaximumSignificantDigits(int32_t value) {
   1474    if (fields == nullptr) { return; }
   1475    if (value == fields->properties.maximumSignificantDigits) { return; }
   1476    int32_t min = fields->properties.minimumSignificantDigits;
   1477    if (min >= 0 && min > value) {
   1478        fields->properties.minimumSignificantDigits = value;
   1479    }
   1480    fields->properties.maximumSignificantDigits = value;
   1481    touchNoError();
   1482 }
   1483 
   1484 UBool DecimalFormat::areSignificantDigitsUsed() const {
   1485    const DecimalFormatProperties* dfp;
   1486    // Not much we can do to report an error.
   1487    if (fields == nullptr) {
   1488        // Fallback to using the default instance of DecimalFormatProperties.
   1489        dfp = &(DecimalFormatProperties::getDefault());
   1490    } else {
   1491        dfp = &fields->properties;
   1492    }
   1493    return dfp->minimumSignificantDigits != -1 || dfp->maximumSignificantDigits != -1;    
   1494 }
   1495 
   1496 void DecimalFormat::setSignificantDigitsUsed(UBool useSignificantDigits) {
   1497    if (fields == nullptr) { return; }
   1498    
   1499    // These are the default values from the old implementation.
   1500    if (useSignificantDigits) {
   1501        if (fields->properties.minimumSignificantDigits != -1 ||
   1502            fields->properties.maximumSignificantDigits != -1) {
   1503            return;
   1504        }
   1505    } else {
   1506        if (fields->properties.minimumSignificantDigits == -1 &&
   1507            fields->properties.maximumSignificantDigits == -1) {
   1508            return;
   1509        }
   1510    }
   1511    int32_t minSig = useSignificantDigits ? 1 : -1;
   1512    int32_t maxSig = useSignificantDigits ? 6 : -1;
   1513    fields->properties.minimumSignificantDigits = minSig;
   1514    fields->properties.maximumSignificantDigits = maxSig;
   1515    touchNoError();
   1516 }
   1517 
   1518 void DecimalFormat::setCurrency(const char16_t* theCurrency, UErrorCode& ec) {
   1519    // don't overwrite ec if it's already a failure.
   1520    if (U_FAILURE(ec)) { return; }
   1521    if (fields == nullptr) {
   1522        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
   1523        ec = U_MEMORY_ALLOCATION_ERROR;
   1524        return;
   1525    }
   1526    CurrencyUnit currencyUnit(theCurrency, ec);
   1527    if (U_FAILURE(ec)) { return; }
   1528    if (!fields->properties.currency.isNull() && fields->properties.currency.getNoError() == currencyUnit) {
   1529        return;
   1530    }
   1531    NumberFormat::setCurrency(theCurrency, ec); // to set field for compatibility
   1532    fields->properties.currency = currencyUnit;
   1533    // In Java, the DecimalFormatSymbols is mutable. Why not in C++?
   1534    LocalPointer<DecimalFormatSymbols> newSymbols(new DecimalFormatSymbols(*getDecimalFormatSymbols()), ec);
   1535    newSymbols->setCurrency(currencyUnit.getISOCurrency(), ec);
   1536    fields->symbols.adoptInsteadAndCheckErrorCode(newSymbols.orphan(), ec);
   1537    touch(ec);
   1538 }
   1539 
   1540 void DecimalFormat::setCurrency(const char16_t* theCurrency) {
   1541    ErrorCode localStatus;
   1542    setCurrency(theCurrency, localStatus);
   1543 }
   1544 
   1545 void DecimalFormat::setCurrencyUsage(UCurrencyUsage newUsage, UErrorCode* ec) {
   1546    // don't overwrite ec if it's already a failure.
   1547    if (U_FAILURE(*ec)) { return; }
   1548    if (fields == nullptr) {
   1549        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
   1550        *ec = U_MEMORY_ALLOCATION_ERROR;
   1551        return;
   1552    }
   1553    if (!fields->properties.currencyUsage.isNull() && newUsage == fields->properties.currencyUsage.getNoError()) {
   1554        return;
   1555    }
   1556    fields->properties.currencyUsage = newUsage;
   1557    touch(*ec);
   1558 }
   1559 
   1560 UCurrencyUsage DecimalFormat::getCurrencyUsage() const {
   1561    // CurrencyUsage is not exported, so we have to get it from the input property bag.
   1562    // TODO: Should we export CurrencyUsage instead?
   1563    if (fields == nullptr || fields->properties.currencyUsage.isNull()) {
   1564        return UCURR_USAGE_STANDARD;
   1565    }
   1566    return fields->properties.currencyUsage.getNoError();
   1567 }
   1568 
   1569 void
   1570 DecimalFormat::formatToDecimalQuantity(double number, DecimalQuantity& output, UErrorCode& status) const {
   1571    // don't overwrite status if it's already a failure.
   1572    if (U_FAILURE(status)) { return; }
   1573    if (fields == nullptr) {
   1574        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
   1575        status = U_MEMORY_ALLOCATION_ERROR;
   1576        return;
   1577    }
   1578    fields->formatter.formatDouble(number, status).getDecimalQuantity(output, status);
   1579 }
   1580 
   1581 void DecimalFormat::formatToDecimalQuantity(const Formattable& number, DecimalQuantity& output,
   1582                                            UErrorCode& status) const {
   1583    // don't overwrite status if it's already a failure.
   1584    if (U_FAILURE(status)) { return; }
   1585    if (fields == nullptr) {
   1586        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
   1587        status = U_MEMORY_ALLOCATION_ERROR;
   1588        return;
   1589    }
   1590    UFormattedNumberData obj;
   1591    number.populateDecimalQuantity(obj.quantity, status);
   1592    fields->formatter.formatImpl(&obj, status);
   1593    output = std::move(obj.quantity);
   1594 }
   1595 
   1596 const number::LocalizedNumberFormatter* DecimalFormat::toNumberFormatter(UErrorCode& status) const {
   1597    // We sometimes need to return nullptr here (see ICU-20380)
   1598    if (U_FAILURE(status)) { return nullptr; }
   1599    if (fields == nullptr) {
   1600        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
   1601        status = U_MEMORY_ALLOCATION_ERROR;
   1602        return nullptr;
   1603    }
   1604    return &fields->formatter;
   1605 }
   1606 
   1607 /** Rebuilds the formatter object from the property bag. */
   1608 void DecimalFormat::touch(UErrorCode& status) {
   1609    if (U_FAILURE(status)) {
   1610        return;
   1611    }
   1612    if (fields == nullptr) {
   1613        // We only get here if an OOM error happened during construction, copy construction, assignment, or modification.
   1614        // For regular construction, the caller should have checked the status variable for errors.
   1615        // For copy construction, there is unfortunately nothing to report the error, so we need to guard against
   1616        // this possible bad state here and set the status to an error.
   1617        status = U_MEMORY_ALLOCATION_ERROR;
   1618        return;
   1619    }
   1620 
   1621    // In C++, fields->symbols (or, if it's null, the DecimalFormatSymbols owned by the underlying LocalizedNumberFormatter)
   1622    // is the source of truth for the locale.
   1623    const DecimalFormatSymbols* symbols = getDecimalFormatSymbols();
   1624    Locale locale = symbols->getLocale();
   1625    
   1626    // Note: The formatter is relatively cheap to create, and we need it to populate fields->exportedProperties,
   1627    // so automatically recompute it here. The parser is a bit more expensive and is not needed until the
   1628    // parse method is called, so defer that until needed.
   1629    // TODO: Only update the pieces that changed instead of re-computing the whole formatter?
   1630 
   1631    // Since memory has already been allocated for the formatter, we can move assign a stack-allocated object
   1632    // and don't need to call new. (Which is slower and could possibly fail).
   1633    // [Note that "symbols" above might point to the DecimalFormatSymbols object owned by fields->formatter.
   1634    // That's okay, because NumberPropertyMapper::create() will clone it before fields->formatter's assignment
   1635    // operator deletes it.  But it does mean that "symbols" can't be counted on to be good after this line.]
   1636    fields->formatter = NumberPropertyMapper::create(
   1637        fields->properties, *symbols, fields->warehouse, fields->exportedProperties, status
   1638    ).locale(locale);
   1639    fields->symbols.adoptInstead(nullptr); // the fields->symbols property is only temporary, until we can copy it into a new LocalizedNumberFormatter
   1640    
   1641    // Do this after fields->exportedProperties are set up
   1642    setupFastFormat();
   1643 
   1644    // Delete the parsers if they were made previously
   1645 #ifndef __wasi__
   1646    delete fields->atomicParser.exchange(nullptr);
   1647    delete fields->atomicCurrencyParser.exchange(nullptr);
   1648 #else
   1649    delete fields->atomicParser;
   1650    delete fields->atomicCurrencyParser;
   1651 #endif
   1652 
   1653    // In order for the getters to work, we need to populate some fields in NumberFormat.
   1654    NumberFormat::setCurrency(fields->exportedProperties.currency.get(status).getISOCurrency(), status);
   1655    NumberFormat::setMaximumIntegerDigits(fields->exportedProperties.maximumIntegerDigits);
   1656    NumberFormat::setMinimumIntegerDigits(fields->exportedProperties.minimumIntegerDigits);
   1657    NumberFormat::setMaximumFractionDigits(fields->exportedProperties.maximumFractionDigits);
   1658    NumberFormat::setMinimumFractionDigits(fields->exportedProperties.minimumFractionDigits);
   1659    // fImpl->properties, not fields->exportedProperties, since this information comes from the pattern:
   1660    NumberFormat::setGroupingUsed(fields->properties.groupingUsed);
   1661 }
   1662 
   1663 void DecimalFormat::touchNoError() {
   1664    UErrorCode localStatus = U_ZERO_ERROR;
   1665    touch(localStatus);
   1666 }
   1667 
   1668 void DecimalFormat::setPropertiesFromPattern(const UnicodeString& pattern, int32_t ignoreRounding,
   1669                                             UErrorCode& status) {
   1670    if (U_SUCCESS(status)) {
   1671        // Cast workaround to get around putting the enum in the public header file
   1672        auto actualIgnoreRounding = static_cast<IgnoreRounding>(ignoreRounding);
   1673        PatternParser::parseToExistingProperties(pattern, fields->properties,  actualIgnoreRounding, status);
   1674    }
   1675 }
   1676 
   1677 const numparse::impl::NumberParserImpl* DecimalFormat::getParser(UErrorCode& status) const {
   1678    // TODO: Move this into umutex.h? (similar logic also in numrange_fluent.cpp)
   1679    // See ICU-20146
   1680 
   1681    if (U_FAILURE(status)) {
   1682        return nullptr;
   1683    }
   1684 
   1685    // First try to get the pre-computed parser
   1686 #ifndef __wasi__
   1687    auto* ptr = fields->atomicParser.load();
   1688 #else
   1689    auto* ptr = fields->atomicParser;
   1690 #endif
   1691    if (ptr != nullptr) {
   1692        return ptr;
   1693    }
   1694 
   1695    // Try computing the parser on our own
   1696    auto* temp = NumberParserImpl::createParserFromProperties(fields->properties, *getDecimalFormatSymbols(), false, status);
   1697    if (U_FAILURE(status)) {
   1698        return nullptr;
   1699    }
   1700    if (temp == nullptr) {
   1701        status = U_MEMORY_ALLOCATION_ERROR;
   1702        return nullptr;
   1703    }
   1704 
   1705    // Note: ptr starts as nullptr; during compare_exchange,
   1706    // it is set to what is actually stored in the atomic
   1707    // if another thread beat us to computing the parser object.
   1708    auto* nonConstThis = const_cast<DecimalFormat*>(this);
   1709 #ifndef __wasi__
   1710    if (!nonConstThis->fields->atomicParser.compare_exchange_strong(ptr, temp)) {
   1711        // Another thread beat us to computing the parser
   1712        delete temp;
   1713        return ptr;
   1714    } else {
   1715        // Our copy of the parser got stored in the atomic
   1716        return temp;
   1717    }
   1718 #else
   1719    nonConstThis->fields->atomicParser = temp;
   1720    return temp;
   1721 #endif
   1722 }
   1723 
   1724 const numparse::impl::NumberParserImpl* DecimalFormat::getCurrencyParser(UErrorCode& status) const {
   1725    if (U_FAILURE(status)) { return nullptr; }
   1726 
   1727    // First try to get the pre-computed parser
   1728 #ifndef __wasi__
   1729    auto* ptr = fields->atomicCurrencyParser.load();
   1730 #else
   1731    auto* ptr = fields->atomicCurrencyParser;
   1732 #endif
   1733    if (ptr != nullptr) {
   1734        return ptr;
   1735    }
   1736 
   1737    // Try computing the parser on our own
   1738    auto* temp = NumberParserImpl::createParserFromProperties(fields->properties, *getDecimalFormatSymbols(), true, status);
   1739    if (temp == nullptr) {
   1740        status = U_MEMORY_ALLOCATION_ERROR;
   1741        // although we may still dereference, call sites should be guarded
   1742    }
   1743 
   1744    // Note: ptr starts as nullptr; during compare_exchange, it is set to what is actually stored in the
   1745    // atomic if another thread beat us to computing the parser object.
   1746    auto* nonConstThis = const_cast<DecimalFormat*>(this);
   1747 #ifndef __wasi__
   1748    if (!nonConstThis->fields->atomicCurrencyParser.compare_exchange_strong(ptr, temp)) {
   1749        // Another thread beat us to computing the parser
   1750        delete temp;
   1751        return ptr;
   1752    } else {
   1753        // Our copy of the parser got stored in the atomic
   1754        return temp;
   1755    }
   1756 #else
   1757    nonConstThis->fields->atomicCurrencyParser = temp;
   1758    return temp;
   1759 #endif
   1760 }
   1761 
   1762 void
   1763 DecimalFormat::fieldPositionHelper(
   1764        const UFormattedNumberData& formatted,
   1765        FieldPosition& fieldPosition,
   1766        int32_t offset,
   1767        UErrorCode& status) {
   1768    if (U_FAILURE(status)) { return; }
   1769    // always return first occurrence:
   1770    fieldPosition.setBeginIndex(0);
   1771    fieldPosition.setEndIndex(0);
   1772    bool found = formatted.nextFieldPosition(fieldPosition, status);
   1773    if (found && offset != 0) {
   1774        FieldPositionOnlyHandler fpoh(fieldPosition);
   1775        fpoh.shiftLast(offset);
   1776    }
   1777 }
   1778 
   1779 void
   1780 DecimalFormat::fieldPositionIteratorHelper(
   1781        const UFormattedNumberData& formatted,
   1782        FieldPositionIterator* fpi,
   1783        int32_t offset,
   1784        UErrorCode& status) {
   1785    if (U_SUCCESS(status) && (fpi != nullptr)) {
   1786        FieldPositionIteratorHandler fpih(fpi, status);
   1787        fpih.setShift(offset);
   1788        formatted.getAllFieldPositions(fpih, status);
   1789    }
   1790 }
   1791 
   1792 // To debug fast-format, change void(x) to printf(x)
   1793 #define trace(x) void(x)
   1794 
   1795 void DecimalFormat::setupFastFormat() {
   1796    // Check the majority of properties:
   1797    if (!fields->properties.equalsDefaultExceptFastFormat()) {
   1798        trace("no fast format: equality\n");
   1799        fields->canUseFastFormat = false;
   1800        return;
   1801    }
   1802 
   1803    // Now check the remaining properties.
   1804    // Nontrivial affixes:
   1805    UBool trivialPP = fields->properties.positivePrefixPattern.isEmpty();
   1806    UBool trivialPS = fields->properties.positiveSuffixPattern.isEmpty();
   1807    UBool trivialNP = fields->properties.negativePrefixPattern.isBogus() || (
   1808            fields->properties.negativePrefixPattern.length() == 1 &&
   1809            fields->properties.negativePrefixPattern.charAt(0) == u'-');
   1810    UBool trivialNS = fields->properties.negativeSuffixPattern.isEmpty();
   1811    if (!trivialPP || !trivialPS || !trivialNP || !trivialNS) {
   1812        trace("no fast format: affixes\n");
   1813        fields->canUseFastFormat = false;
   1814        return;
   1815    }
   1816 
   1817    const DecimalFormatSymbols* symbols = getDecimalFormatSymbols();
   1818    
   1819    // Grouping (secondary grouping is forbidden in equalsDefaultExceptFastFormat):
   1820    bool groupingUsed = fields->properties.groupingUsed;
   1821    int32_t groupingSize = fields->properties.groupingSize;
   1822    bool unusualGroupingSize = groupingSize > 0 && groupingSize != 3;
   1823    const UnicodeString& groupingString = symbols->getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
   1824    if (groupingUsed && (unusualGroupingSize || groupingString.length() != 1)) {
   1825        trace("no fast format: grouping\n");
   1826        fields->canUseFastFormat = false;
   1827        return;
   1828    }
   1829 
   1830    // Integer length:
   1831    int32_t minInt = fields->exportedProperties.minimumIntegerDigits;
   1832    int32_t maxInt = fields->exportedProperties.maximumIntegerDigits;
   1833    // Fastpath supports up to only 10 digits (length of INT32_MIN)
   1834    if (minInt > 10) {
   1835        trace("no fast format: integer\n");
   1836        fields->canUseFastFormat = false;
   1837        return;
   1838    }
   1839 
   1840    // Fraction length (no fraction part allowed in fast path):
   1841    int32_t minFrac = fields->exportedProperties.minimumFractionDigits;
   1842    if (minFrac > 0) {
   1843        trace("no fast format: fraction\n");
   1844        fields->canUseFastFormat = false;
   1845        return;
   1846    }
   1847 
   1848    // Other symbols:
   1849    const UnicodeString& minusSignString = symbols->getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
   1850    UChar32 codePointZero = symbols->getCodePointZero();
   1851    if (minusSignString.length() != 1 || U16_LENGTH(codePointZero) != 1) {
   1852        trace("no fast format: symbols\n");
   1853        fields->canUseFastFormat = false;
   1854        return;
   1855    }
   1856 
   1857    // Good to go!
   1858    trace("can use fast format!\n");
   1859    fields->canUseFastFormat = true;
   1860    fields->fastData.cpZero = static_cast<char16_t>(codePointZero);
   1861    fields->fastData.cpGroupingSeparator = groupingUsed && groupingSize == 3 ? groupingString.charAt(0) : 0;
   1862    fields->fastData.cpMinusSign = minusSignString.charAt(0);
   1863    fields->fastData.minInt = (minInt < 0 || minInt > 127) ? 0 : static_cast<int8_t>(minInt);
   1864    fields->fastData.maxInt = (maxInt < 0 || maxInt > 127) ? 127 : static_cast<int8_t>(maxInt);
   1865 }
   1866 
   1867 bool DecimalFormat::fastFormatDouble(double input, UnicodeString& output) const {
   1868    if (!fields->canUseFastFormat) {
   1869        return false;
   1870    }
   1871    if (std::isnan(input)
   1872            || uprv_trunc(input) != input
   1873            || input <= INT32_MIN
   1874            || input > INT32_MAX) {
   1875        return false;
   1876    }
   1877    doFastFormatInt32(static_cast<int32_t>(input), std::signbit(input), output);
   1878    return true;
   1879 }
   1880 
   1881 bool DecimalFormat::fastFormatInt64(int64_t input, UnicodeString& output) const {
   1882    if (!fields->canUseFastFormat) {
   1883        return false;
   1884    }
   1885    if (input <= INT32_MIN || input > INT32_MAX) {
   1886        return false;
   1887    }
   1888    doFastFormatInt32(static_cast<int32_t>(input), input < 0, output);
   1889    return true;
   1890 }
   1891 
   1892 void DecimalFormat::doFastFormatInt32(int32_t input, bool isNegative, UnicodeString& output) const {
   1893    U_ASSERT(fields->canUseFastFormat);
   1894    if (isNegative) {
   1895        output.append(fields->fastData.cpMinusSign);
   1896        U_ASSERT(input != INT32_MIN);  // handled by callers
   1897        input = -input;
   1898    }
   1899    // Cap at int32_t to make the buffer small and operations fast.
   1900    // Longest string: "2,147,483,648" (13 chars in length)
   1901    static constexpr int32_t localCapacity = 13;
   1902    char16_t localBuffer[localCapacity];
   1903    char16_t* ptr = localBuffer + localCapacity;
   1904    int8_t group = 0;
   1905    int8_t minInt = (fields->fastData.minInt < 1)? 1: fields->fastData.minInt;
   1906    for (int8_t i = 0; i < fields->fastData.maxInt && (input != 0 || i < minInt); i++) {
   1907        if (group++ == 3 && fields->fastData.cpGroupingSeparator != 0) {
   1908            *(--ptr) = fields->fastData.cpGroupingSeparator;
   1909            group = 1;
   1910        }
   1911        std::div_t res = std::div(input, 10);
   1912        *(--ptr) = static_cast<char16_t>(fields->fastData.cpZero + res.rem);
   1913        input = res.quot;
   1914    }
   1915    int32_t len = localCapacity - static_cast<int32_t>(ptr - localBuffer);
   1916    output.append(ptr, len);
   1917 }
   1918 
   1919 
   1920 #endif /* #if !UCONFIG_NO_FORMATTING */