summaryrefslogtreecommitdiffstats
path: root/intl/components/src/NumberRangeFormat.cpp
blob: bf82e36c3365362975d27a81df790704585798db (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
/* 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 "mozilla/intl/NumberRangeFormat.h"

#include "mozilla/intl/ICU4CGlue.h"
#include "mozilla/intl/NumberFormat.h"
#include "NumberFormatFields.h"
#include "NumberFormatterSkeleton.h"
#include "ScopedICUObject.h"

#include "unicode/uformattedvalue.h"
#include "unicode/unumberrangeformatter.h"
#include "unicode/upluralrules.h"

namespace mozilla::intl {

/*static*/ Result<UniquePtr<NumberRangeFormat>, ICUError>
NumberRangeFormat::TryCreate(std::string_view aLocale,
                             const NumberRangeFormatOptions& aOptions) {
  UniquePtr<NumberRangeFormat> nrf = MakeUnique<NumberRangeFormat>();
  MOZ_TRY(nrf->initialize(aLocale, aOptions));
  return nrf;
}

NumberRangeFormat::~NumberRangeFormat() {
  if (mFormattedNumberRange) {
    unumrf_closeResult(mFormattedNumberRange);
  }
  if (mNumberRangeFormatter) {
    unumrf_close(mNumberRangeFormatter);
  }
}

Result<Ok, ICUError> NumberRangeFormat::initialize(
    std::string_view aLocale, const NumberRangeFormatOptions& aOptions) {
  mFormatForUnit = aOptions.mUnit.isSome();

  NumberFormatterSkeleton skeleton(aOptions);
  mNumberRangeFormatter = skeleton.toRangeFormatter(
      aLocale, aOptions.mRangeCollapse, aOptions.mRangeIdentityFallback);
  if (mNumberRangeFormatter) {
    UErrorCode status = U_ZERO_ERROR;
    mFormattedNumberRange = unumrf_openResult(&status);
    if (U_FAILURE(status)) {
      return Err(ToICUError(status));
    }
    return Ok();
  }
  return Err(ICUError::InternalError);
}

Result<int32_t, ICUError> NumberRangeFormat::selectForRange(
    double start, double end, char16_t* keyword, int32_t keywordSize,
    const UPluralRules* pluralRules) const {
  MOZ_ASSERT(keyword);
  MOZ_ASSERT(pluralRules);

  MOZ_TRY(format(start, end));

  UErrorCode status = U_ZERO_ERROR;
  int32_t utf16KeywordLength = uplrules_selectForRange(
      pluralRules, mFormattedNumberRange, keyword, keywordSize, &status);
  if (U_FAILURE(status)) {
    return Err(ToICUError(status));
  }

  return utf16KeywordLength;
}

bool NumberRangeFormat::formatInternal(double start, double end) const {
  // ICU incorrectly formats NaN values with the sign bit set, as if they
  // were negative.  Replace all NaNs with a single pattern with sign bit
  // unset ("positive", that is) until ICU is fixed.
  if (MOZ_UNLIKELY(std::isnan(start))) {
    start = SpecificNaN<double>(0, 1);
  }
  if (MOZ_UNLIKELY(std::isnan(end))) {
    end = SpecificNaN<double>(0, 1);
  }

  UErrorCode status = U_ZERO_ERROR;
  unumrf_formatDoubleRange(mNumberRangeFormatter, start, end,
                           mFormattedNumberRange, &status);
  return U_SUCCESS(status);
}

bool NumberRangeFormat::formatInternal(std::string_view start,
                                       std::string_view end) const {
  UErrorCode status = U_ZERO_ERROR;
  unumrf_formatDecimalRange(mNumberRangeFormatter, start.data(), start.size(),
                            end.data(), end.size(), mFormattedNumberRange,
                            &status);
  return U_SUCCESS(status);
}

Result<std::u16string_view, ICUError> NumberRangeFormat::formatResult() const {
  UErrorCode status = U_ZERO_ERROR;

  const UFormattedValue* formattedValue =
      unumrf_resultAsValue(mFormattedNumberRange, &status);
  if (U_FAILURE(status)) {
    return Err(ToICUError(status));
  }

  int32_t utf16Length;
  const char16_t* utf16Str =
      ufmtval_getString(formattedValue, &utf16Length, &status);
  if (U_FAILURE(status)) {
    return Err(ToICUError(status));
  }

  return std::u16string_view(utf16Str, static_cast<size_t>(utf16Length));
}

Result<std::u16string_view, ICUError> NumberRangeFormat::formatResultToParts(
    Maybe<double> start, bool startIsNegative, Maybe<double> end,
    bool endIsNegative, NumberPartVector& parts) const {
  UErrorCode status = U_ZERO_ERROR;

  const UFormattedValue* formattedValue =
      unumrf_resultAsValue(mFormattedNumberRange, &status);
  if (U_FAILURE(status)) {
    return Err(ToICUError(status));
  }

  int32_t utf16Length;
  const char16_t* utf16Str =
      ufmtval_getString(formattedValue, &utf16Length, &status);
  if (U_FAILURE(status)) {
    return Err(ToICUError(status));
  }

  UConstrainedFieldPosition* fpos = ucfpos_open(&status);
  if (U_FAILURE(status)) {
    return Err(ToICUError(status));
  }
  ScopedICUObject<UConstrainedFieldPosition, ucfpos_close> toCloseFpos(fpos);

  Maybe<double> number = start;
  bool isNegative = startIsNegative;

  NumberPartSourceMap sourceMap;

  // Vacuum up fields in the overall formatted string.
  NumberFormatFields fields;

  while (true) {
    bool hasMore = ufmtval_nextPosition(formattedValue, fpos, &status);
    if (U_FAILURE(status)) {
      return Err(ToICUError(status));
    }
    if (!hasMore) {
      break;
    }

    int32_t category = ucfpos_getCategory(fpos, &status);
    if (U_FAILURE(status)) {
      return Err(ToICUError(status));
    }

    int32_t fieldName = ucfpos_getField(fpos, &status);
    if (U_FAILURE(status)) {
      return Err(ToICUError(status));
    }

    int32_t beginIndex, endIndex;
    ucfpos_getIndexes(fpos, &beginIndex, &endIndex, &status);
    if (U_FAILURE(status)) {
      return Err(ToICUError(status));
    }

    if (category == UFIELD_CATEGORY_NUMBER_RANGE_SPAN) {
      // The special field category UFIELD_CATEGORY_NUMBER_RANGE_SPAN has only
      // two allowed values (0 or 1), indicating the begin of the start resp.
      // end number.
      MOZ_ASSERT(fieldName == 0 || fieldName == 1,
                 "span category has unexpected value");

      if (fieldName == 0) {
        number = start;
        isNegative = startIsNegative;

        sourceMap.start = {uint32_t(beginIndex), uint32_t(endIndex)};
      } else {
        number = end;
        isNegative = endIsNegative;

        sourceMap.end = {uint32_t(beginIndex), uint32_t(endIndex)};
      }

      continue;
    }

    // Ignore categories other than UFIELD_CATEGORY_NUMBER.
    if (category != UFIELD_CATEGORY_NUMBER) {
      continue;
    }

    Maybe<NumberPartType> partType = GetPartTypeForNumberField(
        UNumberFormatFields(fieldName), number, isNegative, mFormatForUnit);
    if (!partType || !fields.append(*partType, beginIndex, endIndex)) {
      return Err(ToICUError(status));
    }
  }

  if (!fields.toPartsVector(utf16Length, sourceMap, parts)) {
    return Err(ToICUError(status));
  }

  return std::u16string_view(utf16Str, static_cast<size_t>(utf16Length));
}

}  // namespace mozilla::intl