1use alloc::format;
10use alloc::string::String;
11use alloc::vec::Vec;
12
13#[derive(Clone, Copy, PartialEq, Eq, Debug)]
14pub enum Style {
15 Decimal,
16 Percent,
17 Currency,
18 Unit,
19}
20
21#[derive(Clone, Copy, PartialEq, Eq, Debug)]
22pub enum Notation {
23 Standard,
24 Compact,
25 Scientific,
26 Engineering,
27}
28
29#[derive(Clone, Copy, PartialEq, Eq, Debug)]
30pub enum SignDisplay {
31 Auto,
32 Never,
33 Always,
34 ExceptZero,
35 Negative,
36}
37
38#[derive(Clone, Copy, PartialEq, Eq, Debug)]
39pub enum Grouping {
40 Auto,
41 Always,
42 Min2,
43 Off,
44}
45
46#[derive(Clone, Copy, PartialEq, Eq, Debug)]
48pub enum RoundingMode {
49 Ceil,
50 Floor,
51 Expand,
52 Trunc,
53 HalfCeil,
54 HalfFloor,
55 HalfExpand,
56 HalfTrunc,
57 HalfEven,
58}
59
60impl RoundingMode {
61 pub const NAMES: [&'static str; 9] = ["ceil", "floor", "expand", "trunc", "halfCeil", "halfFloor", "halfExpand", "halfTrunc", "halfEven"];
62
63 pub fn from_name(s: &str) -> Option<Self> {
64 Some(match s {
65 "ceil" => RoundingMode::Ceil,
66 "floor" => RoundingMode::Floor,
67 "expand" => RoundingMode::Expand,
68 "trunc" => RoundingMode::Trunc,
69 "halfCeil" => RoundingMode::HalfCeil,
70 "halfFloor" => RoundingMode::HalfFloor,
71 "halfExpand" => RoundingMode::HalfExpand,
72 "halfTrunc" => RoundingMode::HalfTrunc,
73 "halfEven" => RoundingMode::HalfEven,
74 _ => return None,
75 })
76 }
77
78 pub fn name(self) -> &'static str {
79 match self {
80 RoundingMode::Ceil => "ceil",
81 RoundingMode::Floor => "floor",
82 RoundingMode::Expand => "expand",
83 RoundingMode::Trunc => "trunc",
84 RoundingMode::HalfCeil => "halfCeil",
85 RoundingMode::HalfFloor => "halfFloor",
86 RoundingMode::HalfExpand => "halfExpand",
87 RoundingMode::HalfTrunc => "halfTrunc",
88 RoundingMode::HalfEven => "halfEven",
89 }
90 }
91}
92
93#[derive(Clone, Debug)]
95pub enum NumValue {
96 NaN,
97 Infinity(bool),
99 Finite { neg: bool, digits: Vec<u8>, pt: i32 },
101}
102
103impl NumValue {
104 pub fn from_f64(x: f64) -> Self {
105 if x.is_nan() {
106 return NumValue::NaN;
107 }
108 if x.is_infinite() {
109 return NumValue::Infinity(x < 0.0);
110 }
111 let d = dec_of(libm::fabs(x));
112 NumValue::Finite { neg: x.is_sign_negative(), digits: d.digits, pt: d.pt }
113 }
114
115 fn finite(neg: bool, mut digits: Vec<u8>, mut pt: i32) -> Self {
116 while digits.first() == Some(&0) {
117 digits.remove(0);
118 pt -= 1;
119 }
120 while digits.last() == Some(&0) {
121 digits.pop();
122 }
123 if digits.is_empty() {
124 pt = 0;
125 }
126 NumValue::Finite { neg, digits, pt }
127 }
128
129 pub fn from_int_str(s: &str) -> Self {
131 let (neg, body) = match s.strip_prefix('-') {
132 Some(r) => (true, r),
133 None => (false, s),
134 };
135 let digits: Vec<u8> = body.bytes().filter(u8::is_ascii_digit).map(|b| b - b'0').collect();
136 let n = digits.len() as i32;
137 Self::finite(neg, digits, n)
138 }
139
140 pub fn parse_str(s: &str) -> Self {
142 let t = s.trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}');
143 if t.is_empty() {
144 return NumValue::Finite { neg: false, digits: Vec::new(), pt: 0 };
145 }
146 for (p, radix) in [("0x", 16u32), ("0X", 16), ("0o", 8), ("0O", 8), ("0b", 2), ("0B", 2)] {
147 if let Some(rest) = t.strip_prefix(p) {
148 if rest.is_empty() {
149 return NumValue::NaN;
150 }
151 let mut acc: Vec<u8> = Vec::new();
152 for c in rest.chars() {
153 let Some(v) = c.to_digit(radix) else { return NumValue::NaN };
154 mul_add(&mut acc, radix, v);
155 }
156 let n = acc.len() as i32;
157 return Self::finite(false, acc, n);
158 }
159 }
160 let (neg, body) = if let Some(r) = t.strip_prefix('-') {
161 (true, r)
162 } else if let Some(r) = t.strip_prefix('+') {
163 (false, r)
164 } else {
165 (false, t)
166 };
167 if body == "Infinity" {
168 return NumValue::Infinity(neg);
169 }
170 let (mant, exp) = match body.find(['e', 'E']) {
171 Some(i) => (body.get(..i).unwrap_or(""), Some(body.get(i + 1..).unwrap_or(""))),
172 None => (body, None),
173 };
174 let (ip, fp) = match mant.split_once('.') {
175 Some((a, b)) => (a, b),
176 None => (mant, ""),
177 };
178 if (ip.is_empty() && fp.is_empty()) || !ip.bytes().all(|b| b.is_ascii_digit()) || !fp.bytes().all(|b| b.is_ascii_digit()) {
179 return NumValue::NaN;
180 }
181 let mut e: i64 = 0;
182 if let Some(es) = exp {
183 let (eneg, ed) = if let Some(r) = es.strip_prefix('-') {
184 (true, r)
185 } else if let Some(r) = es.strip_prefix('+') {
186 (false, r)
187 } else {
188 (false, es)
189 };
190 if ed.is_empty() || !ed.bytes().all(|b| b.is_ascii_digit()) {
191 return NumValue::NaN;
192 }
193 for b in ed.bytes() {
194 e = (e * 10 + i64::from(b - b'0')).min(1_000_000);
195 }
196 if eneg {
197 e = -e;
198 }
199 }
200 let digits: Vec<u8> = ip.bytes().chain(fp.bytes()).map(|b| b - b'0').collect();
201 let pt = ip.len() as i64 + e;
202 if digits.iter().all(|&d| d == 0) {
203 return NumValue::Finite { neg, digits: Vec::new(), pt: 0 };
204 }
205 if pt > 100_000 {
206 return NumValue::Infinity(neg);
207 }
208 if pt < -100_000 {
209 return NumValue::Finite { neg, digits: Vec::new(), pt: 0 };
210 }
211 Self::finite(neg, digits, pt as i32)
212 }
213
214 pub fn is_nan(&self) -> bool {
215 matches!(self, NumValue::NaN)
216 }
217
218 pub fn is_neg(&self) -> bool {
220 match self {
221 NumValue::NaN => false,
222 NumValue::Infinity(n) => *n,
223 NumValue::Finite { neg, .. } => *neg,
224 }
225 }
226
227 pub fn is_zero(&self) -> bool {
228 matches!(self, NumValue::Finite { digits, .. } if digits.is_empty())
229 }
230
231 pub fn cmp_value(&self, other: &NumValue) -> core::cmp::Ordering {
233 use core::cmp::Ordering;
234 let key = |v: &NumValue| -> (i8, i32, Vec<u8>) {
235 match v {
236 NumValue::NaN => (0, 0, Vec::new()),
237 NumValue::Infinity(true) => (-2, 0, Vec::new()),
238 NumValue::Infinity(false) => (2, 0, Vec::new()),
239 NumValue::Finite { neg, digits, pt } => {
240 if digits.is_empty() {
241 (0, 0, Vec::new())
242 } else if *neg {
243 (-1, *pt, digits.clone())
244 } else {
245 (1, *pt, digits.clone())
246 }
247 }
248 }
249 };
250 let (sa, pa, da) = key(self);
251 let (sb, pb, db) = key(other);
252 if sa != sb {
253 return sa.cmp(&sb);
254 }
255 if sa.abs() != 1 {
256 return Ordering::Equal;
257 }
258 let mag = pa.cmp(&pb).then_with(|| da.cmp(&db));
259 if sa < 0 {
260 mag.reverse()
261 } else {
262 mag
263 }
264 }
265
266 pub fn to_f64(&self) -> f64 {
268 match self {
269 NumValue::NaN => f64::NAN,
270 NumValue::Infinity(n) => {
271 if *n {
272 f64::NEG_INFINITY
273 } else {
274 f64::INFINITY
275 }
276 }
277 NumValue::Finite { neg, digits, pt } => {
278 if digits.is_empty() {
279 return if *neg { -0.0 } else { 0.0 };
280 }
281 let mut s = String::from(if *neg { "-0." } else { "0." });
282 for d in digits {
283 s.push((b'0' + d) as char);
284 }
285 s.push('e');
286 s.push_str(&format!("{}", pt));
287 s.parse::<f64>().unwrap_or(f64::NAN)
288 }
289 }
290 }
291}
292
293fn mul_add(acc: &mut Vec<u8>, m: u32, a: u32) {
295 let mut carry = a;
296 for d in acc.iter_mut().rev() {
297 let v = u32::from(*d) * m + carry;
298 *d = (v % 10) as u8;
299 carry = v / 10;
300 }
301 while carry > 0 {
302 acc.insert(0, (carry % 10) as u8);
303 carry /= 10;
304 }
305}
306
307fn div_small(digits: &[u8], n: u32) -> (Vec<u8>, u32) {
309 let mut q: Vec<u8> = Vec::with_capacity(digits.len());
310 let mut r: u64 = 0;
311 for &d in digits {
312 let cur = r * 10 + u64::from(d);
313 q.push((cur / u64::from(n)) as u8);
314 r = cur % u64::from(n);
315 }
316 while q.first() == Some(&0) {
317 q.remove(0);
318 }
319 (q, r as u32)
320}
321
322#[derive(Clone, Debug)]
324pub struct NfOptions {
325 pub locale: String,
327 pub style: Style,
328 pub currency: String,
330 pub currency_display: u8,
332 pub unit: String,
333 pub unit_display: u8,
335 pub notation: Notation,
336 pub compact_long: bool,
337 pub sign: SignDisplay,
338 pub grouping: Grouping,
339 pub min_int: usize,
340 pub min_frac: usize,
341 pub max_frac: usize,
342 pub min_sig: usize,
344 pub max_sig: usize,
345 pub compact_round: bool,
347 pub rounding_mode: RoundingMode,
348 pub rounding_increment: u32,
350 pub rounding_priority: u8,
352 pub strip_if_integer: bool,
354 pub numbering_system: String,
356 pub accounting: bool,
358}
359
360#[derive(Clone, Copy, Default, Debug)]
362pub struct DigitOpts {
363 pub min_int: Option<usize>,
364 pub min_frac: Option<usize>,
365 pub max_frac: Option<usize>,
366 pub min_sig: Option<usize>,
367 pub max_sig: Option<usize>,
368}
369
370fn currency_digits(code: &str) -> usize {
372 match code {
373 "JPY" | "KRW" | "VND" | "CLP" | "ISK" | "UGX" | "XAF" | "XOF" | "PYG" | "RWF" | "VUV" => 0,
374 "BHD" | "KWD" | "OMR" | "JOD" | "TND" | "IQD" | "LYD" => 3,
375 _ => 2,
376 }
377}
378
379impl NfOptions {
380 pub fn new(locale: &str) -> Self {
381 NfOptions {
382 locale: String::from(locale),
383 style: Style::Decimal,
384 currency: String::new(),
385 currency_display: 0,
386 unit: String::new(),
387 unit_display: 0,
388 notation: Notation::Standard,
389 compact_long: false,
390 sign: SignDisplay::Auto,
391 grouping: Grouping::Auto,
392 min_int: 1,
393 min_frac: 0,
394 max_frac: 3,
395 min_sig: 0,
396 max_sig: 0,
397 compact_round: false,
398 rounding_mode: RoundingMode::HalfExpand,
399 rounding_increment: 1,
400 rounding_priority: 0,
401 strip_if_integer: false,
402 numbering_system: String::from("latn"),
403 accounting: false,
404 }
405 }
406
407 pub fn resolve_digits(&mut self, d: DigitOpts) -> Result<(), &'static str> {
409 let (mnfd_def, mxfd_def) = match self.style {
410 Style::Currency => {
411 let c = currency_digits(&self.currency);
412 (c, c)
413 }
414 Style::Percent => (0, 0),
415 _ => (0, 3),
416 };
417 let (mnfd_def, mxfd_def) = if self.notation == Notation::Compact { (0, 0) } else { (mnfd_def, mxfd_def) };
418 self.min_int = d.min_int.unwrap_or(1);
419 if d.min_sig.is_some() || d.max_sig.is_some() {
420 let mn = d.min_sig.unwrap_or(1);
421 let mx = d.max_sig.unwrap_or(21);
422 if mn > mx {
423 return Err("maximumSignificantDigits value is out of range.");
424 }
425 self.min_sig = mn;
426 self.max_sig = mx;
427 self.min_frac = 0;
428 self.max_frac = 0;
429 } else if d.min_frac.is_some() || d.max_frac.is_some() {
430 let (mn, mx) = match (d.min_frac, d.max_frac) {
431 (Some(a), Some(b)) => {
432 if a > b {
433 return Err("maximumFractionDigits value is out of range.");
434 }
435 (a, b)
436 }
437 (Some(a), None) => (a, mxfd_def.max(a)),
438 (None, Some(b)) => (mnfd_def.min(b), b),
439 (None, None) => (mnfd_def, mxfd_def),
440 };
441 self.min_frac = mn;
442 self.max_frac = mx;
443 self.min_sig = 0;
444 self.max_sig = 0;
445 } else if self.notation == Notation::Compact {
446 self.min_frac = 0;
447 self.max_frac = 0;
448 self.min_sig = 0;
449 self.max_sig = 0;
450 self.compact_round = true;
451 } else {
452 self.min_frac = mnfd_def;
453 self.max_frac = mxfd_def;
454 self.min_sig = 0;
455 self.max_sig = 0;
456 }
457 Ok(())
458 }
459
460 pub fn resolve_digits_full(&mut self, d: DigitOpts, priority: u8, increment: u32) -> Result<(), (bool, &'static str)> {
463 const INCREMENTS: [u32; 15] = [1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000];
464 if !INCREMENTS.contains(&increment) {
465 return Err((false, "roundingIncrement value is out of range."));
466 }
467 self.rounding_priority = priority;
468 self.rounding_increment = increment;
469 if priority == 0 {
470 self.resolve_digits(d).map_err(|m| (false, m))?;
471 if increment != 1 {
472 if self.max_sig > 0 || self.compact_round {
473 return Err((true, "roundingIncrement is only valid with fraction digits rounding."));
474 }
475 if self.min_frac != self.max_frac {
476 return Err((false, "maximumFractionDigits must equal minimumFractionDigits with roundingIncrement."));
477 }
478 }
479 return Ok(());
480 }
481 if increment != 1 {
482 return Err((true, "roundingIncrement is only valid with fraction digits rounding."));
483 }
484 let (mnfd_def, mxfd_def) = match self.style {
485 Style::Currency => {
486 let c = currency_digits(&self.currency);
487 (c, c)
488 }
489 Style::Percent => (0, 0),
490 _ => (0, 3),
491 };
492 let (mnfd_def, mxfd_def) = if self.notation == Notation::Compact { (0, 0) } else { (mnfd_def, mxfd_def) };
493 self.min_int = d.min_int.unwrap_or(1);
494 if d.min_sig.is_some() || d.max_sig.is_some() {
495 let mn = d.min_sig.unwrap_or(1);
496 let mx = d.max_sig.unwrap_or(21);
497 if mn > mx {
498 return Err((false, "maximumSignificantDigits value is out of range."));
499 }
500 self.min_sig = mn;
501 self.max_sig = mx;
502 } else {
503 self.min_sig = 1;
504 self.max_sig = 21;
505 }
506 if d.min_frac.is_some() || d.max_frac.is_some() {
507 let (mn, mx) = match (d.min_frac, d.max_frac) {
508 (Some(a), Some(b)) => {
509 if a > b {
510 return Err((false, "maximumFractionDigits value is out of range."));
511 }
512 (a, b)
513 }
514 (Some(a), None) => (a, mxfd_def.max(a)),
515 (None, Some(b)) => (mnfd_def.min(b), b),
516 (None, None) => (mnfd_def, mxfd_def),
517 };
518 self.min_frac = mn;
519 self.max_frac = mx;
520 } else {
521 self.min_frac = mnfd_def;
522 self.max_frac = mxfd_def;
523 }
524 Ok(())
525 }
526}
527
528struct Seps {
532 dec: &'static str,
533 grp: &'static str,
534 min_group: usize,
536 indian: bool,
537 minus: &'static str,
538}
539
540pub fn split_locale(loc: &str) -> (String, String) {
542 let mut lang = String::new();
543 let mut region = String::new();
544 for (i, part) in loc.split(['-', '_']).enumerate() {
545 if i == 0 {
546 lang = part.to_ascii_lowercase();
547 } else if part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()) {
548 region = part.to_ascii_uppercase();
549 } else if part.len() == 1 {
550 break; }
552 }
553 (lang, region)
554}
555
556fn seps(lang: &str, region: &str) -> Seps {
557 let nb = "\u{a0}";
558 let (dec, grp, min_group, minus) = match lang {
559 "de" => {
560 if region == "CH" || region == "LI" {
561 (".", "\u{2019}", 1, "-")
562 } else {
563 (",", ".", 1, "-")
564 }
565 }
566 "es" => {
567 if matches!(region, "MX" | "US" | "PR" | "GT" | "HN" | "NI" | "PA" | "SV" | "DO") {
568 (".", ",", 1, "-")
569 } else {
570 (",", ".", 2, "-")
571 }
572 }
573 "it" => (",", ".", 2, "-"),
574 "nl" | "tr" | "id" | "da" | "el" | "ro" | "hr" | "sl" | "vi" => (",", ".", 1, "-"),
575 "pt" => {
576 if region == "PT" {
577 (",", nb, 2, "-")
578 } else {
579 (",", ".", 1, "-")
580 }
581 }
582 "fr" => (",", "\u{202f}", 1, "-"),
583 "ru" | "uk" | "cs" | "sk" | "bg" | "hu" | "lt" | "lv" | "et" => (",", nb, 1, "-"),
584 "pl" => (",", nb, 2, "-"),
585 "fi" | "nb" | "no" | "nn" | "sv" => (",", nb, 1, "\u{2212}"),
586 _ => (".", ",", 1, "-"),
587 };
588 let indian = region == "IN" && (lang == "en" || lang == "hi");
589 let indian = indian || lang == "hi";
590 Seps { dec, grp, min_group, indian, minus }
591}
592
593#[derive(Clone)]
598struct Dec {
599 digits: Vec<u8>,
600 pt: i32,
601}
602
603fn dec_of(x: f64) -> Dec {
604 if x == 0.0 {
605 return Dec { digits: Vec::new(), pt: 0 };
606 }
607 let s = format!("{:e}", x);
608 let (mant, exp) = s.split_once('e').unwrap_or((s.as_str(), "0"));
609 let mut digits: Vec<u8> = mant.bytes().filter(u8::is_ascii_digit).map(|b| b - b'0').collect();
610 while digits.last() == Some(&0) {
611 digits.pop();
612 }
613 Dec { digits, pt: exp.parse::<i32>().unwrap_or(0) + 1 }
614}
615
616impl Dec {
617 fn is_zero(&self) -> bool {
618 self.digits.is_empty()
619 }
620
621 fn int_frac(&self) -> (String, String) {
623 let mut int = String::new();
624 let mut frac = String::new();
625 if self.digits.is_empty() {
626 int.push('0');
627 return (int, frac);
628 }
629 if self.pt <= 0 {
630 int.push('0');
631 for _ in 0..(-self.pt) {
632 frac.push('0');
633 }
634 for d in &self.digits {
635 frac.push((b'0' + d) as char);
636 }
637 } else {
638 let p = self.pt as usize;
639 for i in 0..p {
640 int.push(self.digits.get(i).map_or('0', |d| (b'0' + d) as char));
641 }
642 for d in self.digits.iter().skip(p) {
643 frac.push((b'0' + d) as char);
644 }
645 }
646 (int, frac)
647 }
648}
649
650type Parts = Vec<(&'static str, String)>;
654
655fn push(parts: &mut Parts, ty: &'static str, s: &str) {
656 if !s.is_empty() {
657 parts.push((ty, String::from(s)));
658 }
659}
660
661fn push_int(parts: &mut Parts, int: &str, sp: &Seps, grouping: Grouping) {
663 let n = int.len();
664 let min_group = match grouping {
665 Grouping::Off => usize::MAX,
666 Grouping::Always => 1,
667 Grouping::Min2 => 2,
668 Grouping::Auto => sp.min_group,
669 };
670 let group_it = min_group != usize::MAX && n >= 3 + min_group;
672 if !group_it {
673 push(parts, "integer", int);
674 return;
675 }
676 let mut cuts: Vec<usize> = Vec::new();
678 let mut pos = 3usize;
679 while pos < n {
680 cuts.push(pos);
681 pos += if sp.indian { 2 } else { 3 };
682 }
683 cuts.reverse(); let mut start = 0usize;
685 for c in cuts {
686 let at = n - c;
687 if let Some(seg) = int.get(start..at) {
688 push(parts, "integer", seg);
689 }
690 push(parts, "group", sp.grp);
691 start = at;
692 }
693 if let Some(seg) = int.get(start..) {
694 push(parts, "integer", seg);
695 }
696}
697
698fn frac_cmp_half(lead: usize, frac: &[u8]) -> core::cmp::Ordering {
700 use core::cmp::Ordering;
701 if frac.is_empty() {
702 return Ordering::Less;
703 }
704 if lead > 0 {
705 return Ordering::Less;
706 }
707 match frac.first().copied().unwrap_or(0) {
708 d if d > 5 => Ordering::Greater,
709 5 => {
710 if frac.len() > 1 {
711 Ordering::Greater
712 } else {
713 Ordering::Equal
714 }
715 }
716 _ => Ordering::Less,
717 }
718}
719
720fn round_to(d: &Dec, m: i32, inc: u32, mode: RoundingMode, neg: bool) -> Dec {
722 use core::cmp::Ordering;
723 if d.is_zero() {
724 return d.clone();
725 }
726 let inc = inc.max(1);
727 let int_len = i64::from(d.pt) - i64::from(m);
729 let (int_digits, lead, frac): (Vec<u8>, usize, &[u8]) = if int_len <= 0 {
730 (Vec::new(), (-int_len) as usize, d.digits.as_slice())
731 } else if int_len as usize >= d.digits.len() {
732 let mut v = d.digits.clone();
733 v.resize(int_len as usize, 0);
734 (v, 0, &[])
735 } else {
736 let k = int_len as usize;
737 (d.digits.get(..k).map(<[u8]>::to_vec).unwrap_or_default(), 0, d.digits.get(k..).unwrap_or(&[]))
738 };
739 let (q, r) = div_small(&int_digits, inc);
740 if r == 0 && frac.is_empty() {
741 return d.clone();
742 }
743 let two_r = u64::from(r) * 2;
745 let inc64 = u64::from(inc);
746 let half = if two_r > inc64 {
747 Ordering::Greater
748 } else if two_r == inc64 {
749 if frac.is_empty() {
750 Ordering::Equal
751 } else {
752 Ordering::Greater
753 }
754 } else if two_r + 2 <= inc64 {
755 Ordering::Less
756 } else {
757 frac_cmp_half(lead, frac)
758 };
759 let q_odd = q.last().is_some_and(|d| d % 2 == 1);
760 let up = match mode {
761 RoundingMode::Ceil => !neg,
762 RoundingMode::Floor => neg,
763 RoundingMode::Expand => true,
764 RoundingMode::Trunc => false,
765 RoundingMode::HalfCeil => half == Ordering::Greater || (half == Ordering::Equal && !neg),
766 RoundingMode::HalfFloor => half == Ordering::Greater || (half == Ordering::Equal && neg),
767 RoundingMode::HalfExpand => half != Ordering::Less,
768 RoundingMode::HalfTrunc => half == Ordering::Greater,
769 RoundingMode::HalfEven => half == Ordering::Greater || (half == Ordering::Equal && q_odd),
770 };
771 let mut n = q;
772 if up {
773 mul_add(&mut n, 1, 1);
774 }
775 mul_add(&mut n, inc, 0);
776 while n.first() == Some(&0) {
777 n.remove(0);
778 }
779 let pt = n.len() as i32 + m;
780 while n.last() == Some(&0) {
781 n.pop();
782 }
783 if n.is_empty() {
784 return Dec { digits: Vec::new(), pt: 0 };
785 }
786 Dec { digits: n, pt }
787}
788
789struct Raw {
791 int: String,
792 frac: String,
793 mag: i32,
794 d: Dec,
795}
796
797fn raw_fixed(d: &Dec, min_frac: usize, max_frac: usize, inc: u32, mode: RoundingMode, neg: bool) -> Raw {
799 let m = -(max_frac as i32);
800 let r = round_to(d, m, inc, mode, neg);
801 let (int, mut frac) = r.int_frac();
802 while frac.len() < min_frac {
803 frac.push('0');
804 }
805 Raw { int, frac, mag: m, d: r }
806}
807
808fn raw_precision(d: &Dec, min_sig: usize, max_sig: usize, mode: RoundingMode, neg: bool) -> Raw {
810 let max_sig = max_sig.max(1);
811 if d.is_zero() {
812 let mut frac = String::new();
813 for _ in 1..min_sig {
814 frac.push('0');
815 }
816 return Raw { int: String::from("0"), frac, mag: 1 - max_sig as i32, d: d.clone() };
817 }
818 let m = d.pt - max_sig as i32;
819 let r = round_to(d, m, 1, mode, neg);
820 let (int, mut frac) = r.int_frac();
821 let need = min_sig as i64 - i64::from(r.pt);
822 while (frac.len() as i64) < need {
823 frac.push('0');
824 }
825 Raw { int, frac, mag: r.pt - max_sig as i32, d: r }
826}
827
828fn round_digits(d: &mut Dec, o: &NfOptions, neg: bool) -> (String, String) {
830 let mode = o.rounding_mode;
831 let pick = |s: Raw, f: Raw, more: bool| -> Raw {
832 if s.mag <= f.mag {
833 if more {
834 s
835 } else {
836 f
837 }
838 } else if more {
839 f
840 } else {
841 s
842 }
843 };
844 let raw = if o.compact_round {
845 let s = raw_precision(d, 1, 2, mode, neg);
847 let f = raw_fixed(d, 0, 0, 1, mode, neg);
848 pick(s, f, true)
849 } else if o.rounding_priority != 0 && o.max_sig > 0 {
850 let s = raw_precision(d, o.min_sig, o.max_sig, mode, neg);
851 let f = raw_fixed(d, o.min_frac, o.max_frac, o.rounding_increment, mode, neg);
852 pick(s, f, o.rounding_priority == 1)
853 } else if o.max_sig > 0 {
854 raw_precision(d, o.min_sig, o.max_sig, mode, neg)
855 } else {
856 raw_fixed(d, o.min_frac, o.max_frac, o.rounding_increment, mode, neg)
857 };
858 *d = raw.d;
859 let mut frac = raw.frac;
860 if o.strip_if_integer && frac.bytes().all(|b| b == b'0') {
861 frac.clear();
862 }
863 (raw.int, frac)
864}
865
866fn nu_zero(nu: &str) -> Option<u32> {
868 Some(match nu {
869 "adlm" => 0x1E950, "ahom" => 0x11730, "arab" => 0x660, "arabext" => 0x6F0, "bali" => 0x1B50, "beng" => 0x9E6,
870 "bhks" => 0x11C50, "brah" => 0x11066, "cakm" => 0x11136, "cham" => 0xAA50, "deva" => 0x966, "diak" => 0x11950,
871 "fullwide" => 0xFF10, "gara" => 0x10D40, "gong" => 0x11DA0, "gonm" => 0x11D50, "gujr" => 0xAE6, "gukh" => 0x16130,
872 "guru" => 0xA66, "hmng" => 0x16B50, "hmnp" => 0x1E140, "java" => 0xA9D0, "kali" => 0xA900, "kawi" => 0x11F50,
873 "khmr" => 0x17E0, "knda" => 0xCE6, "krai" => 0x16D70, "lana" => 0x1A80, "lanatham" => 0x1A90, "laoo" => 0xED0,
874 "latn" => 0x30, "lepc" => 0x1C40, "limb" => 0x1946, "mathbold" => 0x1D7CE, "mathdbl" => 0x1D7D8, "mathmono" => 0x1D7F6,
875 "mathsanb" => 0x1D7EC, "mathsans" => 0x1D7E2, "mlym" => 0xD66, "modi" => 0x11650, "mong" => 0x1810, "mroo" => 0x16A60,
876 "mtei" => 0xABF0, "mymr" => 0x1040, "mymrepka" => 0x116DA, "mymrpao" => 0x116D0, "mymrshan" => 0x1090, "mymrtlng" => 0xA9F0,
877 "nagm" => 0x1E4F0, "newa" => 0x11450, "nkoo" => 0x7C0, "olck" => 0x1C50, "onao" => 0x1E5F1, "orya" => 0xB66,
878 "osma" => 0x104A0, "outlined" => 0x1CCF0, "rohg" => 0x10D30, "saur" => 0xA8D0, "segment" => 0x1FBF0, "shrd" => 0x111D0,
879 "sind" => 0x112F0, "sinh" => 0xDE6, "sora" => 0x110F0, "sund" => 0x1BB0, "sunu" => 0x11BF0, "takr" => 0x116C0,
880 "talu" => 0x19D0, "tamldec" => 0xBE6, "telu" => 0xC66, "thai" => 0xE50, "tibt" => 0xF20, "tirh" => 0x114D0,
881 "tnsa" => 0x16AC0, "tols" => 0x11DE0, "vaii" => 0xA620, "wara" => 0x118E0, "wcho" => 0x1E2F0,
882 _ => return None,
883 })
884}
885
886pub const SIMPLE_NUMBERING_SYSTEMS: &[&str] = &[
888 "adlm", "ahom", "arab", "arabext", "bali", "beng", "bhks", "brah", "cakm", "cham", "deva", "diak", "fullwide", "gara", "gong",
889 "gonm", "gujr", "gukh", "guru", "hanidec", "hmng", "hmnp", "java", "kali", "kawi", "khmr", "knda", "krai", "lana", "lanatham",
890 "laoo", "latn", "lepc", "limb", "mathbold", "mathdbl", "mathmono", "mathsanb", "mathsans", "mlym", "modi", "mong", "mroo",
891 "mtei", "mymr", "mymrepka", "mymrpao", "mymrshan", "mymrtlng", "nagm", "newa", "nkoo", "olck", "onao", "orya", "osma",
892 "outlined", "rohg", "saur", "segment", "shrd", "sind", "sinh", "sora", "sund", "sunu", "takr", "talu", "tamldec", "telu",
893 "thai", "tibt", "tirh", "tnsa", "tols", "vaii", "wara", "wcho",
894];
895
896pub fn is_supported_numbering_system(nu: &str) -> bool {
898 SIMPLE_NUMBERING_SYSTEMS.contains(&nu)
899}
900
901pub fn transliterate_digits(s: &str, nu: &str) -> String {
903 if nu == "latn" || nu.is_empty() {
904 return String::from(s);
905 }
906 const HANIDEC: [char; 10] = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
907 let zero = nu_zero(nu);
908 if zero.is_none() && nu != "hanidec" {
909 return String::from(s);
910 }
911 s.chars()
912 .map(|c| match c.to_digit(10) {
913 Some(v) if c.is_ascii_digit() => {
914 if nu == "hanidec" {
915 HANIDEC.get(v as usize).copied().unwrap_or(c)
916 } else {
917 zero.and_then(|z| char::from_u32(z + v)).unwrap_or(c)
918 }
919 }
920 _ => c,
921 })
922 .collect()
923}
924
925fn compact_table(lang: &str, region: &str) -> &'static [(i32, &'static str, &'static str)] {
930 if lang == "en" && region == "IN" {
931 return &[(3, "K", " thousand"), (5, "L", " lakh"), (7, "Cr", " crore"), (12, "LCr", " lakh crore")];
932 }
933 match lang {
934 "ja" => &[(4, "万", "万"), (8, "億", "億"), (12, "兆", "兆")],
935 "zh" => &[(4, "万", "万"), (8, "亿", "亿"), (12, "万亿", "万亿")],
936 "ko" => &[(3, "천", "천"), (4, "만", "만"), (8, "억", "억"), (12, "조", "조")],
937 "de" => &[(3, "", " Tausend"), (6, "\u{a0}Mio.", " Millionen"), (9, "\u{a0}Mrd.", " Milliarden"), (12, "\u{a0}Bio.", " Billionen")],
938 "fr" => &[(3, "\u{a0}k", " mille"), (6, "\u{a0}M", " million"), (9, "\u{a0}Md", " milliard"), (12, "\u{a0}Bn", " billion")],
939 "es" => &[(3, "\u{a0}mil", " mil"), (6, "\u{a0}M", " millones"), (9, "", " mil millones"), (12, "\u{a0}B", " billones")],
940 "pt" => &[(3, "\u{a0}mil", " mil"), (6, "\u{a0}mi", " milhão"), (9, "\u{a0}bi", " bilhão"), (12, "\u{a0}tri", " trilhão")],
941 "it" => &[(3, "K", " mila"), (6, "\u{a0}Mln", " milioni"), (9, "\u{a0}Mld", " miliardi"), (12, "\u{a0}Bln", " mila miliardi")],
942 "nl" => &[(3, "K", " duizend"), (6, "\u{a0}mln.", " miljoen"), (9, "\u{a0}mld.", " miljard"), (12, "\u{a0}bln.", " biljoen")],
943 "ru" => &[(3, "\u{a0}тыс.", " тысячи"), (6, "\u{a0}млн", " миллиона"), (9, "\u{a0}млрд", " миллиарда"), (12, "\u{a0}трлн", " триллиона")],
944 _ => &[(3, "K", " thousand"), (6, "M", " million"), (9, "B", " billion"), (12, "T", " trillion")],
945 }
946}
947
948fn currency_symbol(lang: &str, region: &str, code: &str, narrow: bool) -> String {
952 if narrow {
953 match code {
954 "USD" | "CAD" | "AUD" | "MXN" | "HKD" | "NZD" | "SGD" | "TWD" => return String::from("$"),
955 "CNY" | "JPY" => return String::from("¥"),
956 _ => {}
957 }
958 }
959 let over: Option<&str> = match (lang, code) {
961 ("en", "JPY") if region == "IN" => Some("JP¥"),
962 ("zh", "USD") | ("ko", "USD") | ("es", "USD") | ("pt", "USD") | ("nl", "USD") => Some("US$"),
963 ("zh", "JPY") | ("ko", "JPY") | ("pt", "JPY") | ("nl", "JPY") => Some("JP¥"),
964 ("zh", "CNY") => Some("¥"),
965 ("ja", "JPY") => Some("\u{ffe5}"),
966 ("ja", "CNY") => Some("元"),
967 ("fr", "USD") => Some("$US"),
968 ("fr", "GBP") => Some("£GB"),
969 ("fr", "JPY") | ("es", "JPY") | ("it", "JPY") => Some("JPY"),
970 ("fr", "CNY") | ("es", "CNY") => Some("CNY"),
971 ("es", "GBP") => Some("GBP"),
972 ("es", "KRW") | ("it", "KRW") => Some("KRW"),
973 ("it", "USD") => Some("USD"),
974 ("ru", "RUB") => Some("₽"),
975 _ => None,
976 };
977 if let Some(s) = over {
978 return String::from(s);
979 }
980 let s = match code {
981 "USD" => "$",
982 "EUR" => "€",
983 "GBP" => "£",
984 "JPY" => "¥",
985 "CNY" => "CN¥",
986 "KRW" => "₩",
987 "INR" => "₹",
988 "BRL" => "R$",
989 "CAD" => "CA$",
990 "AUD" => "A$",
991 "MXN" => "MX$",
992 "HKD" => "HK$",
993 "NZD" => "NZ$",
994 "ILS" => "₪",
995 "VND" => "₫",
996 "TWD" => "NT$",
997 "PHP" => "₱",
998 "TRY" => "₺",
999 "PLN" => "zł",
1000 "THB" => "฿",
1001 _ => code,
1002 };
1003 String::from(s)
1004}
1005
1006fn currency_name(code: &str, one: bool) -> String {
1007 let (s, p) = match code {
1008 "USD" => ("US dollar", "US dollars"),
1009 "EUR" => ("euro", "euros"),
1010 "GBP" => ("British pound", "British pounds"),
1011 "JPY" => ("Japanese yen", "Japanese yen"),
1012 "CNY" => ("Chinese yuan", "Chinese yuan"),
1013 "KRW" => ("South Korean won", "South Korean won"),
1014 "INR" => ("Indian rupee", "Indian rupees"),
1015 "CAD" => ("Canadian dollar", "Canadian dollars"),
1016 "AUD" => ("Australian dollar", "Australian dollars"),
1017 _ => return String::from(code),
1018 };
1019 String::from(if one { s } else { p })
1020}
1021
1022fn simple_unit_names(unit: &str) -> Option<[&'static str; 5]> {
1025 Some(match unit {
1026 "acre" => ["ac", "ac", "ac", "acre", "acres"],
1027 "bit" => ["bit", "bit", "bit", "bit", "bits"],
1028 "byte" => ["byte", "byte", "B", "byte", "bytes"],
1029 "celsius" => ["°C", "°C", "°C", "degree Celsius", "degrees Celsius"],
1030 "centimeter" => ["cm", "cm", "cm", "centimeter", "centimeters"],
1031 "day" => ["day", "days", "d", "day", "days"],
1032 "degree" => ["deg", "deg", "°", "degree", "degrees"],
1033 "fahrenheit" => ["°F", "°F", "°", "degree Fahrenheit", "degrees Fahrenheit"],
1034 "fluid-ounce" => ["fl oz", "fl oz", "fl oz", "fluid ounce", "fluid ounces"],
1035 "foot" => ["ft", "ft", "′", "foot", "feet"],
1036 "gallon" => ["gal", "gal", "gal", "gallon", "gallons"],
1037 "gigabit" => ["Gb", "Gb", "Gb", "gigabit", "gigabits"],
1038 "gigabyte" => ["GB", "GB", "GB", "gigabyte", "gigabytes"],
1039 "gram" => ["g", "g", "g", "gram", "grams"],
1040 "hectare" => ["ha", "ha", "ha", "hectare", "hectares"],
1041 "hour" => ["hr", "hr", "h", "hour", "hours"],
1042 "inch" => ["in", "in", "″", "inch", "inches"],
1043 "kilobit" => ["kb", "kb", "kb", "kilobit", "kilobits"],
1044 "kilobyte" => ["kB", "kB", "kB", "kilobyte", "kilobytes"],
1045 "kilogram" => ["kg", "kg", "kg", "kilogram", "kilograms"],
1046 "kilometer" => ["km", "km", "km", "kilometer", "kilometers"],
1047 "liter" => ["L", "L", "L", "liter", "liters"],
1048 "megabit" => ["Mb", "Mb", "Mb", "megabit", "megabits"],
1049 "megabyte" => ["MB", "MB", "MB", "megabyte", "megabytes"],
1050 "meter" => ["m", "m", "m", "meter", "meters"],
1051 "microsecond" => ["μs", "μs", "μs", "microsecond", "microseconds"],
1052 "mile" => ["mi", "mi", "mi", "mile", "miles"],
1053 "mile-scandinavian" => ["smi", "smi", "smi", "mile-scandinavian", "miles-scandinavian"],
1054 "milliliter" => ["mL", "mL", "mL", "milliliter", "milliliters"],
1055 "millimeter" => ["mm", "mm", "mm", "millimeter", "millimeters"],
1056 "millisecond" => ["ms", "ms", "ms", "millisecond", "milliseconds"],
1057 "minute" => ["min", "min", "m", "minute", "minutes"],
1058 "month" => ["mth", "mths", "m", "month", "months"],
1059 "nanosecond" => ["ns", "ns", "ns", "nanosecond", "nanoseconds"],
1060 "ounce" => ["oz", "oz", "oz", "ounce", "ounces"],
1061 "percent" => ["%", "%", "%", "percent", "percent"],
1062 "petabyte" => ["PB", "PB", "PB", "petabyte", "petabytes"],
1063 "pound" => ["lb", "lb", "#", "pound", "pounds"],
1064 "second" => ["sec", "sec", "s", "second", "seconds"],
1065 "stone" => ["st", "st", "st", "stone", "stones"],
1066 "terabit" => ["Tb", "Tb", "Tb", "terabit", "terabits"],
1067 "terabyte" => ["TB", "TB", "TB", "terabyte", "terabytes"],
1068 "week" => ["wk", "wks", "w", "week", "weeks"],
1069 "yard" => ["yd", "yd", "yd", "yard", "yards"],
1070 "year" => ["yr", "yrs", "y", "year", "years"],
1071 _ => return None,
1072 })
1073}
1074
1075pub const SIMPLE_UNITS: &[&str] = &[
1077 "acre", "bit", "byte", "celsius", "centimeter", "day", "degree", "fahrenheit", "fluid-ounce", "foot", "gallon", "gigabit",
1078 "gigabyte", "gram", "hectare", "hour", "inch", "kilobit", "kilobyte", "kilogram", "kilometer", "liter", "megabit", "megabyte",
1079 "meter", "microsecond", "mile", "mile-scandinavian", "milliliter", "millimeter", "millisecond", "minute", "month", "nanosecond",
1080 "ounce", "percent", "petabyte", "pound", "second", "stone", "terabit", "terabyte", "week", "yard", "year",
1081];
1082
1083fn unit_names(unit: &str) -> Option<[&'static str; 5]> {
1085 match unit {
1086 "kilometer-per-hour" => Some(["km/h", "km/h", "km/h", "kilometer per hour", "kilometers per hour"]),
1087 "mile-per-hour" => Some(["mph", "mph", "mph", "mile per hour", "miles per hour"]),
1088 "meter-per-second" => Some(["m/s", "m/s", "m/s", "meter per second", "meters per second"]),
1089 _ => simple_unit_names(unit),
1090 }
1091}
1092
1093pub fn is_sanctioned_unit(unit: &str) -> bool {
1095 if simple_unit_names(unit).is_some() {
1096 return true;
1097 }
1098 match unit.split_once("-per-") {
1099 Some((a, b)) => simple_unit_names(a).is_some() && simple_unit_names(b).is_some(),
1100 None => false,
1101 }
1102}
1103
1104fn unit_suffix(lang: &str, unit: &str, display: u8, one: bool) -> (String, String) {
1106 if unit == "kilometer-per-hour" {
1107 match (lang, display) {
1108 ("de", 2) => return (String::from(" "), String::from("Kilometer pro Stunde")),
1109 ("de", _) => return (String::from(" "), String::from("km/h")),
1110 ("ko", 2) | ("ja", 2) | ("zh", 2) => {}
1111 ("ko", _) => return (String::new(), String::from("km/h")),
1112 ("ja", _) => return (String::from(" "), String::from("km/h")),
1113 _ => {}
1114 }
1115 }
1116 if let Some(n) = unit_names(unit) {
1117 let gap_short = if matches!(unit, "celsius" | "fahrenheit" | "percent") {
1118 ""
1119 } else if lang == "fr" {
1120 "\u{202f}"
1121 } else {
1122 " "
1123 };
1124 return match display {
1125 2 => (String::from(" "), String::from(if one { n[3] } else { n[4] })),
1126 1 => (String::new(), String::from(n[2])),
1127 _ => (String::from(gap_short), String::from(if one { n[0] } else { n[1] })),
1128 };
1129 }
1130 if let Some((a, b)) = unit.split_once("-per-") {
1132 let na = simple_unit_names(a).unwrap_or([""; 5]);
1133 let nb = simple_unit_names(b).unwrap_or([""; 5]);
1134 return match display {
1135 2 => (String::from(" "), format!("{} per {}", if one { na[3] } else { na[4] }, nb[3])),
1136 1 => (String::new(), format!("{}/{}", na[2], nb[2])),
1137 _ => (String::from(" "), format!("{}/{}", if one { na[0] } else { na[1] }, nb[0])),
1138 };
1139 }
1140 (String::from(" "), String::from(unit))
1141}
1142
1143pub fn format_parts(x: f64, o: &NfOptions) -> Vec<(&'static str, String)> {
1148 format_value_parts(&NumValue::from_f64(x), o)
1149}
1150
1151fn is_hant(locale: &str, lang: &str, region: &str) -> bool {
1153 lang == "zh" && (matches!(region, "TW" | "HK" | "MO") || locale.split('-').any(|p| p.eq_ignore_ascii_case("hant")))
1154}
1155
1156pub fn format_value_parts(v: &NumValue, o: &NfOptions) -> Vec<(&'static str, String)> {
1158 let (lang, region) = split_locale(&o.locale);
1159 let hant = is_hant(&o.locale, &lang, ®ion);
1160 let sp = seps(&lang, ®ion);
1161 let neg = v.is_neg();
1162 let mut parts: Parts = Vec::new();
1163 let mut number: Parts = Vec::new();
1164 let mut is_zero = false;
1165 let mut one = false;
1166 let mut compact_suffix: &str = "";
1167
1168 match v {
1169 NumValue::NaN => push(&mut number, "nan", if hant { "非數值" } else { "NaN" }),
1170 NumValue::Infinity(_) => push(&mut number, "infinity", "∞"),
1171 NumValue::Finite { digits, pt, .. } => {
1172 let mut d = Dec { digits: digits.clone(), pt: *pt };
1173 if o.style == Style::Percent && !d.is_zero() {
1174 d.pt += 2;
1175 }
1176 match o.notation {
1177 Notation::Compact => {
1178 let table: &[(i32, &str, &str)] = if hant {
1179 &[(4, "萬", "萬"), (8, "億", "億"), (12, "兆", "兆")]
1180 } else {
1181 compact_table(&lang, ®ion)
1182 };
1183 let mut chosen: Option<(i32, &str, &str)> = None;
1185 let mut scaled = d.clone();
1186 for _ in 0..3 {
1187 let mag = if d.is_zero() { 0 } else { d.pt - 1 };
1188 chosen = None;
1189 for &(e, s, l) in table {
1190 let word = if o.compact_long { l } else { s };
1192 if mag >= e && !word.is_empty() {
1193 chosen = Some((e, s, l));
1194 }
1195 }
1196 scaled = d.clone();
1197 let e = chosen.map_or(0, |c| c.0);
1198 if !scaled.is_zero() {
1199 scaled.pt -= e;
1200 }
1201 let before = scaled.pt;
1202 let mut probe = scaled.clone();
1203 let _ = round_digits(&mut probe, o, neg);
1204 if !d.is_zero() && probe.pt > before {
1205 let new_mag = probe.pt - 1 + e;
1206 if table.iter().any(|&(e2, _, _)| e2 > e && e2 <= new_mag) {
1207 probe.pt += e;
1208 d = probe;
1209 continue;
1210 }
1211 }
1212 break;
1213 }
1214 let (int, frac) = round_digits(&mut scaled, o, neg);
1215 is_zero = scaled.is_zero();
1216 one = int == "1" && frac.is_empty();
1217 if let Some((_, s, l)) = chosen {
1218 compact_suffix = if o.compact_long { l } else { s };
1219 }
1220 push_int(&mut number, &int, &sp, if o.grouping == Grouping::Auto { Grouping::Min2 } else { o.grouping });
1221 if !frac.is_empty() {
1222 push(&mut number, "decimal", sp.dec);
1223 push(&mut number, "fraction", &frac);
1224 }
1225 if !compact_suffix.is_empty() {
1226 let trimmed = compact_suffix.trim_start_matches([' ', '\u{a0}']);
1227 if let Some(gap) = compact_suffix.get(..compact_suffix.len() - trimmed.len()) {
1228 push(&mut number, "literal", gap);
1229 }
1230 push(&mut number, "compact", trimmed);
1231 }
1232 }
1233 Notation::Scientific | Notation::Engineering => {
1234 let step = if o.notation == Notation::Engineering { 3 } else { 1 };
1235 let mut exp = if d.is_zero() { 0 } else { d.pt - 1 };
1236 if step == 3 {
1237 exp = exp.div_euclid(3) * 3;
1238 }
1239 let mut m = d.clone();
1240 if !m.is_zero() {
1241 m.pt -= exp;
1242 }
1243 let (int, frac) = round_digits(&mut m, o, neg);
1244 let (int, frac, exp) = if m.pt > step && !m.is_zero() {
1246 let mut m2 = d.clone();
1247 m2.pt -= exp + step;
1248 let (i2, f2) = round_digits(&mut m2, o, neg);
1249 m = m2;
1250 (i2, f2, exp + step)
1251 } else {
1252 (int, frac, exp)
1253 };
1254 is_zero = m.is_zero();
1255 push(&mut number, "integer", &int);
1256 if !frac.is_empty() {
1257 push(&mut number, "decimal", sp.dec);
1258 push(&mut number, "fraction", &frac);
1259 }
1260 push(&mut number, "exponentSeparator", "E");
1261 if exp < 0 {
1262 push(&mut number, "exponentMinusSign", sp.minus);
1263 }
1264 push(&mut number, "exponentInteger", &format!("{}", exp.abs()));
1265 }
1266 Notation::Standard => {
1267 let (mut int, frac) = round_digits(&mut d, o, neg);
1268 is_zero = d.is_zero();
1269 one = int == "1" && frac.is_empty();
1270 while int.len() < o.min_int {
1271 int.insert(0, '0');
1272 }
1273 push_int(&mut number, &int, &sp, o.grouping);
1274 if !frac.is_empty() {
1275 push(&mut number, "decimal", sp.dec);
1276 push(&mut number, "fraction", &frac);
1277 }
1278 }
1279 }
1280 }
1281 }
1282
1283 if o.numbering_system != "latn" && !o.numbering_system.is_empty() {
1285 for (ty, val) in number.iter_mut() {
1286 if matches!(*ty, "integer" | "fraction" | "exponentInteger") {
1287 *val = transliterate_digits(val, &o.numbering_system);
1288 }
1289 }
1290 }
1291
1292 let nan = v.is_nan();
1294 let sign: &str = match o.sign {
1295 SignDisplay::Never => "",
1296 SignDisplay::Auto => {
1297 if neg {
1298 sp.minus
1299 } else {
1300 ""
1301 }
1302 }
1303 SignDisplay::Always => {
1304 if neg {
1305 sp.minus
1306 } else {
1307 "+"
1308 }
1309 }
1310 SignDisplay::ExceptZero => {
1311 if is_zero || nan {
1312 ""
1313 } else if neg {
1314 sp.minus
1315 } else {
1316 "+"
1317 }
1318 }
1319 SignDisplay::Negative => {
1320 if neg && !is_zero {
1321 sp.minus
1322 } else {
1323 ""
1324 }
1325 }
1326 };
1327 let sign_ty = if sign == "+" { "plusSign" } else { "minusSign" };
1328
1329 match o.style {
1330 Style::Decimal => {
1331 push(&mut parts, sign_ty, sign);
1332 parts.extend(number);
1333 }
1334 Style::Percent => {
1335 push(&mut parts, sign_ty, sign);
1336 let pct_prefix = lang == "tr";
1337 let gap: &str = match lang.as_str() {
1338 "de" | "es" | "ru" | "sv" | "nb" | "no" | "fi" | "cs" | "sk" | "da" | "uk" | "bg" | "fr" => "\u{a0}",
1339 _ => "",
1340 };
1341 if pct_prefix {
1342 push(&mut parts, "percentSign", "%");
1343 parts.extend(number);
1344 } else {
1345 parts.extend(number);
1346 push(&mut parts, "literal", gap);
1347 push(&mut parts, "percentSign", "%");
1348 }
1349 }
1350 Style::Currency => {
1351 let code = o.currency.as_str();
1352 match o.currency_display {
1353 3 => {
1354 push(&mut parts, sign_ty, sign);
1355 parts.extend(number);
1356 push(&mut parts, "literal", " ");
1357 push(&mut parts, "currency", ¤cy_name(code, one));
1358 }
1359 disp => {
1360 let sym = if disp == 2 { String::from(code) } else { currency_symbol(&lang, ®ion, code, disp == 1) };
1361 let suffix = matches!(lang.as_str(), "de" | "fr" | "es" | "it" | "ru" | "pl" | "sv" | "nb" | "no" | "fi" | "cs" | "sk" | "da" | "uk" | "bg" | "hu" | "ro" | "el")
1362 || (lang == "pt" && region == "PT");
1363 let paren = o.accounting && !suffix && sign_ty == "minusSign" && !sign.is_empty();
1365 if paren {
1366 push(&mut parts, "literal", "(");
1367 }
1368 if suffix {
1369 push(&mut parts, sign_ty, sign);
1370 parts.extend(number);
1371 push(&mut parts, "literal", "\u{a0}");
1372 push(&mut parts, "currency", &sym);
1373 } else {
1374 if !paren {
1375 push(&mut parts, sign_ty, sign);
1376 }
1377 push(&mut parts, "currency", &sym);
1378 let alpha_end = sym.chars().last().is_some_and(|c| c.is_alphabetic());
1380 if alpha_end || lang == "pt" || lang == "nl" {
1381 push(&mut parts, "literal", "\u{a0}");
1382 }
1383 parts.extend(number);
1384 }
1385 if paren {
1386 push(&mut parts, "literal", ")");
1387 }
1388 }
1389 }
1390 }
1391 Style::Unit => {
1392 let (gap, text) = unit_suffix(&lang, &o.unit, o.unit_display, one);
1393 push(&mut parts, sign_ty, sign);
1394 parts.extend(number);
1395 push(&mut parts, "literal", &gap);
1396 push(&mut parts, "unit", &text);
1397 }
1398 }
1399 parts
1400}
1401
1402pub fn format(x: f64, o: &NfOptions) -> String {
1404 format_value(&NumValue::from_f64(x), o)
1405}
1406
1407pub fn format_value(v: &NumValue, o: &NfOptions) -> String {
1409 let mut s = String::new();
1410 for (_, p) in format_value_parts(v, o) {
1411 s.push_str(&p);
1412 }
1413 s
1414}
1415
1416pub fn is_structurally_valid_tag(tag: &str) -> bool {
1418 if tag.is_empty() {
1419 return false;
1420 }
1421 let mut it = tag.split('-');
1422 let Some(lang) = it.next() else { return false };
1423 let ll = lang.len();
1424 if !(ll == 2 || ll == 3 || (5..=8).contains(&ll)) || !lang.bytes().all(|b| b.is_ascii_alphabetic()) {
1425 return false;
1426 }
1427 for sub in it {
1428 if sub.is_empty() || sub.len() > 8 || !sub.bytes().all(|b| b.is_ascii_alphanumeric()) {
1429 return false;
1430 }
1431 }
1432 true
1433}
1434
1435pub fn canonicalize_tag(tag: &str) -> String {
1437 let mut out = String::new();
1438 for (i, part) in tag.split(['-', '_']).enumerate() {
1439 if i > 0 {
1440 out.push('-');
1441 }
1442 if i == 0 {
1443 out.push_str(&part.to_ascii_lowercase());
1444 } else if part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()) {
1445 out.push_str(&part.to_ascii_uppercase());
1446 } else if part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()) {
1447 let mut c = part.to_ascii_lowercase();
1448 if let Some(f) = c.get_mut(0..1) {
1449 f.make_ascii_uppercase();
1450 }
1451 out.push_str(&c);
1452 } else {
1453 out.push_str(&part.to_ascii_lowercase());
1454 }
1455 }
1456 out
1457}