Coverage Report

Created: 2023-11-19 06:22

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