Debian Codegraph @

intl/components/src/NumberFormat.h

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 #ifndef intl_components_NumberFormat_h_
5 #define intl_components_NumberFormat_h_
6 #include <string_view>
7 #include <utility>
8 #include <vector>
9
10 #include "mozilla/FloatingPoint.h"
11 #include "mozilla/intl/ICU4CGlue.h"
12 #include "mozilla/Maybe.h"
13 #include "mozilla/PodOperations.h"
14 #include "mozilla/Result.h"
15 #include "mozilla/Utf8.h"
16 #include "mozilla/Vector.h"
17 #include "mozilla/intl/ICUError.h"
18 #include "mozilla/intl/NumberPart.h"
19
20 #include "unicode/ustring.h"
21 #include "unicode/unum.h"
22 #include "unicode/unumberformatter.h"
23
24 struct UPluralRules;
25
26 namespace mozilla::intl {
27
28 struct PluralRulesOptions;
29
30 /**
31 * Configure NumberFormat options.
32 * The supported display styles are:
33 * * Decimal (default)
34 * * Currency (controlled by mCurrency)
35 * * Unit (controlled by mUnit)
36 * * Percent (controlled by mPercent)
37 *
38 * Only one of mCurrency, mUnit or mPercent should be set. If none are set,
39 * the number will formatted as a decimal.
40 *
41 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit
42 */
43 struct MOZ_STACK_CLASS NumberFormatOptions {
44 /**
45 * Display a currency amount. |currency| must be a three-letter currency code.
46 *
47 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit
48 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit-width
49 */
50 enum class CurrencyDisplay {
51 Symbol,
52 Code,
53 Name,
54 NarrowSymbol,
55 };
56 Maybe<std::pair<std::string_view, CurrencyDisplay>> mCurrency;
57
58 /**
59 * Set the fraction digits settings. |min| can be zero, |max| must be
60 * larger-or-equal to |min|.
61 *
62 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#fraction-precision
63 */
64 Maybe<std::pair<uint32_t, uint32_t>> mFractionDigits;
65
66 /**
67 * Set the minimum number of integer digits. |min| must be a non-zero
68 * number.
69 *
70 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#integer-width
71 */
72 Maybe<uint32_t> mMinIntegerDigits;
73
74 /**
75 * Set the significant digits settings. |min| must be a non-zero number, |max|
76 * must be larger-or-equal to |min|.
77 *
78 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#significant-digits-precision
79 */
80 Maybe<std::pair<uint32_t, uint32_t>> mSignificantDigits;
81
82 /**
83 * Display a unit amount. |unit| must be a well-formed unit identifier.
84 *
85 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit
86 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#per-unit
87 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit-width
88 */
89 enum class UnitDisplay { Short, Narrow, Long };
90 Maybe<std::pair<std::string_view, UnitDisplay>> mUnit;
91
92 /**
93 * Display a percent number.
94 *
95 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#unit
96 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#scale
97 */
98 bool mPercent = false;
99
100 /**
101 * Set to true to strip trailing zeros after the decimal point for integer
102 * values.
103 *
104 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#trailing-zero-display
105 */
106 bool mStripTrailingZero = false;
107
108 /**
109 * Enable or disable grouping.
110 *
111 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#grouping
112 */
113 enum class Grouping {
114 Auto,
115 Always,
116 Min2,
117 Never,
118 } mGrouping = Grouping::Auto;
119
120 /**
121 * Set the notation style.
122 *
123 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#notation
124 */
125 enum class Notation {
126 Standard,
127 Scientific,
128 Engineering,
129 CompactShort,
130 CompactLong
131 } mNotation = Notation::Standard;
132
133 /**
134 * Set the sign-display.
135 *
136 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#sign-display
137 */
138 enum class SignDisplay {
139 Auto,
140 Never,
141 Always,
142 ExceptZero,
143 Negative,
144 Accounting,
145 AccountingAlways,
146 AccountingExceptZero,
147 AccountingNegative,
148 } mSignDisplay = SignDisplay::Auto;
149
150 /**
151 * Set the rounding increment, which must be a non-zero number.
152 *
153 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#precision
154 */
155 uint32_t mRoundingIncrement = 1;
156
157 /**
158 * Set the rounding mode.
159 *
160 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#rounding-mode
161 */
162 enum class RoundingMode {
163 Ceil,
164 Floor,
165 Expand,
166 Trunc,
167 HalfCeil,
168 HalfFloor,
169 HalfExpand,
170 HalfTrunc,
171 HalfEven,
172 HalfOdd,
173 } mRoundingMode = RoundingMode::HalfExpand;
174
175 /**
176 * Set the rounding priority. |mFractionDigits| and |mSignificantDigits| must
177 * both be set if the rounding priority isn't equal to "auto".
178 *
179 * https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#fraction-precision
180 */
181 enum class RoundingPriority {
182 Auto,
183 MorePrecision,
184 LessPrecision,
185 } mRoundingPriority = RoundingPriority::Auto;
186 };
187
188 /**
189 * According to http://userguide.icu-project.org/design, as long as we constrain
190 * ourselves to const APIs ICU is const-correct.
191 */
192
193 /**
194 * A NumberFormat implementation that roughly mirrors the API provided by
195 * the ECMA-402 Intl.NumberFormat object.
196 *
197 * https://tc39.es/ecma402/#numberformat-objects
198 */
199 class NumberFormat final {
200 public:
201 /**
202 * Initialize a new NumberFormat for the provided locale and using the
203 * provided options.
204 *
205 * https://tc39.es/ecma402/#sec-initializenumberformat
206 */
207 static Result<UniquePtr<NumberFormat>, ICUError> TryCreate(
208 std::string_view aLocale, const NumberFormatOptions& aOptions);
209
210 NumberFormat() = default;
211 NumberFormat(const NumberFormat&) = delete;
212 NumberFormat& operator=(const NumberFormat&) = delete;
213 ~NumberFormat();
214
215 /**
216 * Formats a double to a utf-16 string. The string view is valid until
217 * another number is formatted. Accessing the string view after this event
218 * is undefined behavior.
219 *
220 * https://tc39.es/ecma402/#sec-formatnumberstring
221 */
222 Result<std::u16string_view, ICUError> format(double number) const {
223 if (!formatInternal(number)) {
224 return Err(ICUError::InternalError);
225 }
226
227 return formatResult();
228 }
229
230 /**
231 * Formats a double to a utf-16 string, and fills the provided parts vector.
232 * The string view is valid until another number is formatted. Accessing the
233 * string view after this event is undefined behavior.
234 *
235 * This is utf-16 only because the only current use case is in
236 * SpiderMonkey. Supporting utf-8 would require recalculating the offsets
237 * in NumberPartVector from fixed width to variable width, which might be
238 * tricky to get right and is work that won't be necessary if we switch to
239 * ICU4X (see Bug 1707035).
240 *
241 * https://tc39.es/ecma402/#sec-partitionnumberpattern
242 */
243 Result<std::u16string_view, ICUError> formatToParts(
244 double number, NumberPartVector& parts) const;
245
246 /**
247 * Formats a double to the provider buffer (either utf-8 or utf-16)
248 *
249 * https://tc39.es/ecma402/#sec-formatnumberstring
250 */
251 template <typename B>
252 Result<Ok, ICUError> format(double number, B& buffer) const {
253 if (!formatInternal(number)) {
254 return Err(ICUError::InternalError);
255 }
256
257 return formatResult<typename B::CharType, B>(buffer);
258 }
259
260 /**
261 * Formats an int64_t to a utf-16 string. The string view is valid until
262 * another number is formatted. Accessing the string view after this event is
263 * undefined behavior.
264 *
265 * https://tc39.es/ecma402/#sec-formatnumberstring
266 */
267 Result<std::u16string_view, ICUError> format(int64_t number) const {
268 if (!formatInternal(number)) {
269 return Err(ICUError::InternalError);
270 }
271
272 return formatResult();
273 }
274
275 /**
276 * Formats a int64_t to a utf-16 string, and fills the provided parts vector.
277 * The string view is valid until another number is formatted. Accessing the
278 * string view after this event is undefined behavior.
279 *
280 * This is utf-16 only because the only current use case is in
281 * SpiderMonkey. Supporting utf-8 would require recalculating the offsets
282 * in NumberPartVector from fixed width to variable width, which might be
283 * tricky to get right and is work that won't be necessary if we switch to
284 * ICU4X (see Bug 1707035).
285 *
286 * https://tc39.es/ecma402/#sec-partitionnumberpattern
287 */
288 Result<std::u16string_view, ICUError> formatToParts(
289 int64_t number, NumberPartVector& parts) const;
290
291 /**
292 * Formats an int64_t to the provider buffer (either utf-8 or utf-16).
293 *
294 * https://tc39.es/ecma402/#sec-formatnumberstring
295 */
296 template <typename B>
297 Result<Ok, ICUError> format(int64_t number, B& buffer) const {
298 if (!formatInternal(number)) {
299 return Err(ICUError::InternalError);
300 }
301
302 return formatResult<typename B::CharType, B>(buffer);
303 }
304
305 /**
306 * Formats a string encoded decimal number to a utf-16 string. The string view
307 * is valid until another number is formatted. Accessing the string view
308 * after this event is undefined behavior.
309 *
310 * https://tc39.es/ecma402/#sec-formatnumberstring
311 */
312 Result<std::u16string_view, ICUError> format(std::string_view number) const {
313 if (!formatInternal(number)) {
314 return Err(ICUError::InternalError);
315 }
316
317 return formatResult();
318 }
319
320 /**
321 * Formats a string encoded decimal number to a utf-16 string, and fills the
322 * provided parts vector. The string view is valid until another number is
323 * formatted. Accessing the string view after this event is undefined
324 * behavior.
325 *
326 * This is utf-16 only because the only current use case is in
327 * SpiderMonkey. Supporting utf-8 would require recalculating the offsets
328 * in NumberPartVector from fixed width to variable width, which might be
329 * tricky to get right and is work that won't be necessary if we switch to
330 * ICU4X (see Bug 1707035).
331 *
332 * https://tc39.es/ecma402/#sec-partitionnumberpattern
333 */
334 Result<std::u16string_view, ICUError> formatToParts(
335 std::string_view number, NumberPartVector& parts) const;
336
337 /**
338 * Formats a string encoded decimal number to the provider buffer
339 * (either utf-8 or utf-16).
340 *
341 * https://tc39.es/ecma402/#sec-formatnumberstring
342 */
343 template <typename B>
344 Result<Ok, ICUError> format(std::string_view number, B& buffer) const {
345 if (!formatInternal(number)) {
346 return Err(ICUError::InternalError);
347 }
348
349 return formatResult<typename B::CharType, B>(buffer);
350 }
351
352 /**
353 * Formats the number and selects the keyword by using a provided
354 * UPluralRules object.
355 *
356 * https://tc39.es/ecma402/#sec-intl.pluralrules.prototype.select
357 *
358 * TODO(1713917) This is necessary because both PluralRules and
359 * NumberFormat have a shared dependency on the raw UFormattedNumber
360 * type. Once we transition to using ICU4X, the FFI calls should no
361 * longer require such shared dependencies. At that time, this
362 * functionality should be removed from NumberFormat and invoked
363 * solely from PluralRules.
364 */
365 Result<int32_t, ICUError> selectFormatted(double number, char16_t* keyword,
366 int32_t keywordSize,
367 UPluralRules* pluralRules) const;
368
369 /**
370 * Returns an iterator over all supported number formatter locales.
371 *
372 * The returned strings are ICU locale identifiers and NOT BCP 47 language
373 * tags.
374 *
375 * Also see <https://unicode-org.github.io/icu/userguide/locale>.
376 */
377 static auto GetAvailableLocales() {
378 return AvailableLocalesEnumeration<unum_countAvailable,
379 unum_getAvailable>();
380 }
381
382 private:
383 UNumberFormatter* mNumberFormatter = nullptr;
384 UFormattedNumber* mFormattedNumber = nullptr;
385 bool mFormatForUnit = false;
386
387 Result<Ok, ICUError> initialize(std::string_view aLocale,
388 const NumberFormatOptions& aOptions);
389
390 [[nodiscard]] bool formatInternal(double number) const;
391 [[nodiscard]] bool formatInternal(int64_t number) const;
392 [[nodiscard]] bool formatInternal(std::string_view number) const;
393
394 Result<std::u16string_view, ICUError> formatResult() const;
395
396 template <typename C, typename B>
397 Result<Ok, ICUError> formatResult(B& buffer) const {
398 // We only support buffers with char or char16_t.
399 static_assert(std::is_same_v<C, char> || std::is_same_v<C, char16_t>);
400
401 return formatResult().andThen(
402 [&buffer](std::u16string_view result) -> Result<Ok, ICUError> {
403 if constexpr (std::is_same_v<C, char>) {
404 if (!FillBuffer(Span(result.data(), result.size()), buffer)) {
405 return Err(ICUError::OutOfMemory);
406 }
407 return Ok();
408 } else {
409 // ICU provides APIs which accept a buffer, but they just copy from
410 // an internal buffer behind the scenes anyway.
411 if (!buffer.reserve(result.size())) {
412 return Err(ICUError::OutOfMemory);
413 }
414 PodCopy(static_cast<char16_t*>(buffer.data()), result.data(),
415 result.size());
416 buffer.written(result.size());
417
418 return Ok();
419 }
420 });
421 }
422 };
423
424 } // namespace mozilla::intl
425
426 #endif