NumberParser.cpp (1447B)
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 #include "mozilla/intl/NumberParser.h" 5 6 namespace mozilla::intl { 7 8 /*static*/ Result<UniquePtr<NumberParser>, ICUError> NumberParser::TryCreate( 9 std::string_view aLocale, bool aUseGrouping) { 10 UniquePtr<NumberParser> nf = MakeUnique<NumberParser>(); 11 12 UErrorCode status = U_ZERO_ERROR; 13 nf->mNumberFormat = 14 unum_open(UNUM_DECIMAL, nullptr, 0, AssertNullTerminatedString(aLocale), 15 nullptr, &status); 16 if (U_FAILURE(status)) { 17 return Err(ToICUError(status)); 18 } 19 20 if (!aUseGrouping) { 21 unum_setAttribute(nf->mNumberFormat.GetMut(), UNUM_GROUPING_USED, UBool(0)); 22 } 23 24 return nf; 25 } 26 27 NumberParser::~NumberParser() { 28 if (mNumberFormat) { 29 unum_close(mNumberFormat.GetMut()); 30 } 31 } 32 33 Result<std::pair<double, int32_t>, ICUError> NumberParser::ParseDouble( 34 Span<const char16_t> aDouble) const { 35 UErrorCode status = U_ZERO_ERROR; 36 int32_t parsePos = 0; 37 double value = unum_parseDouble(mNumberFormat.GetConst(), aDouble.data(), 38 static_cast<int32_t>(aDouble.size()), 39 &parsePos, &status); 40 if (U_FAILURE(status)) { 41 return Err(ToICUError(status)); 42 } 43 return std::make_pair(value, parsePos); 44 } 45 46 } // namespace mozilla::intl