summaryrefslogtreecommitdiff
path: root/deps/icu-small/source/i18n/number_patternmodifier.cpp
blob: e182104c9116e7606cccd022cb3816ec0a7847f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// © 2017 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#include "unicode/utypes.h"

#if !UCONFIG_NO_FORMATTING && !UPRV_INCOMPLETE_CPP11_SUPPORT

#include "cstring.h"
#include "number_patternmodifier.h"
#include "unicode/dcfmtsym.h"
#include "unicode/ucurr.h"
#include "unicode/unistr.h"

using namespace icu;
using namespace icu::number;
using namespace icu::number::impl;

MutablePatternModifier::MutablePatternModifier(bool isStrong) : fStrong(isStrong) {}

void MutablePatternModifier::setPatternInfo(const AffixPatternProvider *patternInfo) {
    this->patternInfo = patternInfo;
}

void MutablePatternModifier::setPatternAttributes(UNumberSignDisplay signDisplay, bool perMille) {
    this->signDisplay = signDisplay;
    this->perMilleReplacesPercent = perMille;
}

void
MutablePatternModifier::setSymbols(const DecimalFormatSymbols *symbols, const CurrencyUnit &currency,
                                   const UNumberUnitWidth unitWidth, const PluralRules *rules) {
    U_ASSERT((rules != nullptr) == needsPlurals());
    this->symbols = symbols;
    uprv_memcpy(static_cast<char16_t *>(this->currencyCode),
            currency.getISOCurrency(),
            sizeof(char16_t) * 4);
    this->unitWidth = unitWidth;
    this->rules = rules;
}

void MutablePatternModifier::setNumberProperties(int8_t signum, StandardPlural::Form plural) {
    this->signum = signum;
    this->plural = plural;
}

bool MutablePatternModifier::needsPlurals() const {
    UErrorCode statusLocal = U_ZERO_ERROR;
    return patternInfo->containsSymbolType(AffixPatternType::TYPE_CURRENCY_TRIPLE, statusLocal);
    // Silently ignore any error codes.
}

ImmutablePatternModifier *MutablePatternModifier::createImmutable(UErrorCode &status) {
    return createImmutableAndChain(nullptr, status);
}

ImmutablePatternModifier *
MutablePatternModifier::createImmutableAndChain(const MicroPropsGenerator *parent, UErrorCode &status) {

    // TODO: Move StandardPlural VALUES to standardplural.h
    static const StandardPlural::Form STANDARD_PLURAL_VALUES[] = {
            StandardPlural::Form::ZERO,
            StandardPlural::Form::ONE,
            StandardPlural::Form::TWO,
            StandardPlural::Form::FEW,
            StandardPlural::Form::MANY,
            StandardPlural::Form::OTHER};

    auto pm = new ParameterizedModifier();
    if (pm == nullptr) {
        status = U_MEMORY_ALLOCATION_ERROR;
        return nullptr;
    }

    if (needsPlurals()) {
        // Slower path when we require the plural keyword.
        for (StandardPlural::Form plural : STANDARD_PLURAL_VALUES) {
            setNumberProperties(1, plural);
            pm->adoptSignPluralModifier(1, plural, createConstantModifier(status));
            setNumberProperties(0, plural);
            pm->adoptSignPluralModifier(0, plural, createConstantModifier(status));
            setNumberProperties(-1, plural);
            pm->adoptSignPluralModifier(-1, plural, createConstantModifier(status));
        }
        if (U_FAILURE(status)) {
            delete pm;
            return nullptr;
        }
        return new ImmutablePatternModifier(pm, rules, parent);  // adopts pm
    } else {
        // Faster path when plural keyword is not needed.
        setNumberProperties(1, StandardPlural::Form::COUNT);
        Modifier *positive = createConstantModifier(status);
        setNumberProperties(0, StandardPlural::Form::COUNT);
        Modifier *zero = createConstantModifier(status);
        setNumberProperties(-1, StandardPlural::Form::COUNT);
        Modifier *negative = createConstantModifier(status);
        pm->adoptPositiveNegativeModifiers(positive, zero, negative);
        if (U_FAILURE(status)) {
            delete pm;
            return nullptr;
        }
        return new ImmutablePatternModifier(pm, nullptr, parent);  // adopts pm
    }
}

ConstantMultiFieldModifier *MutablePatternModifier::createConstantModifier(UErrorCode &status) {
    NumberStringBuilder a;
    NumberStringBuilder b;
    insertPrefix(a, 0, status);
    insertSuffix(b, 0, status);
    if (patternInfo->hasCurrencySign()) {
        return new CurrencySpacingEnabledModifier(a, b, !patternInfo->hasBody(), fStrong, *symbols, status);
    } else {
        return new ConstantMultiFieldModifier(a, b, !patternInfo->hasBody(), fStrong);
    }
}

ImmutablePatternModifier::ImmutablePatternModifier(ParameterizedModifier *pm, const PluralRules *rules,
                                                   const MicroPropsGenerator *parent)
        : pm(pm), rules(rules), parent(parent) {}

void ImmutablePatternModifier::processQuantity(DecimalQuantity &quantity, MicroProps &micros,
                                               UErrorCode &status) const {
    parent->processQuantity(quantity, micros, status);
    applyToMicros(micros, quantity);
}

void ImmutablePatternModifier::applyToMicros(MicroProps &micros, DecimalQuantity &quantity) const {
    if (rules == nullptr) {
        micros.modMiddle = pm->getModifier(quantity.signum());
    } else {
        // TODO: Fix this. Avoid the copy.
        DecimalQuantity copy(quantity);
        copy.roundToInfinity();
        StandardPlural::Form plural = copy.getStandardPlural(rules);
        micros.modMiddle = pm->getModifier(quantity.signum(), plural);
    }
}

/** Used by the unsafe code path. */
MicroPropsGenerator &MutablePatternModifier::addToChain(const MicroPropsGenerator *parent) {
    this->parent = parent;
    return *this;
}

void MutablePatternModifier::processQuantity(DecimalQuantity &fq, MicroProps &micros,
                                             UErrorCode &status) const {
    parent->processQuantity(fq, micros, status);
    // The unsafe code path performs self-mutation, so we need a const_cast.
    // This method needs to be const because it overrides a const method in the parent class.
    auto nonConstThis = const_cast<MutablePatternModifier *>(this);
    if (needsPlurals()) {
        // TODO: Fix this. Avoid the copy.
        DecimalQuantity copy(fq);
        micros.rounding.apply(copy, status);
        nonConstThis->setNumberProperties(fq.signum(), copy.getStandardPlural(rules));
    } else {
        nonConstThis->setNumberProperties(fq.signum(), StandardPlural::Form::COUNT);
    }
    micros.modMiddle = this;
}

int32_t MutablePatternModifier::apply(NumberStringBuilder &output, int32_t leftIndex, int32_t rightIndex,
                                      UErrorCode &status) const {
    // The unsafe code path performs self-mutation, so we need a const_cast.
    // This method needs to be const because it overrides a const method in the parent class.
    auto nonConstThis = const_cast<MutablePatternModifier *>(this);
    int32_t prefixLen = nonConstThis->insertPrefix(output, leftIndex, status);
    int32_t suffixLen = nonConstThis->insertSuffix(output, rightIndex + prefixLen, status);
    // If the pattern had no decimal stem body (like #,##0.00), overwrite the value.
    int32_t overwriteLen = 0;
    if (!patternInfo->hasBody()) {
        overwriteLen = output.splice(
            leftIndex + prefixLen, rightIndex + prefixLen,
            UnicodeString(), 0, 0, UNUM_FIELD_COUNT,
            status);
    }
    CurrencySpacingEnabledModifier::applyCurrencySpacing(
            output,
            leftIndex,
            prefixLen,
            rightIndex + overwriteLen + prefixLen,
            suffixLen,
            *symbols,
            status);
    return prefixLen + overwriteLen + suffixLen;
}

int32_t MutablePatternModifier::getPrefixLength(UErrorCode &status) const {
    // The unsafe code path performs self-mutation, so we need a const_cast.
    // This method needs to be const because it overrides a const method in the parent class.
    auto nonConstThis = const_cast<MutablePatternModifier *>(this);

    // Enter and exit CharSequence Mode to get the length.
    nonConstThis->enterCharSequenceMode(true);
    int result = AffixUtils::unescapedCodePointCount(*this, *this, status);  // prefix length
    nonConstThis->exitCharSequenceMode();
    return result;
}

int32_t MutablePatternModifier::getCodePointCount(UErrorCode &status) const {
    // The unsafe code path performs self-mutation, so we need a const_cast.
    // This method needs to be const because it overrides a const method in the parent class.
    auto nonConstThis = const_cast<MutablePatternModifier *>(this);

    // Enter and exit CharSequence Mode to get the length.
    nonConstThis->enterCharSequenceMode(true);
    int result = AffixUtils::unescapedCodePointCount(*this, *this, status);  // prefix length
    nonConstThis->exitCharSequenceMode();
    nonConstThis->enterCharSequenceMode(false);
    result += AffixUtils::unescapedCodePointCount(*this, *this, status);  // suffix length
    nonConstThis->exitCharSequenceMode();
    return result;
}

bool MutablePatternModifier::isStrong() const {
    return fStrong;
}

int32_t MutablePatternModifier::insertPrefix(NumberStringBuilder &sb, int position, UErrorCode &status) {
    enterCharSequenceMode(true);
    int length = AffixUtils::unescape(*this, sb, position, *this, status);
    exitCharSequenceMode();
    return length;
}

int32_t MutablePatternModifier::insertSuffix(NumberStringBuilder &sb, int position, UErrorCode &status) {
    enterCharSequenceMode(false);
    int length = AffixUtils::unescape(*this, sb, position, *this, status);
    exitCharSequenceMode();
    return length;
}

UnicodeString MutablePatternModifier::getSymbol(AffixPatternType type) const {
    switch (type) {
        case AffixPatternType::TYPE_MINUS_SIGN:
            return symbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kMinusSignSymbol);
        case AffixPatternType::TYPE_PLUS_SIGN:
            return symbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kPlusSignSymbol);
        case AffixPatternType::TYPE_PERCENT:
            return symbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kPercentSymbol);
        case AffixPatternType::TYPE_PERMILLE:
            return symbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kPerMillSymbol);
        case AffixPatternType::TYPE_CURRENCY_SINGLE: {
            // UnitWidth ISO and HIDDEN overrides the singular currency symbol.
            if (unitWidth == UNumberUnitWidth::UNUM_UNIT_WIDTH_ISO_CODE) {
                return UnicodeString(currencyCode, 3);
            } else if (unitWidth == UNumberUnitWidth::UNUM_UNIT_WIDTH_HIDDEN) {
                return UnicodeString();
            } else {
                UCurrNameStyle selector = (unitWidth == UNumberUnitWidth::UNUM_UNIT_WIDTH_NARROW)
                        ? UCurrNameStyle::UCURR_NARROW_SYMBOL_NAME
                        : UCurrNameStyle::UCURR_SYMBOL_NAME;
                UErrorCode status = U_ZERO_ERROR;
                UBool isChoiceFormat = FALSE;
                int32_t symbolLen = 0;
                const char16_t *symbol = ucurr_getName(
                        currencyCode,
                        symbols->getLocale().getName(),
                        selector,
                        &isChoiceFormat,
                        &symbolLen,
                        &status);
                return UnicodeString(symbol, symbolLen);
            }
        }
        case AffixPatternType::TYPE_CURRENCY_DOUBLE:
            return UnicodeString(currencyCode, 3);
        case AffixPatternType::TYPE_CURRENCY_TRIPLE: {
            // NOTE: This is the code path only for patterns containing "¤¤¤".
            // Plural currencies set via the API are formatted in LongNameHandler.
            // This code path is used by DecimalFormat via CurrencyPluralInfo.
            U_ASSERT(plural != StandardPlural::Form::COUNT);
            UErrorCode status = U_ZERO_ERROR;
            UBool isChoiceFormat = FALSE;
            int32_t symbolLen = 0;
            const char16_t *symbol = ucurr_getPluralName(
                    currencyCode,
                    symbols->getLocale().getName(),
                    &isChoiceFormat,
                    StandardPlural::getKeyword(plural),
                    &symbolLen,
                    &status);
            return UnicodeString(symbol, symbolLen);
        }
        case AffixPatternType::TYPE_CURRENCY_QUAD:
            return UnicodeString(u"\uFFFD");
        case AffixPatternType::TYPE_CURRENCY_QUINT:
            return UnicodeString(u"\uFFFD");
        default:
            U_ASSERT(false);
            return UnicodeString();
    }
}

/** This method contains the heart of the logic for rendering LDML affix strings. */
void MutablePatternModifier::enterCharSequenceMode(bool isPrefix) {
    U_ASSERT(!inCharSequenceMode);
    inCharSequenceMode = true;

    // Should the output render '+' where '-' would normally appear in the pattern?
    plusReplacesMinusSign = signum != -1
            && (signDisplay == UNUM_SIGN_ALWAYS
                    || signDisplay == UNUM_SIGN_ACCOUNTING_ALWAYS
                    || (signum == 1
                            && (signDisplay == UNUM_SIGN_EXCEPT_ZERO
                                    || signDisplay == UNUM_SIGN_ACCOUNTING_EXCEPT_ZERO)))
            && patternInfo->positiveHasPlusSign() == false;

    // Should we use the affix from the negative subpattern? (If not, we will use the positive subpattern.)
    bool useNegativeAffixPattern = patternInfo->hasNegativeSubpattern() && (
            signum == -1 || (patternInfo->negativeHasMinusSign() && plusReplacesMinusSign));

    // Resolve the flags for the affix pattern.
    fFlags = 0;
    if (useNegativeAffixPattern) {
        fFlags |= AffixPatternProvider::AFFIX_NEGATIVE_SUBPATTERN;
    }
    if (isPrefix) {
        fFlags |= AffixPatternProvider::AFFIX_PREFIX;
    }
    if (plural != StandardPlural::Form::COUNT) {
        U_ASSERT(plural == (AffixPatternProvider::AFFIX_PLURAL_MASK & plural));
        fFlags |= plural;
    }

    // Should we prepend a sign to the pattern?
    if (!isPrefix || useNegativeAffixPattern) {
        prependSign = false;
    } else if (signum == -1) {
        prependSign = signDisplay != UNUM_SIGN_NEVER;
    } else {
        prependSign = plusReplacesMinusSign;
    }

    // Finally, compute the length of the affix pattern.
    fLength = patternInfo->length(fFlags) + (prependSign ? 1 : 0);
}

void MutablePatternModifier::exitCharSequenceMode() {
    U_ASSERT(inCharSequenceMode);
    inCharSequenceMode = false;
}

int32_t MutablePatternModifier::length() const {
    U_ASSERT(inCharSequenceMode);
    return fLength;
}

char16_t MutablePatternModifier::charAt(int32_t index) const {
    U_ASSERT(inCharSequenceMode);
    char16_t candidate;
    if (prependSign && index == 0) {
        candidate = u'-';
    } else if (prependSign) {
        candidate = patternInfo->charAt(fFlags, index - 1);
    } else {
        candidate = patternInfo->charAt(fFlags, index);
    }
    if (plusReplacesMinusSign && candidate == u'-') {
        return u'+';
    }
    if (perMilleReplacesPercent && candidate == u'%') {
        return u'‰';
    }
    return candidate;
}

UnicodeString MutablePatternModifier::toUnicodeString() const {
    // Never called by AffixUtils
    U_ASSERT(false);
    return UnicodeString();
}

#endif /* #if !UCONFIG_NO_FORMATTING */