summaryrefslogtreecommitdiffstats
path: root/intl/components/src/NumberRangeFormat.h
blob: 40bb85d6d25418fa5919b1b03c65efd2bac57c90 (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
/* 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_NumberRangeFormat_h_
#define intl_components_NumberRangeFormat_h_

#include "mozilla/FloatingPoint.h"
#include "mozilla/intl/ICUError.h"
#include "mozilla/intl/NumberFormat.h"
#include "mozilla/Result.h"
#include "mozilla/UniquePtr.h"

#include <stdint.h>
#include <string_view>

#include "unicode/utypes.h"

struct UFormattedNumberRange;
struct UNumberRangeFormatter;
struct UPluralRules;

namespace mozilla::intl {

/**
 * NumberRangeFormatOptions supports the same set of options as
 * NumberFormatOptions and additionally allows to control how to display ranges.
 */
struct MOZ_STACK_CLASS NumberRangeFormatOptions : public NumberFormatOptions {
  /**
   * Controls if and how to collapse identical parts in a range.
   */
  enum class RangeCollapse {
    /**
     * Apply locale-specific heuristics.
     */
    Auto,

    /**
     * Never collapse identical parts.
     */
    None,

    /**
     * Collapse identical unit parts.
     */
    Unit,

    /**
     * Collapse all identical parts.
     */
    All,
  } mRangeCollapse = RangeCollapse::Auto;

  /**
   * Controls how to display identical numbers.
   */
  enum class RangeIdentityFallback {
    /**
     * Display the range as a single value.
     */
    SingleValue,

    /**
     * Display the range as a single value if both numbers were equal before
     * rounding. Otherwise display with a locale-sensitive approximation
     * pattern.
     */
    ApproximatelyOrSingleValue,

    /**
     * Display with a locale-sensitive approximation pattern.
     */
    Approximately,

    /**
     * Display as a range expression.
     */
    Range,
  } mRangeIdentityFallback = RangeIdentityFallback::SingleValue;
};

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

  NumberRangeFormat() = default;
  NumberRangeFormat(const NumberRangeFormat&) = delete;
  NumberRangeFormat& operator=(const NumberRangeFormat&) = delete;

  ~NumberRangeFormat();

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

    return formatResult();
  }

  /**
   * Formats a double range 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.
   *
   * https://tc39.es/ecma402/#sec-partitionnumberrangepattern
   */
  Result<std::u16string_view, ICUError> formatToParts(
      double start, double end, NumberPartVector& parts) const {
    if (!formatInternal(start, end)) {
      return Err(ICUError::InternalError);
    }

    bool isNegativeStart = !std::isnan(start) && IsNegative(start);
    bool isNegativeEnd = !std::isnan(end) && IsNegative(end);

    return formatResultToParts(Some(start), isNegativeStart, Some(end),
                               isNegativeEnd, parts);
  }

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

    return formatResult();
  }

  /**
   * Formats a string encoded decimal number range 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.
   *
   * https://tc39.es/ecma402/#sec-partitionnumberrangepattern
   */
  Result<std::u16string_view, ICUError> formatToParts(
      std::string_view start, std::string_view end,
      NumberPartVector& parts) const {
    if (!formatInternal(start, end)) {
      return Err(ICUError::InternalError);
    }

    Maybe<double> numStart = Nothing();
    if (start == "Infinity" || start == "+Infinity") {
      numStart.emplace(PositiveInfinity<double>());
    } else if (start == "-Infinity") {
      numStart.emplace(NegativeInfinity<double>());
    } else {
      // Not currently expected, so we assert here.
      MOZ_ASSERT(start != "NaN");
    }

    Maybe<double> numEnd = Nothing();
    if (end == "Infinity" || end == "+Infinity") {
      numEnd.emplace(PositiveInfinity<double>());
    } else if (end == "-Infinity") {
      numEnd.emplace(NegativeInfinity<double>());
    } else {
      // Not currently expected, so we assert here.
      MOZ_ASSERT(end != "NaN");
    }

    bool isNegativeStart = !start.empty() && start[0] == '-';
    bool isNegativeEnd = !end.empty() && end[0] == '-';

    return formatResultToParts(numStart, isNegativeStart, numEnd, isNegativeEnd,
                               parts);
  }

  /**
   * Formats the number range and selects the keyword by using a provided
   * UPluralRules object.
   *
   * https://tc39.es/ecma402/#sec-intl.pluralrules.prototype.selectrange
   *
   * TODO(1713917) This is necessary because both PluralRules and
   * NumberRangeFormat have a shared dependency on the raw UFormattedNumberRange
   * 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 NumberRangeFormat and invoked
   * solely from PluralRules.
   */
  Result<int32_t, ICUError> selectForRange(
      double start, double end, char16_t* keyword, int32_t keywordSize,
      const UPluralRules* pluralRules) const;

 private:
  UNumberRangeFormatter* mNumberRangeFormatter = nullptr;
  UFormattedNumberRange* mFormattedNumberRange = nullptr;
  bool mFormatForUnit = false;

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

  [[nodiscard]] bool formatInternal(double start, double end) const;

  [[nodiscard]] bool formatInternal(std::string_view start,
                                    std::string_view end) const;

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

  Result<std::u16string_view, ICUError> formatResultToParts(
      Maybe<double> start, bool startIsNegative, Maybe<double> end,
      bool endIsNegative, NumberPartVector& parts) const;
};

}  // namespace mozilla::intl

#endif