use alloc::{borrow::Cow, string::String};
use core::fmt;
use crate::{Format, float, lexer};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Number<'a> {
text: Cow<'a, str>,
}
#[inline]
fn digits(text: &[u8]) -> Option<u64> {
let mut value: u64 = 0;
if text.len() < 20 {
if text.is_empty() {
return None;
}
for &b in text {
let digit = b.wrapping_sub(b'0');
if digit > 9 {
return None;
}
value = value * 10 + u64::from(digit);
}
Some(value)
} else {
for &b in text {
let digit = b.wrapping_sub(b'0');
if digit > 9 {
return None;
}
value = value.checked_mul(10)?.checked_add(u64::from(digit))?;
}
Some(value)
}
}
impl<'a> Number<'a> {
#[inline]
pub(crate) const fn from_valid(text: &'a str) -> Self {
Self {
text: Cow::Borrowed(text),
}
}
#[must_use]
pub fn from_text(text: &'a str) -> Option<Self> {
lexer::is_number(text).then_some(Self::from_valid(text))
}
#[must_use]
pub fn from_f64(value: f64) -> Option<Number<'static>> {
format_f64(value).map(|text| Number {
text: Cow::Owned(text),
})
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.text
}
#[must_use]
pub fn is_integer(&self) -> bool {
!self.text.bytes().any(|b| matches!(b, b'.' | b'e' | b'E'))
}
#[must_use]
#[inline]
pub fn as_i64(&self) -> Option<i64> {
match self.text.strip_prefix('-') {
Some(magnitude) => 0i64.checked_sub_unsigned(digits(magnitude.as_bytes())?),
None => i64::try_from(digits(self.text.as_bytes())?).ok(),
}
}
#[must_use]
#[inline]
pub fn as_u64(&self) -> Option<u64> {
match self.text.strip_prefix('-') {
Some("0") => Some(0),
Some(_) => None,
None => digits(self.text.as_bytes()),
}
}
#[must_use]
pub fn as_i128(&self) -> Option<i128> {
if self.is_integer() {
self.text.parse().ok()
} else {
None
}
}
#[must_use]
pub fn as_u128(&self) -> Option<u128> {
if !self.is_integer() {
return None;
}
match self.text.strip_prefix('-') {
Some("0") => Some(0),
Some(_) => None,
None => self.text.parse().ok(),
}
}
#[must_use]
pub fn whole_value(&self) -> Option<i128> {
let text = self.text.as_bytes();
let (negative, text) = match text.split_first() {
Some((b'-', rest)) => (true, rest),
_ => (false, text),
};
let (mantissa, exponent) = match text.iter().position(|&b| b == b'e' || b == b'E') {
Some(at) => (text.get(..at)?, text.get(at + 1..)?),
None => (text, &b""[..]),
};
let (int, frac) = match mantissa.iter().position(|&b| b == b'.') {
Some(at) => (mantissa.get(..at)?, mantissa.get(at + 1..)?),
None => (mantissa, &b""[..]),
};
let (exp_negative, exp_digits) = match exponent.split_first() {
Some((b'-', rest)) => (true, rest),
Some((b'+', rest)) => (false, rest),
_ => (false, exponent),
};
let mut exp: i64 = 0;
for &d in exp_digits {
exp = exp.saturating_mul(10).saturating_add(i64::from(d - b'0'));
}
if exp_negative {
exp = -exp;
}
let digits = int.iter().chain(frac.iter()).copied();
let mut scale = exp.saturating_sub(frac.len() as i64);
let significant: alloc::vec::Vec<u8> = digits.skip_while(|&d| d == b'0').collect();
let trailing = significant.iter().rev().take_while(|&&d| d == b'0').count();
let significant = significant.get(..significant.len() - trailing)?;
scale = scale.saturating_add(trailing as i64);
if significant.is_empty() {
return Some(0);
}
if scale < 0 || (significant.len() as i64).saturating_add(scale) > 39 {
return None;
}
let mut magnitude: u128 = 0;
for &d in significant {
magnitude = magnitude
.checked_mul(10)?
.checked_add(u128::from(d - b'0'))?;
}
for _ in 0..scale {
magnitude = magnitude.checked_mul(10)?;
}
if negative {
0i128.checked_sub_unsigned(magnitude)
} else {
i128::try_from(magnitude).ok()
}
}
#[must_use]
pub fn as_f32(&self) -> Option<f32> {
self.text.parse::<f32>().ok().filter(|x| x.is_finite())
}
#[must_use]
pub fn as_f64(&self) -> Option<f64> {
self.text.parse::<f64>().ok().filter(|x| x.is_finite())
}
#[must_use]
pub fn into_owned(self) -> Number<'static> {
Number {
text: Cow::Owned(self.text.into_owned()),
}
}
}
macro_rules! from_integer {
($($t:ty => $via:ty, $write:ident);* $(;)?) => {$(
impl From<$t> for Number<'static> {
#[inline]
fn from(value: $t) -> Self {
let mut text = String::new();
$write(&mut text, <$via>::from(value));
Self { text: Cow::Owned(text) }
}
}
)*};
}
from_integer!(
i8 => i64, write_i64; i16 => i64, write_i64; i32 => i64, write_i64; i64 => i64, write_i64;
u8 => u64, write_u64; u16 => u64, write_u64; u32 => u64, write_u64; u64 => u64, write_u64;
i128 => i128, write_i128; u128 => u128, write_u128;
);
impl From<isize> for Number<'static> {
#[inline]
fn from(value: isize) -> Self {
let mut text = String::new();
match i64::try_from(value) {
Ok(n) => write_i64(&mut text, n),
Err(_) => write_i128(&mut text, value as i128),
}
Self {
text: Cow::Owned(text),
}
}
}
impl From<usize> for Number<'static> {
#[inline]
fn from(value: usize) -> Self {
let mut text = String::new();
match u64::try_from(value) {
Ok(n) => write_u64(&mut text, n),
Err(_) => write_u128(&mut text, value as u128),
}
Self {
text: Cow::Owned(text),
}
}
}
impl fmt::Display for Number<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
impl fmt::Debug for Number<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
#[cfg(test)]
fn zeros(out: &mut String, count: usize) {
out.extend(core::iter::repeat_n('0', count));
}
#[inline]
pub(crate) fn write_u64(out: &mut String, value: u64) {
let mut digits = [0u8; 20];
let start = float::put_digits(&mut digits, 20, value);
float::push_ascii(out, digits.get(start..).unwrap_or_default());
}
#[inline]
pub(crate) fn write_i64(out: &mut String, value: i64) {
if value < 0 {
out.push('-');
}
write_u64(out, value.unsigned_abs());
}
pub(crate) fn write_u128(out: &mut String, value: u128) {
if let Ok(small) = u64::try_from(value) {
return write_u64(out, small);
}
let mut digits = [0u8; 39];
let mut at = digits.len();
let mut rest = value;
while rest > 0 {
at -= 1;
if let Some(slot) = digits.get_mut(at) {
*slot = b'0' + (rest % 10) as u8;
}
rest /= 10;
}
out.push_str(core::str::from_utf8(digits.get(at..).unwrap_or_default()).unwrap_or("0"));
}
pub(crate) fn write_i128(out: &mut String, value: i128) {
if value < 0 {
out.push('-');
}
write_u128(out, value.unsigned_abs());
}
fn format_f64(value: f64) -> Option<String> {
let mut out = String::with_capacity(26);
write_f64(&mut out, value).then_some(out)
}
#[inline]
pub(crate) fn write_f64(out: &mut String, value: f64) -> bool {
write_f64_as(out, value, Format::compact())
}
pub(crate) fn write_f64_as(out: &mut String, value: f64, format: Format) -> bool {
if !value.is_finite() {
return false;
}
let decimal = float::f64_decimal(value, format.ties());
float::write_decimal(out, value.is_sign_negative(), decimal, format.exponent_plus);
true
}
#[cfg(test)]
pub(crate) fn write_f32(out: &mut String, value: f32) -> bool {
write_f32_as(out, value, Format::compact())
}
pub(crate) fn write_f32_as(out: &mut String, value: f32, format: Format) -> bool {
if !value.is_finite() {
return false;
}
let decimal = float::f32_decimal(value, format.ties());
float::write_decimal(out, value.is_sign_negative(), decimal, format.exponent_plus);
true
}
#[cfg(test)]
pub(crate) fn core_text(sci: &str) -> String {
let mut out = String::new();
let (negative, sci) = match sci.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, sci),
};
let (mantissa, exponent) = sci.split_once('e').unwrap_or((sci, "0"));
let exponent: i32 = exponent.parse().unwrap_or(0);
let (lead, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
if negative {
out.push('-');
}
if (-5..16).contains(&exponent) {
if let Ok(point) = usize::try_from(exponent) {
out.push_str(lead);
if frac.len() <= point {
out.push_str(frac);
zeros(&mut out, point - frac.len());
out.push_str(".0");
} else {
let (int, rest) = frac.split_at_checked(point).unwrap_or((frac, ""));
out.push_str(int);
out.push('.');
out.push_str(rest);
}
} else {
out.push_str("0.");
zeros(&mut out, exponent.unsigned_abs() as usize - 1);
out.push_str(lead);
out.push_str(frac);
}
} else {
out.push_str(lead);
if !frac.is_empty() {
out.push('.');
out.push_str(frac);
}
out.push('e');
out.push_str(&alloc::format!("{exponent}"));
}
out
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use proptest::prelude::*;
use super::*;
#[test]
fn test_integer_reads_agree_with_the_standard_parser() {
let texts = [
"0",
"-0",
"1",
"-1",
"9",
"10",
"18446744073709551615",
"18446744073709551616",
"99999999999999999999",
"100000000000000000000",
"9223372036854775807",
"9223372036854775808",
"-9223372036854775808",
"-9223372036854775809",
"1234567890123456789",
"12345678901234567890",
"-12345678901234567890",
"1.0",
"1e2",
"-1.5",
"0.0",
"-0e0",
"123456789012345678901234567890",
];
for text in texts {
let n = Number::from_text(text).unwrap();
let integer = n.is_integer();
let want_i64 = integer.then(|| text.parse::<i64>().ok()).flatten();
let want_u64 = match text.strip_prefix('-') {
Some("0") => Some(0),
Some(_) => None,
None => integer.then(|| text.parse::<u64>().ok()).flatten(),
};
assert_eq!(n.as_i64(), want_i64, "{text}");
assert_eq!(n.as_u64(), want_u64, "{text}");
}
}
fn f(x: f64) -> String {
format_f64(x).unwrap_or_default()
}
#[test]
fn test_format_f64_layouts() {
let cases: &[(f64, &str)] = &[
(0.0, "0.0"),
(-0.0, "-0.0"),
(1.0, "1.0"),
(1.5, "1.5"),
(100.0, "100.0"),
(123.456, "123.456"),
(0.1, "0.1"),
(1e-5, "0.00001"),
(1.5e-5, "0.000015"),
(1e-6, "1e-6"),
(1.5e-7, "1.5e-7"),
(1e15, "1000000000000000.0"),
(1e16, "1e16"),
(1.7976931348623157e308, "1.7976931348623157e308"),
(5e-324, "5e-324"),
(-2.2250738585072014e-308, "-2.2250738585072014e-308"),
(123456789012345.67, "123456789012345.67"),
];
for &(x, want) in cases {
assert_eq!(f(x), want, "{x:e}");
}
assert!(format_f64(f64::NAN).is_none());
assert!(format_f64(f64::INFINITY).is_none());
assert!(format_f64(f64::NEG_INFINITY).is_none());
}
#[test]
fn test_integer_conversions_exact() {
assert_eq!(Number::from(i64::MIN).as_i64(), Some(i64::MIN));
assert_eq!(Number::from(u64::MAX).as_u64(), Some(u64::MAX));
assert_eq!(Number::from(u64::MAX).as_i64(), None);
assert_eq!(Number::from(-1i8).as_u64(), None);
assert_eq!(
Number::from(u128::MAX).as_str(),
"340282366920938463463374607431768211455"
);
}
#[test]
fn test_integer_writers_match_core_formatting() {
let mut out = String::new();
for n in [
0u64,
1,
9,
10,
99,
100,
12_345,
u64::from(u32::MAX),
u64::MAX,
] {
out.clear();
write_u64(&mut out, n);
assert_eq!(out, alloc::format!("{n}"));
}
for n in [0i64, -1, 1, i64::MIN, i64::MAX, -1_000_000] {
out.clear();
write_i64(&mut out, n);
assert_eq!(out, alloc::format!("{n}"));
}
for n in [
0u128,
u128::from(u64::MAX),
u128::from(u64::MAX) + 1,
u128::MAX,
] {
out.clear();
write_u128(&mut out, n);
assert_eq!(out, alloc::format!("{n}"));
}
for n in [i128::MIN, i128::MAX, -1, 0] {
out.clear();
write_i128(&mut out, n);
assert_eq!(out, alloc::format!("{n}"));
}
assert_eq!(Number::from(isize::MIN).as_i64(), Some(isize::MIN as i64));
assert_eq!(Number::from(usize::MAX).as_u64(), Some(usize::MAX as u64));
}
#[test]
fn test_whole_value_edges() {
let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
assert_eq!(n("0").whole_value(), Some(0));
assert_eq!(n("-0.000e5").whole_value(), Some(0));
assert_eq!(n("1e-0").whole_value(), Some(1));
assert_eq!(n("1E+3").whole_value(), Some(1000));
assert_eq!(n("10e-1").whole_value(), Some(1));
assert_eq!(n("1e-1").whole_value(), None);
assert_eq!(n("1e99999999999999999999").whole_value(), None);
assert_eq!(n("1e-99999999999999999999").whole_value(), None);
assert_eq!(n("0e99999999999999999999").whole_value(), Some(0));
assert_eq!(
n("-170141183460469231731687303715884105728").whole_value(),
Some(i128::MIN)
);
assert_eq!(
n("170141183460469231731687303715884105728").whole_value(),
None
);
assert_eq!(
n("1.7014118346046923173168730371588410572e38").whole_value(),
Some(170_141_183_460_469_231_731_687_303_715_884_105_720)
);
assert_eq!(n("1.23e2").whole_value(), Some(123));
}
#[test]
fn test_wide_and_narrow_conversions() {
let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
assert_eq!(n("170141183460469231731687303715884105728").as_i128(), None);
assert_eq!(n("2.5").as_u128(), None);
assert_eq!(n("2.5").as_i128(), None);
assert_eq!(n("12").as_u128(), Some(12));
assert_eq!(n("-3").as_f32(), Some(-3.0));
assert_eq!(n("16777217").as_f32(), Some(16_777_216.0));
}
#[test]
fn test_f32_is_shortest_for_f32() {
let mut out = String::new();
assert!(write_f32(&mut out, 0.1));
assert_eq!(out, "0.1");
out.clear();
assert!(write_f32(&mut out, 1.0e20));
assert_eq!(out, "1e20");
assert!(!write_f32(&mut out, f32::NAN));
assert!(!write_f64(&mut out, f64::INFINITY));
}
#[test]
fn test_float_options_through_format() {
let both = Format::compact().exponent_plus(true).even_ties(true);
let tie = 164_696_460_098_373.0 + 0.625;
let text = |x: f64, format: Format| {
let mut out = String::new();
assert!(write_f64_as(&mut out, x, format));
out
};
assert_eq!(text(1e16, both), "1e+16");
assert_eq!(text(-1e-7, both), "-1e-7");
assert_eq!(text(tie, both), "164696460098373.62");
assert_eq!(
text(tie, Format::compact().exponent_plus(true)),
"164696460098373.63"
);
assert_eq!(text(1e300, Format::pretty().exponent_plus(true)), "1e+300");
let mut out = String::new();
assert!(write_f32_as(&mut out, 1e20, both));
assert_eq!(out, "1e+20");
assert!(!write_f32_as(&mut out, f32::INFINITY, both));
assert!(!write_f64_as(&mut out, f64::NAN, both));
assert_eq!(out, "1e+20");
let f = Format::compact()
.html_safe(true)
.exponent_plus(true)
.even_ties(true);
assert!(f.exponent_plus && f.even_ties && f.html && !f.pretty);
assert_eq!(Format::default(), Format::compact());
assert_ne!(both, Format::compact());
}
proptest! {
#[test]
fn prop_float_options_keep_the_value(bits in any::<u64>()) {
let x = f64::from_bits(bits);
prop_assume!(x.is_finite());
let both = Format::compact().exponent_plus(true).even_ties(true);
let mut out = String::new();
prop_assert!(write_f64_as(&mut out, x, both));
prop_assert!(lexer::is_number(&out), "{}", out);
prop_assert_eq!(out.parse::<f64>().map(f64::to_bits).ok(), Some(x.to_bits()));
let mut plain = String::new();
prop_assert!(write_f64_as(&mut plain, x, Format::compact().exponent_plus(true)));
let mut default = String::new();
prop_assert!(write_f64(&mut default, x));
prop_assert_eq!(plain.replacen("e+", "e", 1), default);
}
#[test]
fn prop_f32_text_round_trips(bits in any::<u32>()) {
let x = f32::from_bits(bits);
prop_assume!(x.is_finite());
let mut out = String::new();
prop_assert!(write_f32(&mut out, x));
prop_assert!(lexer::is_number(&out), "{}", out);
prop_assert_eq!(out.parse::<f32>().map(f32::to_bits).ok(), Some(x.to_bits()));
}
#[test]
fn prop_whole_value_of_any_spelling(n in any::<i64>(), shift in 0usize..20, zeros in 0usize..4) {
let plain = alloc::format!("{n}");
prop_assert_eq!(Number::from_text(&plain).and_then(|x| x.whole_value()), Some(i128::from(n)));
let spelled = alloc::format!("{n}{}e{}", "0".repeat(zeros), shift as i64 - zeros as i64);
let want = i128::from(n).checked_mul(10i128.pow(shift as u32));
prop_assert_eq!(Number::from_text(&spelled).and_then(|x| x.whole_value()), want);
let fraction = alloc::format!("{n}.{}", "0".repeat(zeros + 1));
prop_assert_eq!(Number::from_text(&fraction).and_then(|x| x.whole_value()), Some(i128::from(n)));
}
#[test]
fn prop_integer_writers_match_core(n in any::<i128>()) {
let mut out = String::new();
write_i128(&mut out, n);
prop_assert_eq!(out, alloc::format!("{n}"));
}
#[test]
fn prop_f64_text_is_valid_and_round_trips(bits in any::<u64>()) {
let x = f64::from_bits(bits);
prop_assume!(x.is_finite());
let n = Number::from_f64(x).unwrap_or_else(|| Number::from(0));
prop_assert!(lexer::is_number(n.as_str()), "{}", n.as_str());
prop_assert!(!n.is_integer());
let back = n.as_f64().unwrap_or(f64::NAN);
prop_assert_eq!(back.to_bits(), x.to_bits());
let digits: Vec<u8> = alloc::format!("{x:e}").bytes().take_while(|&b| b != b'e').filter(u8::is_ascii_digit).collect();
let ours: Vec<u8> = n.as_str().bytes().take_while(|&b| b != b'e' && b != b'E').filter(u8::is_ascii_digit).collect();
let trim = |d: &[u8]| -> Vec<u8> {
let s: &[u8] = d;
let start = s.iter().position(|&b| b != b'0').unwrap_or(s.len());
let end = s.iter().rposition(|&b| b != b'0').map_or(start, |e| e + 1);
s.get(start..end.max(start)).unwrap_or(&[]).to_vec()
};
prop_assert_eq!(trim(&digits), trim(&ours));
}
#[test]
fn prop_i64_round_trips(x in any::<i64>()) {
prop_assert_eq!(Number::from(x).as_i64(), Some(x));
}
#[test]
fn prop_u64_round_trips(x in any::<u64>()) {
prop_assert_eq!(Number::from(x).as_u64(), Some(x));
}
}
}