| 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 |
|
| 5 |
#ifndef intl_components_ICUUtils_h |
| 6 |
#define intl_components_ICUUtils_h |
| 7 |
|
| 8 |
#include "unicode/uenum.h" |
| 9 |
#include "unicode/utypes.h" |
| 10 |
#include "mozilla/Buffer.h" |
| 11 |
#include "mozilla/DebugOnly.h" |
| 12 |
#include "mozilla/Maybe.h" |
| 13 |
#include "mozilla/Result.h" |
| 14 |
#include "mozilla/Span.h" |
| 15 |
#include "mozilla/Utf8.h" |
| 16 |
#include "mozilla/Vector.h" |
| 17 |
#include "mozilla/intl/ICUError.h" |
| 18 |
|
| 19 |
// When building standalone js shell, it will include headers from |
| 20 |
// intl/components if JS_HAS_INTL_API is true (the default value), but js shell |
| 21 |
// won't include headers from XPCOM, so don't include nsTArray.h when building |
| 22 |
// standalone js shell. |
| 23 |
#ifndef JS_STANDALONE |
| 24 |
# include "nsTArray.h" |
| 25 |
#endif |
| 26 |
|
| 27 |
#include <cstring> |
| 28 |
#include <iterator> |
| 29 |
#include <stddef.h> |
| 30 |
#include <stdint.h> |
| 31 |
#include <string> |
| 32 |
#include <string_view> |
| 33 |
|
| 34 |
struct UFormattedValue; |
| 35 |
namespace mozilla::intl { |
| 36 |
|
| 37 |
template <typename CharType> |
| 38 |
static inline CharType* AssertNullTerminatedString(Span<CharType> aSpan) { |
| 39 |
// Intentionally check one past the last character, because we expect that the |
| 40 |
// NUL character isn't part of the string. |
| 41 |
MOZ_ASSERT(*(aSpan.data() + aSpan.size()) == '\0'); |
| 42 |
|
| 43 |
// Also ensure there aren't any other NUL characters within the string. |
| 44 |
MOZ_ASSERT(std::char_traits<std::remove_const_t<CharType>>::length( |
| 45 |
aSpan.data()) == aSpan.size()); |
| 46 |
|
| 47 |
return aSpan.data(); |
| 48 |
} |
| 49 |
|
| 50 |
static inline const char* AssertNullTerminatedString(std::string_view aView) { |
| 51 |
// Intentionally check one past the last character, because we expect that the |
| 52 |
// NUL character isn't part of the string. |
| 53 |
MOZ_ASSERT(*(aView.data() + aView.size()) == '\0'); |
| 54 |
|
| 55 |
// Also ensure there aren't any other NUL characters within the string. |
| 56 |
MOZ_ASSERT(std::strlen(aView.data()) == aView.size()); |
| 57 |
|
| 58 |
return aView.data(); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Map the "und" locale to an empty string, which ICU uses internally. |
| 63 |
*/ |
| 64 |
static inline const char* IcuLocale(const char* aLocale) { |
| 65 |
// Return the empty string if the input is exactly equal to the string "und". |
| 66 |
const char* locale = aLocale; |
| 67 |
if (!std::strcmp(locale, "und")) { |
| 68 |
locale = ""; // ICU root locale |
| 69 |
} |
| 70 |
return locale; |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Ensure a locale is null-terminated, and map the "und" locale to an empty |
| 75 |
* string, which ICU uses internally. |
| 76 |
*/ |
| 77 |
static inline const char* IcuLocale(Span<const char> aLocale) { |
| 78 |
return IcuLocale(AssertNullTerminatedString(aLocale)); |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* Ensure a locale in the buffer is null-terminated, and map the "und" locale to |
| 83 |
* an empty string, which ICU uses internally. |
| 84 |
*/ |
| 85 |
static inline const char* IcuLocale(const Buffer<char>& aLocale) { |
| 86 |
return IcuLocale(Span(aLocale.begin(), aLocale.Length() - 1)); |
| 87 |
} |
| 88 |
|
| 89 |
using ICUResult = Result<Ok, ICUError>; |
| 90 |
|
| 91 |
/** |
| 92 |
* Convert a UErrorCode to ICUError. This will correctly apply the OutOfMemory |
| 93 |
* case. |
| 94 |
*/ |
| 95 |
ICUError ToICUError(UErrorCode status); |
| 96 |
|
| 97 |
/** |
| 98 |
* Convert a UErrorCode to ICUResult. This will correctly apply the OutOfMemory |
| 99 |
* case. |
| 100 |
*/ |
| 101 |
ICUResult ToICUResult(UErrorCode status); |
| 102 |
|
| 103 |
/** |
| 104 |
* The ICU status can complain about a string not being terminated, but this |
| 105 |
* is fine for this API, as it deals with the mozilla::Span that has a pointer |
| 106 |
* and a length. |
| 107 |
*/ |
| 108 |
static inline bool ICUSuccessForStringSpan(UErrorCode status) { |
| 109 |
return U_SUCCESS(status) || status == U_STRING_NOT_TERMINATED_WARNING; |
| 110 |
} |
| 111 |
|
| 112 |
/** |
| 113 |
* This class enforces that the unified mozilla::intl methods match the |
| 114 |
* const-ness of the underlying ICU4C API calls. const ICU4C APIs take a const |
| 115 |
* pointer, while mutable ones take a non-const pointer. |
| 116 |
* |
| 117 |
* For const ICU4C calls use: |
| 118 |
* ICUPointer::GetConst(). |
| 119 |
* |
| 120 |
* For non-const ICU4C calls use: |
| 121 |
* ICUPointer::GetMut(). |
| 122 |
* |
| 123 |
* This will propagate the `const` specifier from the ICU4C API call to the |
| 124 |
* unified method, and it will be enforced by the compiler. This helps ensures |
| 125 |
* a consistence and correct implementation. |
| 126 |
*/ |
| 127 |
template <typename T> |
| 128 |
class ICUPointer { |
| 129 |
public: |
| 130 |
explicit ICUPointer(T* aPointer) : mPointer(aPointer) {} |
| 131 |
|
| 132 |
// Only allow moves of ICUPointers, no copies. |
| 133 |
ICUPointer(ICUPointer&& other) noexcept = default; |
| 134 |
ICUPointer& operator=(ICUPointer&& other) noexcept = default; |
| 135 |
|
| 136 |
// Implicitly take ownership of a raw pointer through copy assignment. |
| 137 |
ICUPointer& operator=(T* aPointer) noexcept { |
| 138 |
mPointer = aPointer; |
| 139 |
return *this; |
| 140 |
}; |
| 141 |
|
| 142 |
const T* GetConst() const { return const_cast<const T*>(mPointer); } |
| 143 |
T* GetMut() { return mPointer; } |
| 144 |
|
| 145 |
explicit operator bool() const { return !!mPointer; } |
| 146 |
|
| 147 |
private: |
| 148 |
T* mPointer; |
| 149 |
}; |
| 150 |
|
| 151 |
/** |
| 152 |
* Calling into ICU with the C-API can be a bit tricky. This function wraps up |
| 153 |
* the relatively risky operations involving pointers, lengths, and buffers into |
| 154 |
* a simpler call. This function accepts a lambda that performs the ICU call, |
| 155 |
* and returns the length of characters in the buffer. When using a temporary |
| 156 |
* stack-based buffer, the calls can often be done in one trip. However, if |
| 157 |
* additional memory is needed, this function will call the C-API twice, in |
| 158 |
* order to first get the size of the result, and then second to copy the result |
| 159 |
* over to the buffer. |
| 160 |
*/ |
| 161 |
template <typename ICUStringFunction, typename Buffer> |
| 162 |
static ICUResult FillBufferWithICUCall(Buffer& buffer, |
| 163 |
const ICUStringFunction& strFn) { |
| 164 |
static_assert(std::is_same_v<typename Buffer::CharType, char16_t> || |
| 165 |
std::is_same_v<typename Buffer::CharType, char> || |
| 166 |
std::is_same_v<typename Buffer::CharType, uint8_t>); |
| 167 |
|
| 168 |
UErrorCode status = U_ZERO_ERROR; |
| 169 |
int32_t length = strFn(buffer.data(), buffer.capacity(), &status); |
| 170 |
if (status == U_BUFFER_OVERFLOW_ERROR) { |
| 171 |
MOZ_ASSERT(length >= 0); |
| 172 |
|
| 173 |
if (!buffer.reserve(length)) { |
| 174 |
return Err(ICUError::OutOfMemory); |
| 175 |
} |
| 176 |
|
| 177 |
status = U_ZERO_ERROR; |
| 178 |
mozilla::DebugOnly<int32_t> length2 = strFn(buffer.data(), length, &status); |
| 179 |
MOZ_ASSERT(length == length2); |
| 180 |
} |
| 181 |
if (!ICUSuccessForStringSpan(status)) { |
| 182 |
return Err(ToICUError(status)); |
| 183 |
} |
| 184 |
|
| 185 |
buffer.written(length); |
| 186 |
|
| 187 |
return Ok{}; |
| 188 |
} |
| 189 |
|
| 190 |
/** |
| 191 |
* Adaptor for mozilla::Vector to implement the Buffer interface. |
| 192 |
*/ |
| 193 |
template <typename T, size_t N> |
| 194 |
class VectorToBufferAdaptor { |
| 195 |
mozilla::Vector<T, N>& vector; |
| 196 |
|
| 197 |
public: |
| 198 |
using CharType = T; |
| 199 |
|
| 200 |
explicit VectorToBufferAdaptor(mozilla::Vector<T, N>& vector) |
| 201 |
: vector(vector) {} |
| 202 |
|
| 203 |
T* data() { return vector.begin(); } |
| 204 |
|
| 205 |
size_t capacity() const { return vector.capacity(); } |
| 206 |
|
| 207 |
bool reserve(size_t length) { return vector.reserve(length); } |
| 208 |
|
| 209 |
void written(size_t length) { |
| 210 |
mozilla::DebugOnly<bool> result = vector.resizeUninitialized(length); |
| 211 |
MOZ_ASSERT(result); |
| 212 |
} |
| 213 |
}; |
| 214 |
|
| 215 |
/** |
| 216 |
* An overload of FillBufferWithICUCall that accepts a mozilla::Vector rather |
| 217 |
* than a Buffer. |
| 218 |
*/ |
| 219 |
template <typename ICUStringFunction, size_t InlineSize, typename CharType> |
| 220 |
static ICUResult FillBufferWithICUCall(Vector<CharType, InlineSize>& vector, |
| 221 |
const ICUStringFunction& strFn) { |
| 222 |
VectorToBufferAdaptor buffer(vector); |
| 223 |
return FillBufferWithICUCall(buffer, strFn); |
| 224 |
} |
| 225 |
|
| 226 |
#ifndef JS_STANDALONE |
| 227 |
/** |
| 228 |
* mozilla::intl APIs require sizeable buffers. This class abstracts over |
| 229 |
* the nsTArray. |
| 230 |
*/ |
| 231 |
template <typename T> |
| 232 |
class nsTArrayToBufferAdapter { |
| 233 |
public: |
| 234 |
using CharType = T; |
| 235 |
|
| 236 |
// Do not allow copy or move. Move could be added in the future if needed. |
| 237 |
nsTArrayToBufferAdapter(const nsTArrayToBufferAdapter&) = delete; |
| 238 |
nsTArrayToBufferAdapter& operator=(const nsTArrayToBufferAdapter&) = delete; |
| 239 |
|
| 240 |
explicit nsTArrayToBufferAdapter(nsTArray<CharType>& aArray) |
| 241 |
: mArray(aArray) {} |
| 242 |
|
| 243 |
/** |
| 244 |
* Ensures the buffer has enough space to accommodate |size| elements. |
| 245 |
*/ |
| 246 |
[[nodiscard]] bool reserve(size_t size) { |
| 247 |
// Use fallible behavior here. |
| 248 |
return mArray.SetCapacity(size, fallible); |
| 249 |
} |
| 250 |
|
| 251 |
/** |
| 252 |
* Returns the raw data inside the buffer. |
| 253 |
*/ |
| 254 |
CharType* data() { return mArray.Elements(); } |
| 255 |
|
| 256 |
/** |
| 257 |
* Returns the count of elements written into the buffer. |
| 258 |
*/ |
| 259 |
size_t length() const { return mArray.Length(); } |
| 260 |
|
| 261 |
/** |
| 262 |
* Returns the buffer's overall capacity. |
| 263 |
*/ |
| 264 |
size_t capacity() const { return mArray.Capacity(); } |
| 265 |
|
| 266 |
/** |
| 267 |
* Resizes the buffer to the given amount of written elements. |
| 268 |
*/ |
| 269 |
void written(size_t amount) { |
| 270 |
MOZ_ASSERT(amount <= mArray.Capacity()); |
| 271 |
// This sets |mArray|'s internal size so that it matches how much was |
| 272 |
// written. This is necessary because the write happens across FFI |
| 273 |
// boundaries. |
| 274 |
mArray.SetLengthAndRetainStorage(amount); |
| 275 |
} |
| 276 |
|
| 277 |
private: |
| 278 |
nsTArray<CharType>& mArray; |
| 279 |
}; |
| 280 |
|
| 281 |
template <typename T, size_t N> |
| 282 |
class AutoTArrayToBufferAdapter : public nsTArrayToBufferAdapter<T> { |
| 283 |
using nsTArrayToBufferAdapter<T>::nsTArrayToBufferAdapter; |
| 284 |
}; |
| 285 |
|
| 286 |
/** |
| 287 |
* An overload of FillBufferWithICUCall that accepts a nsTArray. |
| 288 |
*/ |
| 289 |
template <typename ICUStringFunction, typename CharType> |
| 290 |
static ICUResult FillBufferWithICUCall(nsTArray<CharType>& array, |
| 291 |
const ICUStringFunction& strFn) { |
| 292 |
nsTArrayToBufferAdapter<CharType> buffer(array); |
| 293 |
return FillBufferWithICUCall(buffer, strFn); |
| 294 |
} |
| 295 |
|
| 296 |
template <typename ICUStringFunction, typename CharType, size_t N> |
| 297 |
static ICUResult FillBufferWithICUCall(AutoTArray<CharType, N>& array, |
| 298 |
const ICUStringFunction& strFn) { |
| 299 |
AutoTArrayToBufferAdapter<CharType, N> buffer(array); |
| 300 |
return FillBufferWithICUCall(buffer, strFn); |
| 301 |
} |
| 302 |
#endif |
| 303 |
|
| 304 |
/** |
| 305 |
* Fill a UTF-8 or a UTF-16 buffer with a UTF-16 span. ICU4C mostly uses UTF-16 |
| 306 |
* internally, but different consumers may have different situations with their |
| 307 |
* buffers. |
| 308 |
*/ |
| 309 |
template <typename Buffer> |
| 310 |
[[nodiscard]] bool FillBuffer(Span<const char16_t> utf16Span, |
| 311 |
Buffer& targetBuffer) { |
| 312 |
static_assert(std::is_same_v<typename Buffer::CharType, char> || |
| 313 |
std::is_same_v<typename Buffer::CharType, unsigned char> || |
| 314 |
std::is_same_v<typename Buffer::CharType, char16_t>); |
| 315 |
|
| 316 |
if constexpr (std::is_same_v<typename Buffer::CharType, char> || |
| 317 |
std::is_same_v<typename Buffer::CharType, unsigned char>) { |
| 318 |
if (utf16Span.Length() & mozilla::tl::MulOverflowMask<3>::value) { |
| 319 |
// Tripling the size of the buffer overflows the size_t. |
| 320 |
return false; |
| 321 |
} |
| 322 |
|
| 323 |
if (!targetBuffer.reserve(3 * utf16Span.Length())) { |
| 324 |
return false; |
| 325 |
} |
| 326 |
|
| 327 |
size_t amount = ConvertUtf16toUtf8( |
| 328 |
utf16Span, Span(reinterpret_cast<char*>(targetBuffer.data()), |
| 329 |
targetBuffer.capacity())); |
| 330 |
|
| 331 |
targetBuffer.written(amount); |
| 332 |
} |
| 333 |
if constexpr (std::is_same_v<typename Buffer::CharType, char16_t>) { |
| 334 |
size_t amount = utf16Span.Length(); |
| 335 |
if (!targetBuffer.reserve(amount)) { |
| 336 |
return false; |
| 337 |
} |
| 338 |
for (size_t i = 0; i < amount; i++) { |
| 339 |
targetBuffer.data()[i] = utf16Span[i]; |
| 340 |
} |
| 341 |
targetBuffer.written(amount); |
| 342 |
} |
| 343 |
|
| 344 |
return true; |
| 345 |
} |
| 346 |
|
| 347 |
/** |
| 348 |
* Fill a UTF-8 or a UTF-16 buffer with a UTF-8 span. ICU4C mostly uses UTF-16 |
| 349 |
* internally, but different consumers may have different situations with their |
| 350 |
* buffers. |
| 351 |
*/ |
| 352 |
template <typename Buffer> |
| 353 |
[[nodiscard]] bool FillBuffer(Span<const char> utf8Span, Buffer& targetBuffer) { |
| 354 |
static_assert(std::is_same_v<typename Buffer::CharType, char> || |
| 355 |
std::is_same_v<typename Buffer::CharType, unsigned char> || |
| 356 |
std::is_same_v<typename Buffer::CharType, char16_t>); |
| 357 |
|
| 358 |
if constexpr (std::is_same_v<typename Buffer::CharType, char> || |
| 359 |
std::is_same_v<typename Buffer::CharType, unsigned char>) { |
| 360 |
size_t amount = utf8Span.Length(); |
| 361 |
if (!targetBuffer.reserve(amount)) { |
| 362 |
return false; |
| 363 |
} |
| 364 |
for (size_t i = 0; i < amount; i++) { |
| 365 |
targetBuffer.data()[i] = |
| 366 |
// Static cast in case of a mismatch between `unsigned char` and |
| 367 |
// `char` |
| 368 |
static_cast<typename Buffer::CharType>(utf8Span[i]); |
| 369 |
} |
| 370 |
targetBuffer.written(amount); |
| 371 |
} |
| 372 |
if constexpr (std::is_same_v<typename Buffer::CharType, char16_t>) { |
| 373 |
if (!targetBuffer.reserve(utf8Span.Length() + 1)) { |
| 374 |
return false; |
| 375 |
} |
| 376 |
|
| 377 |
size_t amount = ConvertUtf8toUtf16( |
| 378 |
utf8Span, Span(targetBuffer.data(), targetBuffer.capacity())); |
| 379 |
|
| 380 |
targetBuffer.written(amount); |
| 381 |
} |
| 382 |
|
| 383 |
return true; |
| 384 |
} |
| 385 |
|
| 386 |
/** |
| 387 |
* It is convenient for callers to be able to pass in UTF-8 strings to the API. |
| 388 |
* This function can be used to convert that to a stack-allocated UTF-16 |
| 389 |
* mozilla::Vector that can then be passed into ICU calls. The string will be |
| 390 |
* null terminated. |
| 391 |
*/ |
| 392 |
template <size_t StackSize> |
| 393 |
[[nodiscard]] static bool FillUTF16Vector( |
| 394 |
Span<const char> utf8Span, |
| 395 |
mozilla::Vector<char16_t, StackSize>& utf16TargetVec) { |
| 396 |
// Per ConvertUtf8toUtf16: The length of aDest must be at least one greater |
| 397 |
// than the length of aSource. This additional length will be used for null |
| 398 |
// termination. |
| 399 |
if (!utf16TargetVec.reserve(utf8Span.Length() + 1)) { |
| 400 |
return false; |
| 401 |
} |
| 402 |
|
| 403 |
// ConvertUtf8toUtf16 fills the buffer with the data, but the length of the |
| 404 |
// vector is unchanged. |
| 405 |
size_t length = ConvertUtf8toUtf16( |
| 406 |
utf8Span, Span(utf16TargetVec.begin(), utf16TargetVec.capacity())); |
| 407 |
|
| 408 |
// Assert that the last element is free for writing a null terminator. |
| 409 |
MOZ_ASSERT(length < utf16TargetVec.capacity()); |
| 410 |
utf16TargetVec.begin()[length] = '\0'; |
| 411 |
|
| 412 |
// The call to resizeUninitialized notifies the vector of how much was written |
| 413 |
// exclusive of the null terminated character. |
| 414 |
return utf16TargetVec.resizeUninitialized(length); |
| 415 |
} |
| 416 |
|
| 417 |
/** |
| 418 |
* An iterable class that wraps calls to the ICU UEnumeration C API. |
| 419 |
* |
| 420 |
* Usage: |
| 421 |
* |
| 422 |
* // Make sure the range expression is non-temporary, otherwise there is a |
| 423 |
* // risk of undefined behavior: |
| 424 |
* auto result = Calendar::GetBcp47KeywordValuesForLocale("en-US"); |
| 425 |
* |
| 426 |
* for (auto name : result.unwrap()) { |
| 427 |
* MOZ_ASSERT(name.unwrap(), "An iterable value exists".); |
| 428 |
* } |
| 429 |
*/ |
| 430 |
template <typename CharType, typename T, T(Mapper)(const CharType*, int32_t)> |
| 431 |
class Enumeration { |
| 432 |
public: |
| 433 |
class Iterator; |
| 434 |
friend class Iterator; |
| 435 |
|
| 436 |
// Transfer ownership of the UEnumeration in the move constructor. |
| 437 |
Enumeration(Enumeration&& other) noexcept |
| 438 |
: mUEnumeration(other.mUEnumeration) { |
| 439 |
other.mUEnumeration = nullptr; |
| 440 |
} |
| 441 |
|
| 442 |
// Transfer ownership of the UEnumeration in the move assignment operator. |
| 443 |
Enumeration& operator=(Enumeration&& other) noexcept { |
| 444 |
if (this == &other) { |
| 445 |
return *this; |
| 446 |
} |
| 447 |
if (mUEnumeration) { |
| 448 |
uenum_close(mUEnumeration); |
| 449 |
} |
| 450 |
mUEnumeration = other.mUEnumeration; |
| 451 |
other.mUEnumeration = nullptr; |
| 452 |
return *this; |
| 453 |
} |
| 454 |
|
| 455 |
class Iterator { |
| 456 |
Enumeration& mEnumeration; |
| 457 |
// `Nothing` signifies that no enumeration has been loaded through ICU yet. |
| 458 |
Maybe<int32_t> mIteration = Nothing{}; |
| 459 |
const CharType* mNext = nullptr; |
| 460 |
int32_t mNextLength = 0; |
| 461 |
|
| 462 |
public: |
| 463 |
using value_type = const CharType*; |
| 464 |
using reference = T; |
| 465 |
using iterator_category = std::input_iterator_tag; |
| 466 |
|
| 467 |
explicit Iterator(Enumeration& aEnumeration, bool aIsBegin) |
| 468 |
: mEnumeration(aEnumeration) { |
| 469 |
if (aIsBegin) { |
| 470 |
AdvanceUEnum(); |
| 471 |
} |
| 472 |
} |
| 473 |
|
| 474 |
Iterator& operator++() { |
| 475 |
AdvanceUEnum(); |
| 476 |
return *this; |
| 477 |
} |
| 478 |
|
| 479 |
Iterator operator++(int) { |
| 480 |
Iterator retval = *this; |
| 481 |
++(*this); |
| 482 |
return retval; |
| 483 |
} |
| 484 |
|
| 485 |
bool operator==(Iterator other) const { |
| 486 |
return mIteration == other.mIteration; |
| 487 |
} |
| 488 |
|
| 489 |
bool operator!=(Iterator other) const { return !(*this == other); } |
| 490 |
|
| 491 |
T operator*() const { |
| 492 |
// Map the iterated value to something new. |
| 493 |
return Mapper(mNext, mNextLength); |
| 494 |
} |
| 495 |
|
| 496 |
private: |
| 497 |
void AdvanceUEnum() { |
| 498 |
if (mIteration.isNothing()) { |
| 499 |
mIteration = Some(-1); |
| 500 |
} |
| 501 |
UErrorCode status = U_ZERO_ERROR; |
| 502 |
if constexpr (std::is_same_v<CharType, char16_t>) { |
| 503 |
mNext = uenum_unext(mEnumeration.mUEnumeration, &mNextLength, &status); |
| 504 |
} else { |
| 505 |
static_assert(std::is_same_v<CharType, char>, |
| 506 |
"Only char16_t and char are supported by " |
| 507 |
"mozilla::intl::Enumeration."); |
| 508 |
mNext = uenum_next(mEnumeration.mUEnumeration, &mNextLength, &status); |
| 509 |
} |
| 510 |
if (U_FAILURE(status)) { |
| 511 |
mNext = nullptr; |
| 512 |
} |
| 513 |
|
| 514 |
if (mNext) { |
| 515 |
(*mIteration)++; |
| 516 |
} else { |
| 517 |
// The iterator is complete. |
| 518 |
mIteration = Nothing{}; |
| 519 |
} |
| 520 |
} |
| 521 |
}; |
| 522 |
|
| 523 |
Iterator begin() { return Iterator(*this, true); } |
| 524 |
Iterator end() { return Iterator(*this, false); } |
| 525 |
|
| 526 |
explicit Enumeration(UEnumeration* aUEnumeration) |
| 527 |
: mUEnumeration(aUEnumeration) {} |
| 528 |
|
| 529 |
~Enumeration() { |
| 530 |
if (mUEnumeration) { |
| 531 |
// Only close when the object is being destructed, not moved. |
| 532 |
uenum_close(mUEnumeration); |
| 533 |
} |
| 534 |
} |
| 535 |
|
| 536 |
private: |
| 537 |
UEnumeration* mUEnumeration = nullptr; |
| 538 |
}; |
| 539 |
|
| 540 |
template <typename CharType> |
| 541 |
Result<Span<const CharType>, InternalError> SpanMapper(const CharType* string, |
| 542 |
int32_t length) { |
| 543 |
// Return the raw value from this Iterator. |
| 544 |
if (string == nullptr) { |
| 545 |
return Err(InternalError{}); |
| 546 |
} |
| 547 |
MOZ_ASSERT(length >= 0); |
| 548 |
return Span<const CharType>(string, static_cast<size_t>(length)); |
| 549 |
} |
| 550 |
|
| 551 |
template <typename CharType> |
| 552 |
using SpanResult = Result<Span<const CharType>, InternalError>; |
| 553 |
|
| 554 |
template <typename CharType> |
| 555 |
using SpanEnumeration = Enumeration<CharType, SpanResult<CharType>, SpanMapper>; |
| 556 |
|
| 557 |
/** |
| 558 |
* An iterable class that wraps calls to ICU's available locales API. |
| 559 |
*/ |
| 560 |
template <int32_t(CountAvailable)(), const char*(GetAvailable)(int32_t)> |
| 561 |
class AvailableLocalesEnumeration final { |
| 562 |
// The overall count of available locales. |
| 563 |
int32_t mLocalesCount = 0; |
| 564 |
|
| 565 |
public: |
| 566 |
AvailableLocalesEnumeration() { mLocalesCount = CountAvailable(); } |
| 567 |
|
| 568 |
class Iterator { |
| 569 |
public: |
| 570 |
// std::iterator traits. |
| 571 |
using iterator_category = std::input_iterator_tag; |
| 572 |
using value_type = const char*; |
| 573 |
using difference_type = ptrdiff_t; |
| 574 |
using pointer = value_type*; |
| 575 |
using reference = value_type&; |
| 576 |
|
| 577 |
private: |
| 578 |
// The current position in the list of available locales. |
| 579 |
int32_t mLocalesPos = 0; |
| 580 |
|
| 581 |
public: |
| 582 |
explicit Iterator(int32_t aLocalesPos) : mLocalesPos(aLocalesPos) {} |
| 583 |
|
| 584 |
Iterator& operator++() { |
| 585 |
mLocalesPos++; |
| 586 |
return *this; |
| 587 |
} |
| 588 |
|
| 589 |
Iterator operator++(int) { |
| 590 |
Iterator result = *this; |
| 591 |
++(*this); |
| 592 |
return result; |
| 593 |
} |
| 594 |
|
| 595 |
bool operator==(const Iterator& aOther) const { |
| 596 |
return mLocalesPos == aOther.mLocalesPos; |
| 597 |
} |
| 598 |
|
| 599 |
bool operator!=(const Iterator& aOther) const { return !(*this == aOther); } |
| 600 |
|
| 601 |
value_type operator*() const { return GetAvailable(mLocalesPos); } |
| 602 |
}; |
| 603 |
|
| 604 |
// std::iterator begin() and end() methods. |
| 605 |
|
| 606 |
/** |
| 607 |
* Return an iterator pointing to the first available locale. |
| 608 |
*/ |
| 609 |
Iterator begin() const { return Iterator(0); } |
| 610 |
|
| 611 |
/** |
| 612 |
* Return an iterator pointing to one past the last available locale. |
| 613 |
*/ |
| 614 |
Iterator end() const { return Iterator(mLocalesCount); } |
| 615 |
}; |
| 616 |
|
| 617 |
/** |
| 618 |
* A helper class to wrap calling ICU function in cpp file so we don't have to |
| 619 |
* include the ICU header here. |
| 620 |
*/ |
| 621 |
class FormattedResult { |
| 622 |
protected: |
| 623 |
static Result<Span<const char16_t>, ICUError> ToSpanImpl( |
| 624 |
const UFormattedValue* value); |
| 625 |
}; |
| 626 |
|
| 627 |
/** |
| 628 |
* A RAII class to hold the formatted value of format result. |
| 629 |
* |
| 630 |
* The caller will need to create this AutoFormattedResult on the stack, with |
| 631 |
* the following parameters: |
| 632 |
* 1. Native ICU type. |
| 633 |
* 2. An ICU function which opens the result. |
| 634 |
* 3. An ICU function which can get the result as UFormattedValue. |
| 635 |
* 4. An ICU function which closes the result. |
| 636 |
* |
| 637 |
* After the object is created, caller needs to call IsValid() method to check |
| 638 |
* if the native object has been created properly, and then passes this |
| 639 |
* object to other format interfaces. |
| 640 |
* The format result will be stored in this object, the caller can use ToSpan() |
| 641 |
* method to get the formatted string. |
| 642 |
* |
| 643 |
* The methods GetFormatted() and Value() are private methods since they expose |
| 644 |
* native ICU types. If the caller wants to call these methods, the caller needs |
| 645 |
* to register itself as a friend class in AutoFormattedResult. |
| 646 |
* |
| 647 |
* The formatted value and the native ICU object will be released once this |
| 648 |
* class is destructed. |
| 649 |
*/ |
| 650 |
template <typename T, T*(Open)(UErrorCode*), |
| 651 |
const UFormattedValue*(GetValue)(const T*, UErrorCode*), |
| 652 |
void(Close)(T*)> |
| 653 |
class MOZ_RAII AutoFormattedResult : FormattedResult { |
| 654 |
public: |
| 655 |
AutoFormattedResult() { |
| 656 |
mFormatted = Open(&mError); |
| 657 |
if (U_FAILURE(mError)) { |
| 658 |
mFormatted = nullptr; |
| 659 |
} |
| 660 |
} |
| 661 |
~AutoFormattedResult() { |
| 662 |
if (mFormatted) { |
| 663 |
Close(mFormatted); |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
AutoFormattedResult(const AutoFormattedResult& other) = delete; |
| 668 |
AutoFormattedResult& operator=(const AutoFormattedResult& other) = delete; |
| 669 |
|
| 670 |
AutoFormattedResult(AutoFormattedResult&& other) = delete; |
| 671 |
AutoFormattedResult& operator=(AutoFormattedResult&& other) = delete; |
| 672 |
|
| 673 |
/** |
| 674 |
* Check if the native UFormattedDateInterval was created successfully. |
| 675 |
*/ |
| 676 |
bool IsValid() const { return !!mFormatted; } |
| 677 |
|
| 678 |
/** |
| 679 |
* Get error code if IsValid() returns false. |
| 680 |
*/ |
| 681 |
ICUError GetError() const { return ToICUError(mError); } |
| 682 |
|
| 683 |
/** |
| 684 |
* Get the formatted result. |
| 685 |
*/ |
| 686 |
Result<Span<const char16_t>, ICUError> ToSpan() const { |
| 687 |
if (!IsValid()) { |
| 688 |
return Err(GetError()); |
| 689 |
} |
| 690 |
|
| 691 |
const UFormattedValue* value = Value(); |
| 692 |
if (!value) { |
| 693 |
return Err(ICUError::InternalError); |
| 694 |
} |
| 695 |
|
| 696 |
return ToSpanImpl(value); |
| 697 |
} |
| 698 |
|
| 699 |
private: |
| 700 |
friend class DateIntervalFormat; |
| 701 |
friend class ListFormat; |
| 702 |
T* GetFormatted() const { return mFormatted; } |
| 703 |
|
| 704 |
const UFormattedValue* Value() const { |
| 705 |
if (!IsValid()) { |
| 706 |
return nullptr; |
| 707 |
} |
| 708 |
|
| 709 |
UErrorCode status = U_ZERO_ERROR; |
| 710 |
const UFormattedValue* value = GetValue(mFormatted, &status); |
| 711 |
if (U_FAILURE(status)) { |
| 712 |
return nullptr; |
| 713 |
} |
| 714 |
|
| 715 |
return value; |
| 716 |
}; |
| 717 |
|
| 718 |
T* mFormatted = nullptr; |
| 719 |
UErrorCode mError = U_ZERO_ERROR; |
| 720 |
}; |
| 721 |
} // namespace mozilla::intl |
| 722 |
|
| 723 |
#endif /* intl_components_ICUUtils_h */ |