1use alloc::{borrow::Cow, string::String};
4use core::fmt;
5
6use crate::{Format, float, lexer};
7
8#[derive(Clone, PartialEq, Eq, Hash)]
38pub struct Number<'a> {
39 text: Cow<'a, str>,
41}
42
43#[inline]
47fn digits(text: &[u8]) -> Option<u64> {
48 let mut value: u64 = 0;
49 if text.len() < 20 {
50 if text.is_empty() {
51 return None;
52 }
53 for &b in text {
55 let digit = b.wrapping_sub(b'0');
56 if digit > 9 {
57 return None;
58 }
59 value = value * 10 + u64::from(digit);
60 }
61 Some(value)
62 } else {
63 for &b in text {
64 let digit = b.wrapping_sub(b'0');
65 if digit > 9 {
66 return None;
67 }
68 value = value.checked_mul(10)?.checked_add(u64::from(digit))?;
69 }
70 Some(value)
71 }
72}
73
74impl<'a> Number<'a> {
75 #[inline]
77 pub(crate) const fn from_valid(text: &'a str) -> Self {
78 Self {
79 text: Cow::Borrowed(text),
80 }
81 }
82
83 #[must_use]
101 pub fn from_text(text: &'a str) -> Option<Self> {
102 lexer::is_number(text).then_some(Self::from_valid(text))
103 }
104
105 #[must_use]
126 pub fn from_f64(value: f64) -> Option<Number<'static>> {
127 format_f64(value).map(|text| Number {
128 text: Cow::Owned(text),
129 })
130 }
131
132 #[inline]
144 #[must_use]
145 pub fn as_str(&self) -> &str {
146 &self.text
147 }
148
149 #[must_use]
161 pub fn is_integer(&self) -> bool {
162 !self.text.bytes().any(|b| matches!(b, b'.' | b'e' | b'E'))
163 }
164
165 #[must_use]
180 #[inline]
181 pub fn as_i64(&self) -> Option<i64> {
182 match self.text.strip_prefix('-') {
183 Some(magnitude) => 0i64.checked_sub_unsigned(digits(magnitude.as_bytes())?),
184 None => i64::try_from(digits(self.text.as_bytes())?).ok(),
185 }
186 }
187
188 #[must_use]
203 #[inline]
204 pub fn as_u64(&self) -> Option<u64> {
205 match self.text.strip_prefix('-') {
206 Some("0") => Some(0),
209 Some(_) => None,
210 None => digits(self.text.as_bytes()),
211 }
212 }
213
214 #[must_use]
227 pub fn as_i128(&self) -> Option<i128> {
228 if self.is_integer() {
229 self.text.parse().ok()
230 } else {
231 None
232 }
233 }
234
235 #[must_use]
249 pub fn as_u128(&self) -> Option<u128> {
250 if !self.is_integer() {
251 return None;
252 }
253 match self.text.strip_prefix('-') {
254 Some("0") => Some(0),
255 Some(_) => None,
256 None => self.text.parse().ok(),
257 }
258 }
259
260 #[must_use]
285 pub fn whole_value(&self) -> Option<i128> {
286 let text = self.text.as_bytes();
287 let (negative, text) = match text.split_first() {
288 Some((b'-', rest)) => (true, rest),
289 _ => (false, text),
290 };
291 let (mantissa, exponent) = match text.iter().position(|&b| b == b'e' || b == b'E') {
292 Some(at) => (text.get(..at)?, text.get(at + 1..)?),
293 None => (text, &b""[..]),
294 };
295 let (int, frac) = match mantissa.iter().position(|&b| b == b'.') {
296 Some(at) => (mantissa.get(..at)?, mantissa.get(at + 1..)?),
297 None => (mantissa, &b""[..]),
298 };
299 let (exp_negative, exp_digits) = match exponent.split_first() {
302 Some((b'-', rest)) => (true, rest),
303 Some((b'+', rest)) => (false, rest),
304 _ => (false, exponent),
305 };
306 let mut exp: i64 = 0;
307 for &d in exp_digits {
308 exp = exp.saturating_mul(10).saturating_add(i64::from(d - b'0'));
309 }
310 if exp_negative {
311 exp = -exp;
312 }
313 let digits = int.iter().chain(frac.iter()).copied();
315 let mut scale = exp.saturating_sub(frac.len() as i64);
316 let significant: alloc::vec::Vec<u8> = digits.skip_while(|&d| d == b'0').collect();
317 let trailing = significant.iter().rev().take_while(|&&d| d == b'0').count();
318 let significant = significant.get(..significant.len() - trailing)?;
319 scale = scale.saturating_add(trailing as i64);
320 if significant.is_empty() {
321 return Some(0);
322 }
323 if scale < 0 || (significant.len() as i64).saturating_add(scale) > 39 {
324 return None;
325 }
326 let mut magnitude: u128 = 0;
327 for &d in significant {
328 magnitude = magnitude
329 .checked_mul(10)?
330 .checked_add(u128::from(d - b'0'))?;
331 }
332 for _ in 0..scale {
333 magnitude = magnitude.checked_mul(10)?;
334 }
335 if negative {
336 0i128.checked_sub_unsigned(magnitude)
337 } else {
338 i128::try_from(magnitude).ok()
339 }
340 }
341
342 #[must_use]
354 pub fn as_f32(&self) -> Option<f32> {
355 self.text.parse::<f32>().ok().filter(|x| x.is_finite())
356 }
357
358 #[must_use]
375 pub fn as_f64(&self) -> Option<f64> {
376 self.text.parse::<f64>().ok().filter(|x| x.is_finite())
377 }
378
379 #[must_use]
393 pub fn into_owned(self) -> Number<'static> {
394 Number {
395 text: Cow::Owned(self.text.into_owned()),
396 }
397 }
398}
399
400macro_rules! from_integer {
401 ($($t:ty => $via:ty, $write:ident);* $(;)?) => {$(
402 impl From<$t> for Number<'static> {
403 #[inline]
405 fn from(value: $t) -> Self {
406 let mut text = String::new();
407 $write(&mut text, <$via>::from(value));
408 Self { text: Cow::Owned(text) }
409 }
410 }
411 )*};
412}
413
414from_integer!(
415 i8 => i64, write_i64; i16 => i64, write_i64; i32 => i64, write_i64; i64 => i64, write_i64;
416 u8 => u64, write_u64; u16 => u64, write_u64; u32 => u64, write_u64; u64 => u64, write_u64;
417 i128 => i128, write_i128; u128 => u128, write_u128;
418);
419
420impl From<isize> for Number<'static> {
421 #[inline]
423 fn from(value: isize) -> Self {
424 let mut text = String::new();
425 match i64::try_from(value) {
428 Ok(n) => write_i64(&mut text, n),
429 Err(_) => write_i128(&mut text, value as i128),
430 }
431 Self {
432 text: Cow::Owned(text),
433 }
434 }
435}
436
437impl From<usize> for Number<'static> {
438 #[inline]
440 fn from(value: usize) -> Self {
441 let mut text = String::new();
442 match u64::try_from(value) {
443 Ok(n) => write_u64(&mut text, n),
444 Err(_) => write_u128(&mut text, value as u128),
445 }
446 Self {
447 text: Cow::Owned(text),
448 }
449 }
450}
451
452impl fmt::Display for Number<'_> {
453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455 f.write_str(&self.text)
456 }
457}
458
459impl fmt::Debug for Number<'_> {
460 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461 f.write_str(&self.text)
462 }
463}
464
465#[cfg(test)]
467fn zeros(out: &mut String, count: usize) {
468 out.extend(core::iter::repeat_n('0', count));
469}
470
471#[inline]
474pub(crate) fn write_u64(out: &mut String, value: u64) {
475 let mut digits = [0u8; 20];
476 let start = float::put_digits(&mut digits, 20, value);
477 float::push_ascii(out, digits.get(start..).unwrap_or_default());
478}
479
480#[inline]
482pub(crate) fn write_i64(out: &mut String, value: i64) {
483 if value < 0 {
484 out.push('-');
485 }
486 write_u64(out, value.unsigned_abs());
487}
488
489pub(crate) fn write_u128(out: &mut String, value: u128) {
491 if let Ok(small) = u64::try_from(value) {
492 return write_u64(out, small);
493 }
494 let mut digits = [0u8; 39];
495 let mut at = digits.len();
496 let mut rest = value;
497 while rest > 0 {
498 at -= 1;
499 if let Some(slot) = digits.get_mut(at) {
500 *slot = b'0' + (rest % 10) as u8;
501 }
502 rest /= 10;
503 }
504 out.push_str(core::str::from_utf8(digits.get(at..).unwrap_or_default()).unwrap_or("0"));
505}
506
507pub(crate) fn write_i128(out: &mut String, value: i128) {
509 if value < 0 {
510 out.push('-');
511 }
512 write_u128(out, value.unsigned_abs());
513}
514
515fn format_f64(value: f64) -> Option<String> {
518 let mut out = String::with_capacity(26);
519 write_f64(&mut out, value).then_some(out)
520}
521
522#[inline]
526pub(crate) fn write_f64(out: &mut String, value: f64) -> bool {
527 write_f64_as(out, value, Format::compact())
528}
529
530pub(crate) fn write_f64_as(out: &mut String, value: f64, format: Format) -> bool {
533 if !value.is_finite() {
534 return false;
535 }
536 let decimal = float::f64_decimal(value, format.ties());
537 float::write_decimal(out, value.is_sign_negative(), decimal, format.exponent_plus);
538 true
539}
540
541#[cfg(test)]
545pub(crate) fn write_f32(out: &mut String, value: f32) -> bool {
546 write_f32_as(out, value, Format::compact())
547}
548
549pub(crate) fn write_f32_as(out: &mut String, value: f32, format: Format) -> bool {
551 if !value.is_finite() {
552 return false;
553 }
554 let decimal = float::f32_decimal(value, format.ties());
555 float::write_decimal(out, value.is_sign_negative(), decimal, format.exponent_plus);
556 true
557}
558
559#[cfg(test)]
563pub(crate) fn core_text(sci: &str) -> String {
564 let mut out = String::new();
565 let (negative, sci) = match sci.strip_prefix('-') {
566 Some(rest) => (true, rest),
567 None => (false, sci),
568 };
569 let (mantissa, exponent) = sci.split_once('e').unwrap_or((sci, "0"));
570 let exponent: i32 = exponent.parse().unwrap_or(0);
571 let (lead, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
572 if negative {
573 out.push('-');
574 }
575 if (-5..16).contains(&exponent) {
576 if let Ok(point) = usize::try_from(exponent) {
577 out.push_str(lead);
578 if frac.len() <= point {
579 out.push_str(frac);
580 zeros(&mut out, point - frac.len());
581 out.push_str(".0");
582 } else {
583 let (int, rest) = frac.split_at_checked(point).unwrap_or((frac, ""));
584 out.push_str(int);
585 out.push('.');
586 out.push_str(rest);
587 }
588 } else {
589 out.push_str("0.");
590 zeros(&mut out, exponent.unsigned_abs() as usize - 1);
591 out.push_str(lead);
592 out.push_str(frac);
593 }
594 } else {
595 out.push_str(lead);
596 if !frac.is_empty() {
597 out.push('.');
598 out.push_str(frac);
599 }
600 out.push('e');
601 out.push_str(&alloc::format!("{exponent}"));
602 }
603 out
604}
605
606#[cfg(test)]
607mod tests {
608 use alloc::vec::Vec;
609
610 use proptest::prelude::*;
611
612 use super::*;
613
614 #[test]
615 fn test_integer_reads_agree_with_the_standard_parser() {
616 let texts = [
617 "0",
618 "-0",
619 "1",
620 "-1",
621 "9",
622 "10",
623 "18446744073709551615",
624 "18446744073709551616",
625 "99999999999999999999",
626 "100000000000000000000",
627 "9223372036854775807",
628 "9223372036854775808",
629 "-9223372036854775808",
630 "-9223372036854775809",
631 "1234567890123456789",
632 "12345678901234567890",
633 "-12345678901234567890",
634 "1.0",
635 "1e2",
636 "-1.5",
637 "0.0",
638 "-0e0",
639 "123456789012345678901234567890",
640 ];
641 for text in texts {
642 let n = Number::from_text(text).unwrap();
643 let integer = n.is_integer();
644 let want_i64 = integer.then(|| text.parse::<i64>().ok()).flatten();
645 let want_u64 = match text.strip_prefix('-') {
646 Some("0") => Some(0),
647 Some(_) => None,
648 None => integer.then(|| text.parse::<u64>().ok()).flatten(),
649 };
650 assert_eq!(n.as_i64(), want_i64, "{text}");
651 assert_eq!(n.as_u64(), want_u64, "{text}");
652 }
653 }
654
655 fn f(x: f64) -> String {
656 format_f64(x).unwrap_or_default()
657 }
658
659 #[test]
660 fn test_format_f64_layouts() {
661 let cases: &[(f64, &str)] = &[
662 (0.0, "0.0"),
663 (-0.0, "-0.0"),
664 (1.0, "1.0"),
665 (1.5, "1.5"),
666 (100.0, "100.0"),
667 (123.456, "123.456"),
668 (0.1, "0.1"),
669 (1e-5, "0.00001"),
670 (1.5e-5, "0.000015"),
671 (1e-6, "1e-6"),
672 (1.5e-7, "1.5e-7"),
673 (1e15, "1000000000000000.0"),
674 (1e16, "1e16"),
675 (1.7976931348623157e308, "1.7976931348623157e308"),
676 (5e-324, "5e-324"),
677 (-2.2250738585072014e-308, "-2.2250738585072014e-308"),
678 (123456789012345.67, "123456789012345.67"),
679 ];
680 for &(x, want) in cases {
681 assert_eq!(f(x), want, "{x:e}");
682 }
683 assert!(format_f64(f64::NAN).is_none());
684 assert!(format_f64(f64::INFINITY).is_none());
685 assert!(format_f64(f64::NEG_INFINITY).is_none());
686 }
687
688 #[test]
689 fn test_integer_conversions_exact() {
690 assert_eq!(Number::from(i64::MIN).as_i64(), Some(i64::MIN));
691 assert_eq!(Number::from(u64::MAX).as_u64(), Some(u64::MAX));
692 assert_eq!(Number::from(u64::MAX).as_i64(), None);
693 assert_eq!(Number::from(-1i8).as_u64(), None);
694 assert_eq!(
695 Number::from(u128::MAX).as_str(),
696 "340282366920938463463374607431768211455"
697 );
698 }
699
700 #[test]
701 fn test_integer_writers_match_core_formatting() {
702 let mut out = String::new();
703 for n in [
704 0u64,
705 1,
706 9,
707 10,
708 99,
709 100,
710 12_345,
711 u64::from(u32::MAX),
712 u64::MAX,
713 ] {
714 out.clear();
715 write_u64(&mut out, n);
716 assert_eq!(out, alloc::format!("{n}"));
717 }
718 for n in [0i64, -1, 1, i64::MIN, i64::MAX, -1_000_000] {
719 out.clear();
720 write_i64(&mut out, n);
721 assert_eq!(out, alloc::format!("{n}"));
722 }
723 for n in [
724 0u128,
725 u128::from(u64::MAX),
726 u128::from(u64::MAX) + 1,
727 u128::MAX,
728 ] {
729 out.clear();
730 write_u128(&mut out, n);
731 assert_eq!(out, alloc::format!("{n}"));
732 }
733 for n in [i128::MIN, i128::MAX, -1, 0] {
734 out.clear();
735 write_i128(&mut out, n);
736 assert_eq!(out, alloc::format!("{n}"));
737 }
738 assert_eq!(Number::from(isize::MIN).as_i64(), Some(isize::MIN as i64));
739 assert_eq!(Number::from(usize::MAX).as_u64(), Some(usize::MAX as u64));
740 }
741
742 #[test]
743 fn test_whole_value_edges() {
744 let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
745 assert_eq!(n("0").whole_value(), Some(0));
746 assert_eq!(n("-0.000e5").whole_value(), Some(0));
747 assert_eq!(n("1e-0").whole_value(), Some(1));
748 assert_eq!(n("1E+3").whole_value(), Some(1000));
749 assert_eq!(n("10e-1").whole_value(), Some(1));
750 assert_eq!(n("1e-1").whole_value(), None);
751 assert_eq!(n("1e99999999999999999999").whole_value(), None);
752 assert_eq!(n("1e-99999999999999999999").whole_value(), None);
753 assert_eq!(n("0e99999999999999999999").whole_value(), Some(0));
754 assert_eq!(
755 n("-170141183460469231731687303715884105728").whole_value(),
756 Some(i128::MIN)
757 );
758 assert_eq!(
759 n("170141183460469231731687303715884105728").whole_value(),
760 None
761 );
762 assert_eq!(
763 n("1.7014118346046923173168730371588410572e38").whole_value(),
764 Some(170_141_183_460_469_231_731_687_303_715_884_105_720)
765 );
766 assert_eq!(n("1.23e2").whole_value(), Some(123));
767 }
768
769 #[test]
770 fn test_wide_and_narrow_conversions() {
771 let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
772 assert_eq!(n("170141183460469231731687303715884105728").as_i128(), None);
773 assert_eq!(n("2.5").as_u128(), None);
774 assert_eq!(n("2.5").as_i128(), None);
775 assert_eq!(n("12").as_u128(), Some(12));
776 assert_eq!(n("-3").as_f32(), Some(-3.0));
777 assert_eq!(n("16777217").as_f32(), Some(16_777_216.0));
779 }
780
781 #[test]
782 fn test_f32_is_shortest_for_f32() {
783 let mut out = String::new();
784 assert!(write_f32(&mut out, 0.1));
785 assert_eq!(out, "0.1");
786 out.clear();
787 assert!(write_f32(&mut out, 1.0e20));
788 assert_eq!(out, "1e20");
789 assert!(!write_f32(&mut out, f32::NAN));
790 assert!(!write_f64(&mut out, f64::INFINITY));
791 }
792
793 #[test]
794 fn test_float_options_through_format() {
795 let both = Format::compact().exponent_plus(true).even_ties(true);
796 let tie = 164_696_460_098_373.0 + 0.625;
797 let text = |x: f64, format: Format| {
798 let mut out = String::new();
799 assert!(write_f64_as(&mut out, x, format));
800 out
801 };
802 assert_eq!(text(1e16, both), "1e+16");
803 assert_eq!(text(-1e-7, both), "-1e-7");
804 assert_eq!(text(tie, both), "164696460098373.62");
805 assert_eq!(
806 text(tie, Format::compact().exponent_plus(true)),
807 "164696460098373.63"
808 );
809 assert_eq!(text(1e300, Format::pretty().exponent_plus(true)), "1e+300");
810 let mut out = String::new();
811 assert!(write_f32_as(&mut out, 1e20, both));
812 assert_eq!(out, "1e+20");
813 assert!(!write_f32_as(&mut out, f32::INFINITY, both));
814 assert!(!write_f64_as(&mut out, f64::NAN, both));
815 assert_eq!(out, "1e+20");
816 let f = Format::compact()
818 .html_safe(true)
819 .exponent_plus(true)
820 .even_ties(true);
821 assert!(f.exponent_plus && f.even_ties && f.html && !f.pretty);
822 assert_eq!(Format::default(), Format::compact());
823 assert_ne!(both, Format::compact());
824 }
825
826 proptest! {
827 #[test]
831 fn prop_float_options_keep_the_value(bits in any::<u64>()) {
832 let x = f64::from_bits(bits);
833 prop_assume!(x.is_finite());
834 let both = Format::compact().exponent_plus(true).even_ties(true);
835 let mut out = String::new();
836 prop_assert!(write_f64_as(&mut out, x, both));
837 prop_assert!(lexer::is_number(&out), "{}", out);
838 prop_assert_eq!(out.parse::<f64>().map(f64::to_bits).ok(), Some(x.to_bits()));
839 let mut plain = String::new();
840 prop_assert!(write_f64_as(&mut plain, x, Format::compact().exponent_plus(true)));
841 let mut default = String::new();
842 prop_assert!(write_f64(&mut default, x));
843 prop_assert_eq!(plain.replacen("e+", "e", 1), default);
844 }
845
846 #[test]
847 fn prop_f32_text_round_trips(bits in any::<u32>()) {
848 let x = f32::from_bits(bits);
849 prop_assume!(x.is_finite());
850 let mut out = String::new();
851 prop_assert!(write_f32(&mut out, x));
852 prop_assert!(lexer::is_number(&out), "{}", out);
853 prop_assert_eq!(out.parse::<f32>().map(f32::to_bits).ok(), Some(x.to_bits()));
854 }
855
856 #[test]
858 fn prop_whole_value_of_any_spelling(n in any::<i64>(), shift in 0usize..20, zeros in 0usize..4) {
859 let plain = alloc::format!("{n}");
860 prop_assert_eq!(Number::from_text(&plain).and_then(|x| x.whole_value()), Some(i128::from(n)));
861 let spelled = alloc::format!("{n}{}e{}", "0".repeat(zeros), shift as i64 - zeros as i64);
863 let want = i128::from(n).checked_mul(10i128.pow(shift as u32));
864 prop_assert_eq!(Number::from_text(&spelled).and_then(|x| x.whole_value()), want);
865 let fraction = alloc::format!("{n}.{}", "0".repeat(zeros + 1));
866 prop_assert_eq!(Number::from_text(&fraction).and_then(|x| x.whole_value()), Some(i128::from(n)));
867 }
868
869 #[test]
870 fn prop_integer_writers_match_core(n in any::<i128>()) {
871 let mut out = String::new();
872 write_i128(&mut out, n);
873 prop_assert_eq!(out, alloc::format!("{n}"));
874 }
875
876 #[test]
877 fn prop_f64_text_is_valid_and_round_trips(bits in any::<u64>()) {
878 let x = f64::from_bits(bits);
879 prop_assume!(x.is_finite());
880 let n = Number::from_f64(x).unwrap_or_else(|| Number::from(0));
881 prop_assert!(lexer::is_number(n.as_str()), "{}", n.as_str());
882 prop_assert!(!n.is_integer());
883 let back = n.as_f64().unwrap_or(f64::NAN);
884 prop_assert_eq!(back.to_bits(), x.to_bits());
885 let digits: Vec<u8> = alloc::format!("{x:e}").bytes().take_while(|&b| b != b'e').filter(u8::is_ascii_digit).collect();
888 let ours: Vec<u8> = n.as_str().bytes().take_while(|&b| b != b'e' && b != b'E').filter(u8::is_ascii_digit).collect();
889 let trim = |d: &[u8]| -> Vec<u8> {
890 let s: &[u8] = d;
891 let start = s.iter().position(|&b| b != b'0').unwrap_or(s.len());
892 let end = s.iter().rposition(|&b| b != b'0').map_or(start, |e| e + 1);
893 s.get(start..end.max(start)).unwrap_or(&[]).to_vec()
894 };
895 prop_assert_eq!(trim(&digits), trim(&ours));
896 }
897
898 #[test]
899 fn prop_i64_round_trips(x in any::<i64>()) {
900 prop_assert_eq!(Number::from(x).as_i64(), Some(x));
901 }
902
903 #[test]
904 fn prop_u64_round_trips(x in any::<u64>()) {
905 prop_assert_eq!(Number::from(x).as_u64(), Some(x));
906 }
907 }
908}