NumberFormat.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. /*
  2. * Copyright (c) 2021-2024, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #define AK_DONT_REPLACE_STD
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/QuickSort.h>
  9. #include <AK/Utf8View.h>
  10. #include <LibLocale/ICU.h>
  11. #include <LibLocale/Locale.h>
  12. #include <LibLocale/NumberFormat.h>
  13. #include <LibUnicode/CharacterTypes.h>
  14. #include <math.h>
  15. #include <unicode/numberformatter.h>
  16. #include <unicode/numberrangeformatter.h>
  17. namespace Locale {
  18. NumberFormatStyle number_format_style_from_string(StringView number_format_style)
  19. {
  20. if (number_format_style == "decimal"sv)
  21. return NumberFormatStyle::Decimal;
  22. if (number_format_style == "percent"sv)
  23. return NumberFormatStyle::Percent;
  24. if (number_format_style == "currency"sv)
  25. return NumberFormatStyle::Currency;
  26. if (number_format_style == "unit"sv)
  27. return NumberFormatStyle::Unit;
  28. VERIFY_NOT_REACHED();
  29. }
  30. StringView number_format_style_to_string(NumberFormatStyle number_format_style)
  31. {
  32. switch (number_format_style) {
  33. case NumberFormatStyle::Decimal:
  34. return "decimal"sv;
  35. case NumberFormatStyle::Percent:
  36. return "percent"sv;
  37. case NumberFormatStyle::Currency:
  38. return "currency"sv;
  39. case NumberFormatStyle::Unit:
  40. return "unit"sv;
  41. }
  42. VERIFY_NOT_REACHED();
  43. }
  44. SignDisplay sign_display_from_string(StringView sign_display)
  45. {
  46. if (sign_display == "auto"sv)
  47. return SignDisplay::Auto;
  48. if (sign_display == "never"sv)
  49. return SignDisplay::Never;
  50. if (sign_display == "always"sv)
  51. return SignDisplay::Always;
  52. if (sign_display == "exceptZero"sv)
  53. return SignDisplay::ExceptZero;
  54. if (sign_display == "negative"sv)
  55. return SignDisplay::Negative;
  56. VERIFY_NOT_REACHED();
  57. }
  58. StringView sign_display_to_string(SignDisplay sign_display)
  59. {
  60. switch (sign_display) {
  61. case SignDisplay::Auto:
  62. return "auto"sv;
  63. case SignDisplay::Never:
  64. return "never"sv;
  65. case SignDisplay::Always:
  66. return "always"sv;
  67. case SignDisplay::ExceptZero:
  68. return "exceptZero"sv;
  69. case SignDisplay::Negative:
  70. return "negative"sv;
  71. }
  72. VERIFY_NOT_REACHED();
  73. }
  74. static constexpr UNumberSignDisplay icu_sign_display(SignDisplay sign_display, Optional<CurrencySign> const& currency_sign)
  75. {
  76. switch (sign_display) {
  77. case SignDisplay::Auto:
  78. return currency_sign == CurrencySign::Standard ? UNUM_SIGN_AUTO : UNUM_SIGN_ACCOUNTING;
  79. case SignDisplay::Never:
  80. return UNUM_SIGN_NEVER;
  81. case SignDisplay::Always:
  82. return currency_sign == CurrencySign::Standard ? UNUM_SIGN_ALWAYS : UNUM_SIGN_ACCOUNTING_ALWAYS;
  83. case SignDisplay::ExceptZero:
  84. return currency_sign == CurrencySign::Standard ? UNUM_SIGN_EXCEPT_ZERO : UNUM_SIGN_ACCOUNTING_EXCEPT_ZERO;
  85. case SignDisplay::Negative:
  86. return currency_sign == CurrencySign::Standard ? UNUM_SIGN_NEGATIVE : UNUM_SIGN_ACCOUNTING_NEGATIVE;
  87. }
  88. VERIFY_NOT_REACHED();
  89. }
  90. Notation notation_from_string(StringView notation)
  91. {
  92. if (notation == "standard"sv)
  93. return Notation::Standard;
  94. if (notation == "scientific"sv)
  95. return Notation::Scientific;
  96. if (notation == "engineering"sv)
  97. return Notation::Engineering;
  98. if (notation == "compact"sv)
  99. return Notation::Compact;
  100. VERIFY_NOT_REACHED();
  101. }
  102. StringView notation_to_string(Notation notation)
  103. {
  104. switch (notation) {
  105. case Notation::Standard:
  106. return "standard"sv;
  107. case Notation::Scientific:
  108. return "scientific"sv;
  109. case Notation::Engineering:
  110. return "engineering"sv;
  111. case Notation::Compact:
  112. return "compact"sv;
  113. }
  114. VERIFY_NOT_REACHED();
  115. }
  116. static icu::number::Notation icu_notation(Notation notation, Optional<CompactDisplay> const& compact_display)
  117. {
  118. switch (notation) {
  119. case Notation::Standard:
  120. return icu::number::Notation::simple();
  121. case Notation::Scientific:
  122. return icu::number::Notation::scientific();
  123. case Notation::Engineering:
  124. return icu::number::Notation::engineering();
  125. case Notation::Compact:
  126. switch (*compact_display) {
  127. case CompactDisplay::Short:
  128. return icu::number::Notation::compactShort();
  129. case CompactDisplay::Long:
  130. return icu::number::Notation::compactLong();
  131. }
  132. }
  133. VERIFY_NOT_REACHED();
  134. }
  135. CompactDisplay compact_display_from_string(StringView compact_display)
  136. {
  137. if (compact_display == "short"sv)
  138. return CompactDisplay::Short;
  139. if (compact_display == "long"sv)
  140. return CompactDisplay::Long;
  141. VERIFY_NOT_REACHED();
  142. }
  143. StringView compact_display_to_string(CompactDisplay compact_display)
  144. {
  145. switch (compact_display) {
  146. case CompactDisplay::Short:
  147. return "short"sv;
  148. case CompactDisplay::Long:
  149. return "long"sv;
  150. }
  151. VERIFY_NOT_REACHED();
  152. }
  153. Grouping grouping_from_string(StringView grouping)
  154. {
  155. if (grouping == "always"sv)
  156. return Grouping::Always;
  157. if (grouping == "auto"sv)
  158. return Grouping::Auto;
  159. if (grouping == "min2"sv)
  160. return Grouping::Min2;
  161. if (grouping == "false"sv)
  162. return Grouping::False;
  163. VERIFY_NOT_REACHED();
  164. }
  165. StringView grouping_to_string(Grouping grouping)
  166. {
  167. switch (grouping) {
  168. case Grouping::Always:
  169. return "always"sv;
  170. case Grouping::Auto:
  171. return "auto"sv;
  172. case Grouping::Min2:
  173. return "min2"sv;
  174. case Grouping::False:
  175. return "false"sv;
  176. }
  177. VERIFY_NOT_REACHED();
  178. }
  179. static constexpr UNumberGroupingStrategy icu_grouping_strategy(Grouping grouping)
  180. {
  181. switch (grouping) {
  182. case Grouping::Always:
  183. return UNUM_GROUPING_ON_ALIGNED;
  184. case Grouping::Auto:
  185. return UNUM_GROUPING_AUTO;
  186. case Grouping::Min2:
  187. return UNUM_GROUPING_MIN2;
  188. case Grouping::False:
  189. return UNUM_GROUPING_OFF;
  190. }
  191. VERIFY_NOT_REACHED();
  192. }
  193. CurrencyDisplay currency_display_from_string(StringView currency_display)
  194. {
  195. if (currency_display == "code"sv)
  196. return CurrencyDisplay::Code;
  197. if (currency_display == "symbol"sv)
  198. return CurrencyDisplay::Symbol;
  199. if (currency_display == "narrowSymbol"sv)
  200. return CurrencyDisplay::NarrowSymbol;
  201. if (currency_display == "name"sv)
  202. return CurrencyDisplay::Name;
  203. VERIFY_NOT_REACHED();
  204. }
  205. StringView currency_display_to_string(CurrencyDisplay currency_display)
  206. {
  207. switch (currency_display) {
  208. case CurrencyDisplay::Code:
  209. return "code"sv;
  210. case CurrencyDisplay::Symbol:
  211. return "symbol"sv;
  212. case CurrencyDisplay::NarrowSymbol:
  213. return "narrowSymbol"sv;
  214. case CurrencyDisplay::Name:
  215. return "name"sv;
  216. }
  217. VERIFY_NOT_REACHED();
  218. }
  219. static constexpr UNumberUnitWidth icu_currency_display(CurrencyDisplay currency_display)
  220. {
  221. switch (currency_display) {
  222. case CurrencyDisplay::Code:
  223. return UNUM_UNIT_WIDTH_ISO_CODE;
  224. case CurrencyDisplay::Symbol:
  225. return UNUM_UNIT_WIDTH_SHORT;
  226. case CurrencyDisplay::NarrowSymbol:
  227. return UNUM_UNIT_WIDTH_NARROW;
  228. case CurrencyDisplay::Name:
  229. return UNUM_UNIT_WIDTH_FULL_NAME;
  230. }
  231. VERIFY_NOT_REACHED();
  232. }
  233. CurrencySign currency_sign_from_string(StringView currency_sign)
  234. {
  235. if (currency_sign == "standard"sv)
  236. return CurrencySign::Standard;
  237. if (currency_sign == "accounting"sv)
  238. return CurrencySign::Accounting;
  239. VERIFY_NOT_REACHED();
  240. }
  241. StringView currency_sign_to_string(CurrencySign currency_sign)
  242. {
  243. switch (currency_sign) {
  244. case CurrencySign::Standard:
  245. return "standard"sv;
  246. case CurrencySign::Accounting:
  247. return "accounting"sv;
  248. }
  249. VERIFY_NOT_REACHED();
  250. }
  251. RoundingType rounding_type_from_string(StringView rounding_type)
  252. {
  253. if (rounding_type == "significantDigits"sv)
  254. return RoundingType::SignificantDigits;
  255. if (rounding_type == "fractionDigits"sv)
  256. return RoundingType::FractionDigits;
  257. if (rounding_type == "morePrecision"sv)
  258. return RoundingType::MorePrecision;
  259. if (rounding_type == "lessPrecision"sv)
  260. return RoundingType::LessPrecision;
  261. VERIFY_NOT_REACHED();
  262. }
  263. StringView rounding_type_to_string(RoundingType rounding_type)
  264. {
  265. switch (rounding_type) {
  266. case RoundingType::SignificantDigits:
  267. return "significantDigits"sv;
  268. case RoundingType::FractionDigits:
  269. return "fractionDigits"sv;
  270. case RoundingType::MorePrecision:
  271. return "morePrecision"sv;
  272. case RoundingType::LessPrecision:
  273. return "lessPrecision"sv;
  274. }
  275. VERIFY_NOT_REACHED();
  276. }
  277. RoundingMode rounding_mode_from_string(StringView rounding_mode)
  278. {
  279. if (rounding_mode == "ceil"sv)
  280. return RoundingMode::Ceil;
  281. if (rounding_mode == "expand"sv)
  282. return RoundingMode::Expand;
  283. if (rounding_mode == "floor"sv)
  284. return RoundingMode::Floor;
  285. if (rounding_mode == "halfCeil"sv)
  286. return RoundingMode::HalfCeil;
  287. if (rounding_mode == "halfEven"sv)
  288. return RoundingMode::HalfEven;
  289. if (rounding_mode == "halfExpand"sv)
  290. return RoundingMode::HalfExpand;
  291. if (rounding_mode == "halfFloor"sv)
  292. return RoundingMode::HalfFloor;
  293. if (rounding_mode == "halfTrunc"sv)
  294. return RoundingMode::HalfTrunc;
  295. if (rounding_mode == "trunc"sv)
  296. return RoundingMode::Trunc;
  297. VERIFY_NOT_REACHED();
  298. }
  299. StringView rounding_mode_to_string(RoundingMode rounding_mode)
  300. {
  301. switch (rounding_mode) {
  302. case RoundingMode::Ceil:
  303. return "ceil"sv;
  304. case RoundingMode::Expand:
  305. return "expand"sv;
  306. case RoundingMode::Floor:
  307. return "floor"sv;
  308. case RoundingMode::HalfCeil:
  309. return "halfCeil"sv;
  310. case RoundingMode::HalfEven:
  311. return "halfEven"sv;
  312. case RoundingMode::HalfExpand:
  313. return "halfExpand"sv;
  314. case RoundingMode::HalfFloor:
  315. return "halfFloor"sv;
  316. case RoundingMode::HalfTrunc:
  317. return "halfTrunc"sv;
  318. case RoundingMode::Trunc:
  319. return "trunc"sv;
  320. }
  321. VERIFY_NOT_REACHED();
  322. }
  323. static constexpr UNumberFormatRoundingMode icu_rounding_mode(RoundingMode rounding_mode)
  324. {
  325. switch (rounding_mode) {
  326. case RoundingMode::Ceil:
  327. return UNUM_ROUND_CEILING;
  328. case RoundingMode::Expand:
  329. return UNUM_ROUND_UP;
  330. case RoundingMode::Floor:
  331. return UNUM_ROUND_FLOOR;
  332. case RoundingMode::HalfCeil:
  333. return UNUM_ROUND_HALF_CEILING;
  334. case RoundingMode::HalfEven:
  335. return UNUM_ROUND_HALFEVEN;
  336. case RoundingMode::HalfExpand:
  337. return UNUM_ROUND_HALFUP;
  338. case RoundingMode::HalfFloor:
  339. return UNUM_ROUND_HALF_FLOOR;
  340. case RoundingMode::HalfTrunc:
  341. return UNUM_ROUND_HALFDOWN;
  342. case RoundingMode::Trunc:
  343. return UNUM_ROUND_DOWN;
  344. }
  345. VERIFY_NOT_REACHED();
  346. }
  347. TrailingZeroDisplay trailing_zero_display_from_string(StringView trailing_zero_display)
  348. {
  349. if (trailing_zero_display == "auto"sv)
  350. return TrailingZeroDisplay::Auto;
  351. if (trailing_zero_display == "stripIfInteger"sv)
  352. return TrailingZeroDisplay::StripIfInteger;
  353. VERIFY_NOT_REACHED();
  354. }
  355. StringView trailing_zero_display_to_string(TrailingZeroDisplay trailing_zero_display)
  356. {
  357. switch (trailing_zero_display) {
  358. case TrailingZeroDisplay::Auto:
  359. return "auto"sv;
  360. case TrailingZeroDisplay::StripIfInteger:
  361. return "stripIfInteger"sv;
  362. }
  363. VERIFY_NOT_REACHED();
  364. }
  365. static constexpr UNumberTrailingZeroDisplay icu_trailing_zero_display(TrailingZeroDisplay trailing_zero_display)
  366. {
  367. switch (trailing_zero_display) {
  368. case TrailingZeroDisplay::Auto:
  369. return UNUM_TRAILING_ZERO_AUTO;
  370. case TrailingZeroDisplay::StripIfInteger:
  371. return UNUM_TRAILING_ZERO_HIDE_IF_WHOLE;
  372. }
  373. VERIFY_NOT_REACHED();
  374. }
  375. static constexpr UNumberUnitWidth icu_unit_width(Style unit_display)
  376. {
  377. switch (unit_display) {
  378. case Style::Long:
  379. return UNUM_UNIT_WIDTH_FULL_NAME;
  380. case Style::Short:
  381. return UNUM_UNIT_WIDTH_SHORT;
  382. case Style::Narrow:
  383. return UNUM_UNIT_WIDTH_NARROW;
  384. }
  385. VERIFY_NOT_REACHED();
  386. }
  387. static void apply_display_options(icu::number::LocalizedNumberFormatter& formatter, DisplayOptions const& display_options)
  388. {
  389. UErrorCode status = U_ZERO_ERROR;
  390. switch (display_options.style) {
  391. case NumberFormatStyle::Decimal:
  392. break;
  393. case NumberFormatStyle::Percent:
  394. formatter = formatter.unit(icu::MeasureUnit::getPercent()).scale(icu::number::Scale::byDouble(100));
  395. break;
  396. case NumberFormatStyle::Currency:
  397. formatter = formatter.unit(icu::CurrencyUnit(icu_string_piece(*display_options.currency), status));
  398. formatter = formatter.unitWidth(icu_currency_display(*display_options.currency_display));
  399. VERIFY(icu_success(status));
  400. break;
  401. case NumberFormatStyle::Unit:
  402. formatter = formatter.unit(icu::MeasureUnit::forIdentifier(icu_string_piece(*display_options.unit), status));
  403. formatter = formatter.unitWidth(icu_unit_width(*display_options.unit_display));
  404. VERIFY(icu_success(status));
  405. break;
  406. }
  407. formatter = formatter.sign(icu_sign_display(display_options.sign_display, display_options.currency_sign));
  408. formatter = formatter.notation(icu_notation(display_options.notation, display_options.compact_display));
  409. formatter = formatter.grouping(icu_grouping_strategy(display_options.grouping));
  410. }
  411. static void apply_rounding_options(icu::number::LocalizedNumberFormatter& formatter, RoundingOptions const& rounding_options)
  412. {
  413. auto precision = icu::number::Precision::unlimited();
  414. if (rounding_options.rounding_increment == 1) {
  415. switch (rounding_options.type) {
  416. case RoundingType::SignificantDigits:
  417. precision = icu::number::Precision::minMaxSignificantDigits(*rounding_options.min_significant_digits, *rounding_options.max_significant_digits);
  418. break;
  419. case RoundingType::FractionDigits:
  420. precision = icu::number::Precision::minMaxFraction(*rounding_options.min_fraction_digits, *rounding_options.max_fraction_digits);
  421. break;
  422. case RoundingType::MorePrecision:
  423. precision = icu::number::Precision::minMaxFraction(*rounding_options.min_fraction_digits, *rounding_options.max_fraction_digits)
  424. .withSignificantDigits(*rounding_options.min_significant_digits, *rounding_options.max_significant_digits, UNUM_ROUNDING_PRIORITY_RELAXED);
  425. break;
  426. case RoundingType::LessPrecision:
  427. precision = icu::number::Precision::minMaxFraction(*rounding_options.min_fraction_digits, *rounding_options.max_fraction_digits)
  428. .withSignificantDigits(*rounding_options.min_significant_digits, *rounding_options.max_significant_digits, UNUM_ROUNDING_PRIORITY_STRICT);
  429. break;
  430. }
  431. } else {
  432. auto mantissa = rounding_options.rounding_increment;
  433. auto magnitude = *rounding_options.max_fraction_digits * -1;
  434. precision = icu::number::Precision::incrementExact(mantissa, static_cast<i16>(magnitude))
  435. .withMinFraction(*rounding_options.min_fraction_digits);
  436. }
  437. formatter = formatter.precision(precision.trailingZeroDisplay(icu_trailing_zero_display(rounding_options.trailing_zero_display)));
  438. formatter = formatter.integerWidth(icu::number::IntegerWidth::zeroFillTo(rounding_options.min_integer_digits));
  439. formatter = formatter.roundingMode(icu_rounding_mode(rounding_options.mode));
  440. }
  441. // ICU does not contain a field enumeration for "literal" partitions. Define a custom field so that we may provide a
  442. // type for those partitions.
  443. static constexpr i32 LITERAL_FIELD = -1;
  444. static constexpr StringView icu_number_format_field_to_string(i32 field, NumberFormat::Value const& value, bool is_unit)
  445. {
  446. switch (field) {
  447. case LITERAL_FIELD:
  448. return "literal"sv;
  449. case UNUM_INTEGER_FIELD:
  450. if (auto const* number = value.get_pointer<double>()) {
  451. if (isnan(*number))
  452. return "nan"sv;
  453. if (isinf(*number))
  454. return "infinity"sv;
  455. }
  456. return "integer"sv;
  457. case UNUM_FRACTION_FIELD:
  458. return "fraction"sv;
  459. case UNUM_DECIMAL_SEPARATOR_FIELD:
  460. return "decimal"sv;
  461. case UNUM_EXPONENT_SYMBOL_FIELD:
  462. return "exponentSeparator"sv;
  463. case UNUM_EXPONENT_SIGN_FIELD:
  464. return "exponentMinusSign"sv;
  465. case UNUM_EXPONENT_FIELD:
  466. return "exponentInteger"sv;
  467. case UNUM_GROUPING_SEPARATOR_FIELD:
  468. return "group"sv;
  469. case UNUM_CURRENCY_FIELD:
  470. return "currency"sv;
  471. case UNUM_PERCENT_FIELD:
  472. return is_unit ? "unit"sv : "percentSign"sv;
  473. case UNUM_SIGN_FIELD: {
  474. auto is_negative = value.visit(
  475. [&](double number) { return signbit(number); },
  476. [&](String const& number) { return number.starts_with('-'); });
  477. return is_negative ? "minusSign"sv : "plusSign"sv;
  478. }
  479. case UNUM_MEASURE_UNIT_FIELD:
  480. return "unit"sv;
  481. case UNUM_COMPACT_FIELD:
  482. return "compact"sv;
  483. case UNUM_APPROXIMATELY_SIGN_FIELD:
  484. return "approximatelySign"sv;
  485. }
  486. VERIFY_NOT_REACHED();
  487. }
  488. struct Range {
  489. constexpr bool contains(i32 position) const
  490. {
  491. return start <= position && position < end;
  492. }
  493. constexpr bool operator<(Range const& other) const
  494. {
  495. if (start < other.start)
  496. return true;
  497. if (start == other.start)
  498. return end > other.end;
  499. return false;
  500. }
  501. i32 field { LITERAL_FIELD };
  502. i32 start { 0 };
  503. i32 end { 0 };
  504. };
  505. // ICU will give us overlapping partitions, e.g. for the formatted result "1,234", we will get the following parts:
  506. //
  507. // part="," type=group start=1 end=2
  508. // part="1,234" type=integer start=0 end=5
  509. //
  510. // We need to massage these partitions into non-overlapping parts for ECMA-402:
  511. //
  512. // part="1" type=integer start=0 end=1
  513. // part="," type=group start=1 end=2
  514. // part="234" type=integer start=2 end=5
  515. static void flatten_partitions(Vector<Range>& partitions)
  516. {
  517. if (partitions.size() <= 1)
  518. return;
  519. quick_sort(partitions);
  520. auto subtract_range = [&](auto const& first, auto const& second) -> Vector<Range> {
  521. if (second.start > first.end || first.start > second.end)
  522. return { first };
  523. Vector<Range> result;
  524. if (second.start > first.start)
  525. result.empend(first.field, first.start, second.start);
  526. if (second.end < first.end)
  527. result.empend(first.field, second.end, first.end);
  528. return result;
  529. };
  530. for (size_t i = 0; i < partitions.size(); ++i) {
  531. for (size_t j = i + 1; j < partitions.size(); ++j) {
  532. auto& first = partitions[i];
  533. auto& second = partitions[j];
  534. auto result = subtract_range(first, second);
  535. if (result.is_empty()) {
  536. partitions.remove(i);
  537. --i;
  538. break;
  539. }
  540. first = result[0];
  541. if (result.size() == 2)
  542. partitions.insert(i + 1, result[1]);
  543. }
  544. }
  545. quick_sort(partitions);
  546. }
  547. class NumberFormatImpl : public NumberFormat {
  548. public:
  549. NumberFormatImpl(icu::Locale& locale, icu::number::LocalizedNumberFormatter formatter, bool is_unit)
  550. : m_locale(locale)
  551. , m_formatter(move(formatter))
  552. , m_is_unit(is_unit)
  553. {
  554. }
  555. virtual ~NumberFormatImpl() override = default;
  556. virtual String format(Value const& value) const override
  557. {
  558. UErrorCode status = U_ZERO_ERROR;
  559. auto formatted = format_impl(value);
  560. if (!formatted.has_value())
  561. return {};
  562. auto result = formatted->toTempString(status);
  563. if (icu_failure(status))
  564. return {};
  565. return icu_string_to_string(result);
  566. }
  567. virtual String format_to_decimal(Value const& value) const override
  568. {
  569. UErrorCode status = U_ZERO_ERROR;
  570. auto formatted = format_impl(value);
  571. if (!formatted.has_value())
  572. return {};
  573. auto result = formatted->toDecimalNumber<StringBuilder>(status);
  574. if (icu_failure(status))
  575. return {};
  576. return MUST(result.to_string());
  577. }
  578. virtual Vector<Partition> format_to_parts(Value const& value) const override
  579. {
  580. auto formatted = format_impl(value);
  581. if (!formatted.has_value())
  582. return {};
  583. return format_to_parts_impl(formatted, value, value);
  584. }
  585. virtual String format_range(Value const& start, Value const& end) const override
  586. {
  587. UErrorCode status = U_ZERO_ERROR;
  588. auto formatted = format_range_impl(start, end);
  589. if (!formatted.has_value())
  590. return {};
  591. auto result = formatted->toTempString(status);
  592. if (icu_failure(status))
  593. return {};
  594. return icu_string_to_string(result);
  595. }
  596. virtual Vector<Partition> format_range_to_parts(Value const& start, Value const& end) const override
  597. {
  598. auto formatted = format_range_impl(start, end);
  599. if (!formatted.has_value())
  600. return {};
  601. return format_to_parts_impl(formatted, start, end);
  602. }
  603. private:
  604. static icu::Formattable value_to_formattable(Value const& value)
  605. {
  606. UErrorCode status = U_ZERO_ERROR;
  607. auto formattable = value.visit(
  608. [&](double number) { return icu::Formattable { number }; },
  609. [&](String const& number) { return icu::Formattable(icu_string_piece(number), status); });
  610. VERIFY(icu_success(status));
  611. return formattable;
  612. }
  613. Optional<icu::number::FormattedNumber> format_impl(Value const& value) const
  614. {
  615. UErrorCode status = U_ZERO_ERROR;
  616. auto formatted = value.visit(
  617. [&](double number) {
  618. return m_formatter.formatDouble(number, status);
  619. },
  620. [&](String const& number) {
  621. return m_formatter.formatDecimal(icu_string_piece(number), status);
  622. });
  623. if (icu_failure(status))
  624. return {};
  625. return formatted;
  626. }
  627. Optional<icu::number::FormattedNumberRange> format_range_impl(Value const& start, Value const& end) const
  628. {
  629. UErrorCode status = U_ZERO_ERROR;
  630. if (!m_range_formatter.has_value()) {
  631. auto skeleton = icu::number::NumberFormatter::forSkeleton(m_formatter.toSkeleton(status), status);
  632. if (icu_failure(status))
  633. return {};
  634. auto formatter = icu::number::UnlocalizedNumberRangeFormatter().numberFormatterBoth(move(skeleton)).locale(m_locale);
  635. if (icu_failure(status))
  636. return {};
  637. m_range_formatter = move(formatter);
  638. }
  639. auto formattable_start = value_to_formattable(start);
  640. auto formattable_end = value_to_formattable(end);
  641. auto formatted = m_range_formatter->formatFormattableRange(formattable_start, formattable_end, status);
  642. if (icu_failure(status))
  643. return {};
  644. return formatted;
  645. }
  646. template<typename Formatted>
  647. Vector<Partition> format_to_parts_impl(Formatted const& formatted, Value const& start, Value const& end) const
  648. {
  649. UErrorCode status = U_ZERO_ERROR;
  650. auto formatted_number = formatted->toTempString(status);
  651. if (icu_failure(status))
  652. return {};
  653. Vector<Range> ranges;
  654. ranges.empend(LITERAL_FIELD, 0, formatted_number.length());
  655. icu::ConstrainedFieldPosition position;
  656. Optional<Range> start_range;
  657. Optional<Range> end_range;
  658. while (static_cast<bool>(formatted->nextPosition(position, status)) && icu_success(status)) {
  659. if (position.getCategory() == UFIELD_CATEGORY_NUMBER_RANGE_SPAN) {
  660. auto& range = position.getField() == 0 ? start_range : end_range;
  661. range = Range { position.getField(), position.getStart(), position.getLimit() };
  662. } else {
  663. ranges.empend(position.getField(), position.getStart(), position.getLimit());
  664. }
  665. }
  666. flatten_partitions(ranges);
  667. auto apply_to_partition = [&](Partition& partition, auto field, auto index) {
  668. if (start_range.has_value() && start_range->contains(index)) {
  669. partition.type = icu_number_format_field_to_string(field, start, m_is_unit);
  670. partition.source = "startRange"sv;
  671. return;
  672. }
  673. if (end_range.has_value() && end_range->contains(index)) {
  674. partition.type = icu_number_format_field_to_string(field, end, m_is_unit);
  675. partition.source = "endRange"sv;
  676. return;
  677. }
  678. partition.type = icu_number_format_field_to_string(field, end, m_is_unit);
  679. partition.source = "shared"sv;
  680. };
  681. Vector<Partition> result;
  682. result.ensure_capacity(ranges.size());
  683. for (auto const& range : ranges) {
  684. auto value = formatted_number.tempSubStringBetween(range.start, range.end);
  685. Partition partition;
  686. partition.value = icu_string_to_string(value);
  687. apply_to_partition(partition, range.field, range.start);
  688. result.unchecked_append(move(partition));
  689. }
  690. return result;
  691. }
  692. icu::Locale& m_locale;
  693. icu::number::LocalizedNumberFormatter m_formatter;
  694. mutable Optional<icu::number::LocalizedNumberRangeFormatter> m_range_formatter;
  695. bool m_is_unit { false };
  696. };
  697. NonnullOwnPtr<NumberFormat> NumberFormat::create(
  698. StringView locale,
  699. StringView numbering_system,
  700. DisplayOptions const& display_options,
  701. RoundingOptions const& rounding_options)
  702. {
  703. UErrorCode status = U_ZERO_ERROR;
  704. auto locale_data = LocaleData::for_locale(locale);
  705. VERIFY(locale_data.has_value());
  706. auto formatter = icu::number::NumberFormatter::withLocale(locale_data->locale());
  707. apply_display_options(formatter, display_options);
  708. apply_rounding_options(formatter, rounding_options);
  709. if (!numbering_system.is_empty()) {
  710. if (auto* symbols = icu::NumberingSystem::createInstanceByName(ByteString(numbering_system).characters(), status); symbols && icu_success(status))
  711. formatter = formatter.adoptSymbols(symbols);
  712. }
  713. bool is_unit = display_options.style == NumberFormatStyle::Unit;
  714. return adopt_own(*new NumberFormatImpl(locale_data->locale(), move(formatter), is_unit));
  715. }
  716. }