grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/number.rs
// Purpose:   A number's text read as a value, by one of two stated readings
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A number's text read as a value, by one of two stated readings.
//!
//! [`NumberReading::Exact`] never rounds an integer: a whole number past `u64`
//! has no value, and the text is the truth. [`NumberReading::Cel`] reads as a
//! cel context built from JSON does, so a whole number past `u64` is the
//! nearest double. A typed column wants `Exact`, and anything compared with
//! cel's answers wants `Cel`.
//!
//! The conversions, `convert::parse_int`, `convert::java::parse_int`,
//! `parse_float` and cel's `int()` and `double()`, aren't readings. Each takes
//! its own forms, and `docs/convert.md` has them in one table beside these two.
//!
//! ```
//! use grippo::number::{Number, NumberReading};
//!
//! let past_u64 = "18446744073709551616";
//! assert_eq!(NumberReading::Exact.read(past_u64), None);
//! assert_eq!(
//!     NumberReading::Cel.read(past_u64),
//!     Some(Number::Float(18_446_744_073_709_551_616.0))
//! );
//! assert_eq!(NumberReading::Exact.read("-7"), NumberReading::Cel.read("-7"));
//! ```

/// A number's value, read by a [`NumberReading`] or by `FieldValue::number`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Number {
    /// A whole number that fits `i64`.
    Int(i64),
    /// A whole number past `i64::MAX` that fits `u64`.
    UInt(u64),
    /// A number read as the nearest `f64`.
    Float(f64),
}

/// How number text becomes a [`Number`].
///
/// Both readings take the same text: an optional `+` or `-`, digits with an
/// optional point, and an optional `e` or `E` exponent. Leading zeros are
/// read. Spaces, `inf`, `nan`, hex and a digit separator aren't, and give
/// `None`. The kind comes from the spelling: a `.`, `e` or `E` makes a float,
/// and anything else is whole. They differ in one place, a whole number outside
/// `i64` and `u64`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NumberReading {
    /// Whole text is `Int`, then `UInt`, and past `u64` or below `i64::MIN`
    /// it has no value, so the caller keeps the text. A float is `Float`,
    /// and none when it rounds to an infinity.
    Exact,
    /// As cel 0.14.5 reads a JSON number: `Int` when it fits `i64`, then
    /// `UInt`, then `Float`. A whole number past both is the nearest double,
    /// and none when that is an infinity. `-0` is `Float(-0.0)`, as
    /// `serde_json` gives it to cel.
    Cel,
}

impl NumberReading {
    /// `text` as a number, or `None` when it isn't a number in the form read.
    ///
    /// `None` never means a bad record. Under `Exact` it also means a number
    /// wider than 64 bits, whose text a store that must be exact keeps.
    #[must_use]
    pub fn read(self, text: &str) -> Option<Number> {
        let text = text.as_bytes();
        if spelled_float(text) {
            return float(text).map(Number::Float);
        }
        match (whole(text), self) {
            // serde_json reads `-0` as a negative zero double, so cel is given one.
            (Ok(Number::Int(0)), Self::Cel) if text.first() == Some(&b'-') => {
                Some(Number::Float(-0.0))
            }
            (Ok(number), _) => Some(number),
            (Err(Whole::Past), Self::Cel) => float(text).map(Number::Float),
            (Err(Whole::Past | Whole::Not), _) => None,
        }
    }
}

/// Why a sign and digits gave no `i64` or `u64`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Whole {
    /// A sign and digits, past `u64` or below `i64::MIN`.
    Past,
    /// Anything else.
    Not,
}

/// A sign and digits, as the widest of `Int` and `UInt` that holds them.
pub(crate) fn whole(text: &[u8]) -> Result<Number, Whole> {
    let (negative, digits) = match text.split_first() {
        Some((b'-', rest)) => (true, rest),
        Some((b'+', rest)) => (false, rest),
        _ => (false, text),
    };
    if digits.is_empty() {
        return Err(Whole::Not);
    }
    let mut value: u64 = 0;
    for (at, &byte) in digits.iter().enumerate() {
        let digit = byte.wrapping_sub(b'0');
        if digit > 9 {
            return Err(Whole::Not);
        }
        let Some(next) = value
            .checked_mul(10)
            .and_then(|v| v.checked_add(u64::from(digit)))
        else {
            let rest = digits.get(at..).unwrap_or_default();
            return Err(if rest.iter().all(u8::is_ascii_digit) {
                Whole::Past
            } else {
                Whole::Not
            });
        };
        value = next;
    }
    if negative {
        0_i64
            .checked_sub_unsigned(value)
            .map(Number::Int)
            .ok_or(Whole::Past)
    } else {
        Ok(i64::try_from(value).map_or(Number::UInt(value), Number::Int))
    }
}

/// Whether the text has a point or an exponent, which makes it a float.
pub(crate) fn spelled_float(text: &[u8]) -> bool {
    text.iter().any(|b| matches!(b, b'.' | b'e' | b'E'))
}

/// Decimal text as an `f64`, an infinity where it is past `f64`.
pub(crate) fn decimal(text: &[u8]) -> Option<f64> {
    // `f64::from_str` reads `inf`, `infinity` and `nan` too.
    let digits = |byte: &u8| matches!(byte, b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-');
    if !text.iter().all(digits) {
        return None;
    }
    std::str::from_utf8(text).ok()?.parse().ok()
}

/// Decimal text as a finite `f64`.
pub(crate) fn float(text: &[u8]) -> Option<f64> {
    decimal(text).filter(|value| value.is_finite())
}

#[cfg(test)]
mod tests;