grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/parse/number.rs
// Purpose:   A numeric field's text as a typed number
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A numeric field's text as a typed number.
//!
//! Parsers keep a number as the text the record held and hint it `Int` or
//! `Float`. [`FieldValue::number`] is the one place that text becomes a
//! value, so every sink that stores typed columns reads `07`, `-0` and a
//! 20-digit integer the same way.

use super::{FieldValue, Hint};

/// A numeric field's value, read 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 under a `Float` hint, rounded to the nearest `f64`.
    Float(f64),
}

impl FieldValue<'_> {
    /// The value as a number, or `None` to keep the text.
    ///
    /// The hint says whole or float, never the spelling, so `3` and `3.5`
    /// under one hint don't make one field two kinds:
    ///
    /// - [`Hint::Int`]: a sign and digits. `Int` when it fits `i64`, `UInt`
    ///   past that when it fits `u64`, `None` beyond either end.
    /// - [`Hint::Float`]: digits with an optional point and exponent, as
    ///   `Float`. `None` when it rounds to an infinity.
    /// - Any other hint: `None`, whatever the text looks like.
    ///
    /// A leading `+` and leading zeros are read. Spaces, `inf`, `nan` and
    /// hex are not. `None` never means a bad record: the bytes are
    /// untouched, and a store that must be exact keeps them.
    #[must_use]
    pub fn number(&self) -> Option<Number> {
        match self.hint {
            Hint::Int => whole(&self.bytes),
            Hint::Float => float(&self.bytes),
            _ => None,
        }
    }
}

/// A sign and digits, as the widest of `Int` and `UInt` that holds them.
fn whole(text: &[u8]) -> Option<Number> {
    let (negative, digits) = match text.split_first()? {
        (b'-', rest) => (true, rest),
        (b'+', rest) => (false, rest),
        _ => (false, text),
    };
    if digits.is_empty() {
        return None;
    }
    let mut value: u64 = 0;
    for &byte in digits {
        let digit = byte.wrapping_sub(b'0');
        if digit > 9 {
            return None;
        }
        value = value.checked_mul(10)?.checked_add(u64::from(digit))?;
    }
    if negative {
        0_i64.checked_sub_unsigned(value).map(Number::Int)
    } else {
        Some(i64::try_from(value).map_or(Number::UInt(value), Number::Int))
    }
}

/// Decimal text as a finite `Float`.
fn float(text: &[u8]) -> Option<Number> {
    // `f64::from_str` reads `inf`, `infinity` and `nan` too.
    let decimal = |byte: &u8| matches!(byte, b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-');
    if !text.iter().all(decimal) {
        return None;
    }
    let value: f64 = std::str::from_utf8(text).ok()?.parse().ok()?;
    value.is_finite().then_some(Number::Float(value))
}

#[cfg(test)]
mod tests;