summaryrefslogtreecommitdiffstats
path: root/intl/components/src/NumberFormat.h
blob: 684b772e303ec539ec665fa8036dd159a89147ee (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
/* 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/. */
#ifndef intl_components_NumberFormat_h_
#define intl_components_NumberFormat_h_
#include <string_view>
#include <utility>
#include <vector>

#include "mozilla/FloatingPoint.h"
#include "mozilla/intl/ICU4CGlue.h"
#include "mozilla/Maybe.h"
#include "mozilla/PodOperations.h"
#include "mozilla/Result.h"
#include "mozilla/Utf8.h"
#include "mozilla/Vector.h"
#include "mozilla/intl/ICUError.h"
#include "mozilla/intl/NumberPart.h"

#include "unicode/ustring.h"
#include "unicode/unum.h"
#include "unicode/unumberformatter.h"

struct UPluralRules;

namespace mozilla::intl {

struct PluralRulesOptions;

/**
 * Configure NumberFormat options.
 * The supported display styles are:
 *   * Decimal (default)
 *   * Currency (controlled by mCurrency)
 *   * Unit (controlled by mUnit)
 *   * Percent (controlled by mPercent)
 *
 * Only one of mCurrency, mUnit or mPercent should be set. If none are set,
 * the number will formatted as a decimal.
 *
 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit
 */
struct MOZ_STACK_CLASS NumberFormatOptions {
  /**
   * Display a currency amount. |currency| must be a three-letter currency code.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit-width
   */
  enum class CurrencyDisplay {
    Symbol,
    Code,
    Name,
    NarrowSymbol,
  };
  Maybe<std::pair<std::string_view, CurrencyDisplay>> mCurrency;

  /**
   * Set the fraction digits settings. |min| can be zero, |max| must be
   * larger-or-equal to |min|.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#fraction-precision
   */
  Maybe<std::pair<uint32_t, uint32_t>> mFractionDigits;

  /**
   * Set the minimum number of integer digits. |min| must be a non-zero
   * number.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#integer-width
   */
  Maybe<uint32_t> mMinIntegerDigits;

  /**
   * Set the significant digits settings. |min| must be a non-zero number, |max|
   * must be larger-or-equal to |min|.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#significant-digits-precision
   */
  Maybe<std::pair<uint32_t, uint32_t>> mSignificantDigits;

  /**
   * Display a unit amount. |unit| must be a well-formed unit identifier.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#per-unit
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit-width
   */
  enum class UnitDisplay { Short, Narrow, Long };
  Maybe<std::pair<std::string_view, UnitDisplay>> mUnit;

  /**
   * Display a percent number.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#scale
   */
  bool mPercent = false;

  /**
   * Set to true to strip trailing zeros after the decimal point for integer
   * values.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#trailing-zero-display
   */
  bool mStripTrailingZero = false;

  /**
   * Enable or disable grouping.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#grouping
   */
  enum class Grouping {
    Auto,
    Always,
    Min2,
    Never,
  } mGrouping = Grouping::Auto;

  /**
   * Set the notation style.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#notation
   */
  enum class Notation {
    Standard,
    Scientific,
    Engineering,
    CompactShort,
    CompactLong
  } mNotation = Notation::Standard;

  /**
   * Set the sign-display.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#sign-display
   */
  enum class SignDisplay {
    Auto,
    Never,
    Always,
    ExceptZero,
    Negative,
    Accounting,
    AccountingAlways,
    AccountingExceptZero,
    AccountingNegative,
  } mSignDisplay = SignDisplay::Auto;

  /**
   * Set the rounding increment, which must be a non-zero number.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#precision
   */
  uint32_t mRoundingIncrement = 1;

  /**
   * Set the rounding mode.
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#rounding-mode
   */
  enum class RoundingMode {
    Ceil,
    Floor,
    Expand,
    Trunc,
    HalfCeil,
    HalfFloor,
    HalfExpand,
    HalfTrunc,
    HalfEven,
    HalfOdd,
  } mRoundingMode = RoundingMode::HalfExpand;

  /**
   * Set the rounding priority. |mFractionDigits| and |mSignificantDigits| must
   * both be set if the rounding priority isn't equal to "auto".
   *
   * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#fraction-precision
   */
  enum class RoundingPriority {
    Auto,
    MorePrecision,
    LessPrecision,
  } mRoundingPriority = RoundingPriority::Auto;
};

/**
 * According to http://userguide.icu-project.org/design, as long as we constrain
 * ourselves to const APIs ICU is const-correct.
 */

/**
 * A NumberFormat implementation that roughly mirrors the API provided by
 * the ECMA-402 Intl.NumberFormat object.
 *
 * https://tc39.es/ecma402/#numberformat-objects
 */
class NumberFormat final {
 public:
  /**
   * Initialize a new NumberFormat for the provided locale and using the
   * provided options.
   *
   * https://tc39.es/ecma402/#sec-initializenumberformat
   */
  static Result<UniquePtr<NumberFormat>, ICUError> TryCreate(
      std::string_view aLocale, const NumberFormatOptions& aOptions);

  NumberFormat() = default;
  NumberFormat(const NumberFormat&) = delete;
  NumberFormat& operator=(const NumberFormat&) = delete;
  ~NumberFormat();

  /**
   * Formats a double to a utf-16 string. The string view is valid until
   * another number is formatted. Accessing the string view after this event
   * is undefined behavior.
   *
   * https://tc39.es/ecma402/#sec-formatnumberstring
   */
  Result<std::u16string_view, ICUError> format(double number) const {
    if (!formatInternal(number)) {
      return Err(ICUError::InternalError);
    }

    return formatResult();
  }

  /**
   * Formats a double to a utf-16 string, and fills the provided parts vector.
   * The string view is valid until another number is formatted. Accessing the
   * string view after this event is undefined behavior.
   *
   * This is utf-16 only because the only current use case is in
   * SpiderMonkey. Supporting utf-8 would require recalculating the offsets
   * in NumberPartVector from fixed width to variable width, which might be
   * tricky to get right and is work that won't be necessary if we switch to
   * ICU4X (see Bug 1707035).
   *
   * https://tc39.es/ecma402/#sec-partitionnumberpattern
   */
  Result<std::u16string_view, ICUError> formatToParts(
      double number, NumberPartVector& parts) const;

  /**
   * Formats a double to the provider buffer (either utf-8 or utf-16)
   *
   * https://tc39.es/ecma402/#sec-formatnumberstring
   */
  template <typename B>
  Result<Ok, ICUError> format(double number, B& buffer) const {
    if (!formatInternal(number)) {
      return Err(ICUError::InternalError);
    }

    return formatResult<typename B::CharType, B>(buffer);
  }

  /**
   * Formats an int64_t to a utf-16 string. The string view is valid until
   * another number is formatted. Accessing the string view after this event is
   * undefined behavior.
   *
   * https://tc39.es/ecma402/#sec-formatnumberstring
   */
  Result<std::u16string_view, ICUError> format(int64_t number) const {
    if (!formatInternal(number)) {
      return Err(ICUError::InternalError);
    }

    return formatResult();
  }

  /**
   * Formats a int64_t to a utf-16 string, and fills the provided parts vector.
   * The string view is valid until another number is formatted. Accessing the
   * string view after this event is undefined behavior.
   *
   * This is utf-16 only because the only current use case is in
   * SpiderMonkey. Supporting utf-8 would require recalculating the offsets
   * in NumberPartVector from fixed width to variable width, which might be
   * tricky to get right and is work that won't be necessary if we switch to
   * ICU4X (see Bug 1707035).
   *
   * https://tc39.es/ecma402/#sec-partitionnumberpattern
   */
  Result<std::u16string_view, ICUError> formatToParts(
      int64_t number, NumberPartVector& parts) const;

  /**
   * Formats an int64_t to the provider buffer (either utf-8 or utf-16).
   *
   * https://tc39.es/ecma402/#sec-formatnumberstring
   */
  template <typename B>
  Result<Ok, ICUError> format(int64_t number, B& buffer) const {
    if (!formatInternal(number)) {
      return Err(ICUError::InternalError);
    }

    return formatResult<typename B::CharType, B>(buffer);
  }

  /**
   * Formats a string encoded decimal number to a utf-16 string. The string view
   * is valid until another number is formatted. Accessing the string view
   * after this event is undefined behavior.
   *
   * https://tc39.es/ecma402/#sec-formatnumberstring
   */
  Result<std::u16string_view, ICUError> format(std::string_view number) const {
    if (!formatInternal(number)) {
      return Err(ICUError::InternalError);
    }

    return formatResult();
  }

  /**
   * Formats a string encoded decimal number to a utf-16 string, and fills the
   * provided parts vector. The string view is valid until another number is
   * formatted. Accessing the string view after this event is undefined
   * behavior.
   *
   * This is utf-16 only because the only current use case is in
   * SpiderMonkey. Supporting utf-8 would require recalculating the offsets
   * in NumberPartVector from fixed width to variable width, which might be
   * tricky to get right and is work that won't be necessary if we switch to
   * ICU4X (see Bug 1707035).
   *
   * https://tc39.es/ecma402/#sec-partitionnumberpattern
   */
  Result<std::u16string_view, ICUError> formatToParts(
      std::string_view number, NumberPartVector& parts) const;

  /**
   * Formats a string encoded decimal number to the provider buffer
   * (either utf-8 or utf-16).
   *
   * https://tc39.es/ecma402/#sec-formatnumberstring
   */
  template <typename B>
  Result<Ok, ICUError> format(std::string_view number, B& buffer) const {
    if (!formatInternal(number)) {
      return Err(ICUError::InternalError);
    }

    return formatResult<typename B::CharType, B>(buffer);
  }

  /**
   * Formats the number and selects the keyword by using a provided
   * UPluralRules object.
   *
   * https://tc39.es/ecma402/#sec-intl.pluralrules.prototype.select
   *
   * TODO(1713917) This is necessary because both PluralRules and
   * NumberFormat have a shared dependency on the raw UFormattedNumber
   * type. Once we transition to using ICU4X, the FFI calls should no
   * longer require such shared dependencies. At that time, this
   * functionality should be removed from NumberFormat and invoked
   * solely from PluralRules.
   */
  Result<int32_t, ICUError> selectFormatted(double number, char16_t* keyword,
                                            int32_t keywordSize,
                                            UPluralRules* pluralRules) const;

  /**
   * Returns an iterator over all supported number formatter locales.
   *
   * The returned strings are ICU locale identifiers and NOT BCP 47 language
   * tags.
   *
   * Also see <https://unicode-org.github.io/icu/userguide/locale>.
   */
  static auto GetAvailableLocales() {
    return AvailableLocalesEnumeration<unum_countAvailable,
                                       unum_getAvailable>();
  }

 private:
  UNumberFormatter* mNumberFormatter = nullptr;
  UFormattedNumber* mFormattedNumber = nullptr;
  bool mFormatForUnit = false;

  Result<Ok, ICUError> initialize(std::string_view aLocale,
                                  const NumberFormatOptions& aOptions);

  [[nodiscard]] bool formatInternal(double number) const;
  [[nodiscard]] bool formatInternal(int64_t number) const;
  [[nodiscard]] bool formatInternal(std::string_view number) const;

  Result<std::u16string_view, ICUError> formatResult() const;

  template <typename C, typename B>
  Result<Ok, ICUError> formatResult(B& buffer) const {
    // We only support buffers with char or char16_t.
    static_assert(std::is_same_v<C, char> || std::is_same_v<C, char16_t>);

    return formatResult().andThen(
        [&buffer](std::u16string_view result) -> Result<Ok, ICUError> {
          if constexpr (std::is_same_v<C, char>) {
            if (!FillBuffer(Span(result.data(), result.size()), buffer)) {
              return Err(ICUError::OutOfMemory);
            }
            return Ok();
          } else {
            // ICU provides APIs which accept a buffer, but they just copy from
            // an internal buffer behind the scenes anyway.
            if (!buffer.reserve(result.size())) {
              return Err(ICUError::OutOfMemory);
            }
            PodCopy(static_cast<char16_t*>(buffer.data()), result.data(),
                    result.size());
            buffer.written(result.size());

            return Ok();
          }
        });
  }
};

}  // namespace mozilla::intl

#endif