summaryrefslogtreecommitdiffstats
path: root/intl/components/src/NumberFormatterSkeleton.cpp
blob: 951a7a70a5ba99cd182a80e33db2ba071d09e883 (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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "NumberFormatterSkeleton.h"
#include "NumberFormat.h"

#include "MeasureUnitGenerated.h"

#include "mozilla/RangedPtr.h"

#include <algorithm>
#include <limits>

#include "unicode/unumberrangeformatter.h"

namespace mozilla::intl {

NumberFormatterSkeleton::NumberFormatterSkeleton(
    const NumberFormatOptions& options) {
  if (options.mCurrency.isSome()) {
    if (!currency(options.mCurrency->first) ||
        !currencyDisplay(options.mCurrency->second)) {
      return;
    }
  } else if (options.mUnit.isSome()) {
    if (!unit(options.mUnit->first) || !unitDisplay(options.mUnit->second)) {
      return;
    }
  } else if (options.mPercent) {
    if (!percent()) {
      return;
    }
  }

  if (options.mRoundingIncrement != 1) {
    auto fd = options.mFractionDigits.valueOr(std::pair{0, 0});
    if (!roundingIncrement(options.mRoundingIncrement, fd.first, fd.second,
                           options.mStripTrailingZero)) {
      return;
    }
  } else if (options.mRoundingPriority ==
             NumberFormatOptions::RoundingPriority::Auto) {
    if (options.mFractionDigits.isSome()) {
      if (!fractionDigits(options.mFractionDigits->first,
                          options.mFractionDigits->second,
                          options.mStripTrailingZero)) {
        return;
      }
    }

    if (options.mSignificantDigits.isSome()) {
      if (!significantDigits(options.mSignificantDigits->first,
                             options.mSignificantDigits->second,
                             options.mStripTrailingZero)) {
        return;
      }
    }
  } else {
    MOZ_ASSERT(options.mFractionDigits);
    MOZ_ASSERT(options.mSignificantDigits);

    bool relaxed = options.mRoundingPriority ==
                   NumberFormatOptions::RoundingPriority::MorePrecision;
    if (!fractionWithSignificantDigits(options.mFractionDigits->first,
                                       options.mFractionDigits->second,
                                       options.mSignificantDigits->first,
                                       options.mSignificantDigits->second,
                                       relaxed, options.mStripTrailingZero)) {
      return;
    }
  }

  if (options.mMinIntegerDigits.isSome()) {
    if (!minIntegerDigits(*options.mMinIntegerDigits)) {
      return;
    }
  }

  if (!grouping(options.mGrouping)) {
    return;
  }

  if (!notation(options.mNotation)) {
    return;
  }

  if (!signDisplay(options.mSignDisplay)) {
    return;
  }

  if (!roundingMode(options.mRoundingMode)) {
    return;
  }

  mValidSkeleton = true;
}

bool NumberFormatterSkeleton::currency(std::string_view currency) {
  MOZ_ASSERT(currency.size() == 3,
             "IsWellFormedCurrencyCode permits only length-3 strings");

  char16_t currencyChars[] = {static_cast<char16_t>(currency[0]),
                              static_cast<char16_t>(currency[1]),
                              static_cast<char16_t>(currency[2]), '\0'};
  return append(u"currency/") && append(currencyChars) && append(' ');
}

bool NumberFormatterSkeleton::currencyDisplay(
    NumberFormatOptions::CurrencyDisplay display) {
  switch (display) {
    case NumberFormatOptions::CurrencyDisplay::Code:
      return appendToken(u"unit-width-iso-code");
    case NumberFormatOptions::CurrencyDisplay::Name:
      return appendToken(u"unit-width-full-name");
    case NumberFormatOptions::CurrencyDisplay::Symbol:
      // Default, no additional tokens needed.
      return true;
    case NumberFormatOptions::CurrencyDisplay::NarrowSymbol:
      return appendToken(u"unit-width-narrow");
  }
  MOZ_ASSERT_UNREACHABLE("unexpected currency display type");
  return false;
}

static const SimpleMeasureUnit& FindSimpleMeasureUnit(std::string_view name) {
  const auto* measureUnit = std::lower_bound(
      std::begin(simpleMeasureUnits), std::end(simpleMeasureUnits), name,
      [](const auto& measureUnit, std::string_view name) {
        return name.compare(measureUnit.name) > 0;
      });
  MOZ_ASSERT(measureUnit != std::end(simpleMeasureUnits),
             "unexpected unit identifier: unit not found");
  MOZ_ASSERT(measureUnit->name == name,
             "unexpected unit identifier: wrong unit found");
  return *measureUnit;
}

static constexpr size_t MaxUnitLength() {
  size_t length = 0;
  for (const auto& unit : simpleMeasureUnits) {
    length = std::max(length, std::char_traits<char>::length(unit.name));
  }
  return length * 2 + std::char_traits<char>::length("-per-");
}

bool NumberFormatterSkeleton::unit(std::string_view unit) {
  MOZ_RELEASE_ASSERT(unit.length() <= MaxUnitLength());

  auto appendUnit = [this](const SimpleMeasureUnit& unit) {
    return append(unit.type, strlen(unit.type)) && append('-') &&
           append(unit.name, strlen(unit.name));
  };

  // |unit| can be a compound unit identifier, separated by "-per-".
  static constexpr char separator[] = "-per-";
  size_t separator_len = strlen(separator);
  size_t offset = unit.find(separator);
  if (offset != std::string_view::npos) {
    const auto& numerator = FindSimpleMeasureUnit(unit.substr(0, offset));
    const auto& denominator = FindSimpleMeasureUnit(
        std::string_view(unit.data() + offset + separator_len,
                         unit.length() - offset - separator_len));
    return append(u"measure-unit/") && appendUnit(numerator) && append(' ') &&
           append(u"per-measure-unit/") && appendUnit(denominator) &&
           append(' ');
  }

  const auto& simple = FindSimpleMeasureUnit(unit);
  return append(u"measure-unit/") && appendUnit(simple) && append(' ');
}

bool NumberFormatterSkeleton::unitDisplay(
    NumberFormatOptions::UnitDisplay display) {
  switch (display) {
    case NumberFormatOptions::UnitDisplay::Short:
      return appendToken(u"unit-width-short");
    case NumberFormatOptions::UnitDisplay::Narrow:
      return appendToken(u"unit-width-narrow");
    case NumberFormatOptions::UnitDisplay::Long:
      return appendToken(u"unit-width-full-name");
  }
  MOZ_ASSERT_UNREACHABLE("unexpected unit display type");
  return false;
}

bool NumberFormatterSkeleton::percent() {
  return appendToken(u"percent scale/100");
}

bool NumberFormatterSkeleton::fractionDigits(uint32_t min, uint32_t max,
                                             bool stripTrailingZero) {
  // Note: |min| can be zero here.
  MOZ_ASSERT(min <= max);
  if (!append('.') || !appendN('0', min) || !appendN('#', max - min)) {
    return false;
  }
  if (stripTrailingZero) {
    if (!append(u"/w")) {
      return false;
    }
  }
  return append(' ');
}

bool NumberFormatterSkeleton::fractionWithSignificantDigits(
    uint32_t mnfd, uint32_t mxfd, uint32_t mnsd, uint32_t mxsd, bool relaxed,
    bool stripTrailingZero) {
  // Note: |mnfd| can be zero here.
  MOZ_ASSERT(mnfd <= mxfd);
  MOZ_ASSERT(mnsd > 0);
  MOZ_ASSERT(mnsd <= mxsd);

  if (!append('.') || !appendN('0', mnfd) || !appendN('#', mxfd - mnfd)) {
    return false;
  }
  if (!append('/') || !appendN('@', mnsd) || !appendN('#', mxsd - mnsd)) {
    return false;
  }
  if (!append(relaxed ? 'r' : 's')) {
    return false;
  }
  if (stripTrailingZero) {
    if (!append(u"/w")) {
      return false;
    }
  }
  return append(' ');
}

bool NumberFormatterSkeleton::minIntegerDigits(uint32_t min) {
  MOZ_ASSERT(min > 0);
  return append(u"integer-width/+") && appendN('0', min) && append(' ');
}

bool NumberFormatterSkeleton::significantDigits(uint32_t min, uint32_t max,
                                                bool stripTrailingZero) {
  MOZ_ASSERT(min > 0);
  MOZ_ASSERT(min <= max);
  if (!appendN('@', min) || !appendN('#', max - min)) {
    return false;
  }
  if (stripTrailingZero) {
    if (!append(u"/w")) {
      return false;
    }
  }
  return append(' ');
}

bool NumberFormatterSkeleton::grouping(NumberFormatOptions::Grouping grouping) {
  switch (grouping) {
    case NumberFormatOptions::Grouping::Auto:
      // Default, no additional tokens needed.
      return true;
    case NumberFormatOptions::Grouping::Always:
      return appendToken(u"group-on-aligned");
    case NumberFormatOptions::Grouping::Min2:
      return appendToken(u"group-min2");
    case NumberFormatOptions::Grouping::Never:
      return appendToken(u"group-off");
  }
  MOZ_ASSERT_UNREACHABLE("unexpected grouping mode");
  return false;
}

bool NumberFormatterSkeleton::notation(NumberFormatOptions::Notation style) {
  switch (style) {
    case NumberFormatOptions::Notation::Standard:
      // Default, no additional tokens needed.
      return true;
    case NumberFormatOptions::Notation::Scientific:
      return appendToken(u"scientific");
    case NumberFormatOptions::Notation::Engineering:
      return appendToken(u"engineering");
    case NumberFormatOptions::Notation::CompactShort:
      return appendToken(u"compact-short");
    case NumberFormatOptions::Notation::CompactLong:
      return appendToken(u"compact-long");
  }
  MOZ_ASSERT_UNREACHABLE("unexpected notation style");
  return false;
}

bool NumberFormatterSkeleton::signDisplay(
    NumberFormatOptions::SignDisplay display) {
  switch (display) {
    case NumberFormatOptions::SignDisplay::Auto:
      // Default, no additional tokens needed.
      return true;
    case NumberFormatOptions::SignDisplay::Always:
      return appendToken(u"sign-always");
    case NumberFormatOptions::SignDisplay::Never:
      return appendToken(u"sign-never");
    case NumberFormatOptions::SignDisplay::ExceptZero:
      return appendToken(u"sign-except-zero");
    case NumberFormatOptions::SignDisplay::Negative:
      return appendToken(u"sign-negative");
    case NumberFormatOptions::SignDisplay::Accounting:
      return appendToken(u"sign-accounting");
    case NumberFormatOptions::SignDisplay::AccountingAlways:
      return appendToken(u"sign-accounting-always");
    case NumberFormatOptions::SignDisplay::AccountingExceptZero:
      return appendToken(u"sign-accounting-except-zero");
    case NumberFormatOptions::SignDisplay::AccountingNegative:
      return appendToken(u"sign-accounting-negative");
  }
  MOZ_ASSERT_UNREACHABLE("unexpected sign display type");
  return false;
}

bool NumberFormatterSkeleton::roundingIncrement(uint32_t increment,
                                                uint32_t mnfd, uint32_t mxfd,
                                                bool stripTrailingZero) {
  // Note: |mnfd| can be zero here.
  MOZ_ASSERT(mnfd <= mxfd);
  MOZ_ASSERT(increment > 1);

  // Limit |mxfd| to 100.
  constexpr size_t maxFracDigits = 100;
  MOZ_RELEASE_ASSERT(mxfd <= maxFracDigits);

  static constexpr char digits[] = "0123456789";

  // We need enough space to print any uint32_t, which is possibly shifted by
  // |mxfd| decimal places. And additionally we need to reserve space for "0.".
  static_assert(std::numeric_limits<uint32_t>::digits10 + 1 < maxFracDigits);
  constexpr size_t maxLength = maxFracDigits + 2;

  char chars[maxLength];
  RangedPtr<char> ptr(chars + maxLength, chars, maxLength);
  const RangedPtr<char> end = ptr;

  // Convert to a signed integer, so we don't have to worry about underflows.
  int32_t maxFrac = int32_t(mxfd);

  // Write |increment| from back to front.
  while (increment != 0) {
    *--ptr = digits[increment % 10];
    increment /= 10;
    maxFrac -= 1;

    if (maxFrac == 0) {
      *--ptr = '.';
    }
  }

  // Write any remaining zeros from |mxfd| and prepend '0' if we last wrote the
  // decimal point.
  while (maxFrac >= 0) {
    MOZ_ASSERT_IF(maxFrac == 0, *ptr == '.');

    *--ptr = '0';
    maxFrac -= 1;

    if (maxFrac == 0) {
      *--ptr = '.';
    }
  }

  MOZ_ASSERT(ptr < end, "At least one character is written.");
  MOZ_ASSERT(*ptr != '.', "First character is a digit.");

  if (!append(u"precision-increment/") || !append(ptr.get(), end - ptr)) {
    return false;
  }
  if (stripTrailingZero) {
    if (!append(u"/w")) {
      return false;
    }
  }
  return append(' ');
}

bool NumberFormatterSkeleton::roundingMode(
    NumberFormatOptions::RoundingMode rounding) {
  switch (rounding) {
    case NumberFormatOptions::RoundingMode::Ceil:
      return appendToken(u"rounding-mode-ceiling");
    case NumberFormatOptions::RoundingMode::Floor:
      return appendToken(u"rounding-mode-floor");
    case NumberFormatOptions::RoundingMode::Expand:
      return appendToken(u"rounding-mode-up");
    case NumberFormatOptions::RoundingMode::Trunc:
      return appendToken(u"rounding-mode-down");
    case NumberFormatOptions::RoundingMode::HalfCeil:
      return appendToken(u"rounding-mode-half-ceiling");
    case NumberFormatOptions::RoundingMode::HalfFloor:
      return appendToken(u"rounding-mode-half-floor");
    case NumberFormatOptions::RoundingMode::HalfExpand:
      return appendToken(u"rounding-mode-half-up");
    case NumberFormatOptions::RoundingMode::HalfTrunc:
      return appendToken(u"rounding-mode-half-down");
    case NumberFormatOptions::RoundingMode::HalfEven:
      return appendToken(u"rounding-mode-half-even");
    case NumberFormatOptions::RoundingMode::HalfOdd:
      return appendToken(u"rounding-mode-half-odd");
  }
  MOZ_ASSERT_UNREACHABLE("unexpected rounding mode");
  return false;
}

UNumberFormatter* NumberFormatterSkeleton::toFormatter(
    std::string_view locale) {
  if (!mValidSkeleton) {
    return nullptr;
  }

  UErrorCode status = U_ZERO_ERROR;
  UNumberFormatter* nf = unumf_openForSkeletonAndLocale(
      mVector.begin(), mVector.length(), AssertNullTerminatedString(locale),
      &status);
  if (U_FAILURE(status)) {
    return nullptr;
  }
  return nf;
}

static UNumberRangeCollapse ToUNumberRangeCollapse(
    NumberRangeFormatOptions::RangeCollapse collapse) {
  using RangeCollapse = NumberRangeFormatOptions::RangeCollapse;
  switch (collapse) {
    case RangeCollapse::Auto:
      return UNUM_RANGE_COLLAPSE_AUTO;
    case RangeCollapse::None:
      return UNUM_RANGE_COLLAPSE_NONE;
    case RangeCollapse::Unit:
      return UNUM_RANGE_COLLAPSE_UNIT;
    case RangeCollapse::All:
      return UNUM_RANGE_COLLAPSE_ALL;
  }
  MOZ_ASSERT_UNREACHABLE("unexpected range collapse");
  return UNUM_RANGE_COLLAPSE_NONE;
}

static UNumberRangeIdentityFallback ToUNumberRangeIdentityFallback(
    NumberRangeFormatOptions::RangeIdentityFallback identity) {
  using RangeIdentityFallback = NumberRangeFormatOptions::RangeIdentityFallback;
  switch (identity) {
    case RangeIdentityFallback::SingleValue:
      return UNUM_IDENTITY_FALLBACK_SINGLE_VALUE;
    case RangeIdentityFallback::ApproximatelyOrSingleValue:
      return UNUM_IDENTITY_FALLBACK_APPROXIMATELY_OR_SINGLE_VALUE;
    case RangeIdentityFallback::Approximately:
      return UNUM_IDENTITY_FALLBACK_APPROXIMATELY;
    case RangeIdentityFallback::Range:
      return UNUM_IDENTITY_FALLBACK_RANGE;
  }
  MOZ_ASSERT_UNREACHABLE("unexpected range identity fallback");
  return UNUM_IDENTITY_FALLBACK_RANGE;
}

UNumberRangeFormatter* NumberFormatterSkeleton::toRangeFormatter(
    std::string_view locale, NumberRangeFormatOptions::RangeCollapse collapse,
    NumberRangeFormatOptions::RangeIdentityFallback identity) {
  if (!mValidSkeleton) {
    return nullptr;
  }

  UParseError* perror = nullptr;
  UErrorCode status = U_ZERO_ERROR;
  UNumberRangeFormatter* nrf =
      unumrf_openForSkeletonWithCollapseAndIdentityFallback(
          mVector.begin(), mVector.length(), ToUNumberRangeCollapse(collapse),
          ToUNumberRangeIdentityFallback(identity),
          AssertNullTerminatedString(locale), perror, &status);
  if (U_FAILURE(status)) {
    return nullptr;
  }
  return nrf;
}

}  // namespace mozilla::intl