use alloc::{borrow::Cow, string::String};
use core::fmt::{self, Write as _};
use crate::lexer;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Number<'a> {
text: Cow<'a, str>,
}
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]
pub fn as_i64(&self) -> Option<i64> {
if self.is_integer() {
self.text.parse().ok()
} else {
None
}
}
#[must_use]
pub fn as_u64(&self) -> Option<u64> {
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 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),*) => {$(
impl From<$t> for Number<'static> {
#[inline]
fn from(value: $t) -> Self {
let mut text = String::new();
let _infallible = write!(text, "{value}");
Self { text: Cow::Owned(text) }
}
}
)*};
}
from_integer!(
i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
);
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)
}
}
struct StackText {
buf: [u8; 40],
len: usize,
}
impl fmt::Write for StackText {
fn write_str(&mut self, s: &str) -> fmt::Result {
let end = self.len + s.len();
let slot = self.buf.get_mut(self.len..end).ok_or(fmt::Error)?;
slot.copy_from_slice(s.as_bytes());
self.len = end;
Ok(())
}
}
fn zeros(out: &mut String, count: usize) {
out.extend(core::iter::repeat_n('0', count));
}
fn format_f64(value: f64) -> Option<String> {
if !value.is_finite() {
return None;
}
let mut sci = StackText {
buf: [0; 40],
len: 0,
};
write!(sci, "{value:e}").ok()?;
let sci = core::str::from_utf8(sci.buf.get(..sci.len)?).ok()?;
let (negative, sci) = match sci.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, sci),
};
let (mantissa, exponent) = sci.split_once('e')?;
let exponent: i32 = exponent.parse().ok()?;
let (lead, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
let mut out = String::with_capacity(26);
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 {
out.push_str(frac.get(..point)?);
out.push('.');
out.push_str(frac.get(point..)?);
}
} 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);
}
write!(out, "e{exponent}").ok()?;
}
Some(out)
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use proptest::prelude::*;
use super::*;
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"
);
}
proptest! {
#[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));
}
}
}