Skip to main content

cbcl_core/
numeric.rs

1//! Deterministic non-integer atoms. Floats are finite IEEE 754 binary64;
2//! decimals retain exact, arbitrary precision base-ten values.
3use alloc::string::{String, ToString};
4use core::{fmt, str::FromStr};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[cfg_attr(feature = "serde", serde(try_from = "f64", into = "f64"))]
9pub struct Float(u64);
10impl Float {
11    pub fn new(value: f64) -> Result<Self, &'static str> {
12        if !value.is_finite() {
13            return Err("float must be finite");
14        }
15        Ok(Self(if value == 0.0 { 0 } else { value.to_bits() }))
16    }
17    pub fn get(self) -> f64 {
18        f64::from_bits(self.0)
19    }
20}
21impl TryFrom<f64> for Float {
22    type Error = &'static str;
23    fn try_from(value: f64) -> Result<Self, Self::Error> {
24        Self::new(value)
25    }
26}
27impl From<Float> for f64 {
28    fn from(value: Float) -> Self {
29        value.get()
30    }
31}
32impl FromStr for Float {
33    type Err = &'static str;
34    fn from_str(text: &str) -> Result<Self, Self::Err> {
35        Self::new(text.parse().map_err(|_| "invalid float")?)
36    }
37}
38impl fmt::Display for Float {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        let text = self.get().to_string();
41        f.write_str(&text)?;
42        if !text.contains('.') && !text.contains('e') && !text.contains('E') {
43            f.write_str(".0")?;
44        }
45        Ok(())
46    }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
51#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
52pub struct Decimal(String);
53impl Decimal {
54    /// Canonical exact value, without the wire's `m` suffix.
55    pub fn as_str(&self) -> &str {
56        &self.0
57    }
58}
59impl FromStr for Decimal {
60    type Err = &'static str;
61    fn from_str(text: &str) -> Result<Self, Self::Err> {
62        let (negative, text) = match text.strip_prefix('-') {
63            Some(s) => (true, s),
64            None => (false, text),
65        };
66        let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
67        if whole.is_empty()
68            || !whole.bytes().all(|c| c.is_ascii_digit())
69            || !fraction.bytes().all(|c| c.is_ascii_digit())
70            || text.ends_with('.')
71        {
72            return Err("invalid decimal");
73        }
74        let whole = whole.trim_start_matches('0');
75        let fraction = fraction.trim_end_matches('0');
76        let mut value = String::new();
77        if negative && (!whole.is_empty() || !fraction.is_empty()) {
78            value.push('-');
79        }
80        value.push_str(if whole.is_empty() { "0" } else { whole });
81        if !fraction.is_empty() {
82            value.push('.');
83            value.push_str(fraction);
84        }
85        Ok(Self(value))
86    }
87}
88impl TryFrom<String> for Decimal {
89    type Error = &'static str;
90    fn try_from(value: String) -> Result<Self, Self::Error> {
91        value.parse()
92    }
93}
94impl From<Decimal> for String {
95    fn from(value: Decimal) -> Self {
96        value.0
97    }
98}
99impl fmt::Display for Decimal {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        write!(f, "{}m", self.0)
102    }
103}
104
105/// Recognize a complete non-integer numeric token. `m` marks an exact decimal;
106/// a point or exponent marks a float. Integers keep their existing encoding.
107pub fn parse_atom(text: &str) -> Result<Option<crate::sexpr::Atom>, &'static str> {
108    let number_start = text.as_bytes().first().is_some_and(u8::is_ascii_digit)
109        || text
110            .strip_prefix('-')
111            .and_then(|s| s.as_bytes().first())
112            .is_some_and(u8::is_ascii_digit);
113    if !number_start {
114        return Ok(None);
115    }
116    if let Some(value) = text.strip_suffix('m') {
117        return value.parse().map(crate::sexpr::Atom::Decimal).map(Some);
118    }
119    if text.contains('.') || text.contains('e') || text.contains('E') {
120        return text.parse().map(crate::sexpr::Atom::Float).map(Some);
121    }
122    Ok(None)
123}