grippo 0.1.2

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/convert.rs
// Purpose:   Field text converted to a typed integer, float, boolean or IP address
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Field text converted to a typed value: an integer, a float at single or
//! double precision, a boolean or an IP address.
//!
//! Integers read `0x` hex or decimal, never octal, so a port written `0080`
//! is 80. Nothing allocates.

use std::fmt::Write as _;
use std::net::IpAddr;
use std::num::IntErrorKind;

use thiserror::Error;

/// Why text didn't convert.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ConvertError {
    /// The text isn't a whole number in the form read.
    #[error("not an integer")]
    NotInteger,
    /// A whole number, or a float truncated to one, outside `i64`.
    #[error("outside the 64-bit integer range")]
    OutOfRange,
    /// The text isn't a decimal number.
    #[error("not a number")]
    NotFloat,
    /// The text isn't `true` or `false`.
    #[error("not true or false")]
    NotBoolean,
    /// The text isn't an IPv4 or IPv6 address.
    #[error("not an IP address")]
    NotIp,
}

/// The precision a float is held at.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Width {
    /// 32-bit: the value keeps the digits an `f32` holds.
    Single,
    /// 64-bit: the value as `f64` reads it.
    Double,
}

/// An IP address and the trimmed text it was read from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IpText<'a> {
    /// The text with surrounding whitespace removed, as written.
    pub text: &'a str,
    /// The address.
    pub addr: IpAddr,
}

/// `text` as an `i64`.
///
/// Whitespace around the number is dropped. A `0x` prefix reads the rest as
/// hex digits in either case, with no sign. Anything else is an optional `+`
/// or `-` and decimal digits, leading zeros included, so `010` is 10.
///
/// # Errors
///
/// [`ConvertError::OutOfRange`] for a number past `i64`, and
/// [`ConvertError::NotInteger`] for anything else that isn't that form.
pub fn parse_int(text: &str) -> Result<i64, ConvertError> {
    let text = text.trim();
    let read = match text.strip_prefix("0x") {
        // from_str_radix takes a sign, which can't follow the prefix.
        Some(hex) if hex.starts_with(['+', '-']) => return Err(ConvertError::NotInteger),
        Some(hex) => i64::from_str_radix(hex, 16),
        None => text.parse::<i64>(),
    };
    read.map_err(|error| match error.kind() {
        IntErrorKind::PosOverflow | IntErrorKind::NegOverflow => ConvertError::OutOfRange,
        _ => ConvertError::NotInteger,
    })
}

/// `text` as a float at `width`, widened to `f64`.
///
/// Whitespace around the number is dropped, and the rest is read as
/// `str::parse` reads a float, so `1e3`, `.5`, `inf` and `NaN` are numbers.
/// [`Width::Single`] rounds the text to an `f32` once, then widens it as
/// [`narrow`] does.
///
/// # Errors
///
/// [`ConvertError::NotFloat`] when the text isn't a number.
pub fn parse_float(text: &str, width: Width) -> Result<f64, ConvertError> {
    let text = text.trim();
    match width {
        Width::Double => text.parse::<f64>().map_err(|_| ConvertError::NotFloat),
        Width::Single => text
            .parse::<f32>()
            .map(widen)
            .map_err(|_| ConvertError::NotFloat),
    }
}

/// `value` held at `width`.
///
/// [`Width::Single`] gives the `f64` nearest the shortest decimal that names
/// the `f32` nearest `value`, so `0.1` stays `0.1` where widening the `f32`
/// bits gives `0.10000000149011612`.
#[must_use]
pub fn narrow(value: f64, width: Width) -> f64 {
    match width {
        Width::Double => value,
        #[allow(
            clippy::cast_possible_truncation,
            reason = "rounding to f32 is the point"
        )]
        Width::Single => widen(value as f32),
    }
}

/// `text` as a boolean: `true` or `false` in any ASCII case.
///
/// Whitespace isn't dropped, so ` true` is not a boolean.
///
/// # Errors
///
/// [`ConvertError::NotBoolean`] for any other text.
pub const fn parse_bool(text: &str) -> Result<bool, ConvertError> {
    if text.eq_ignore_ascii_case("true") {
        Ok(true)
    } else if text.eq_ignore_ascii_case("false") {
        Ok(false)
    } else {
        Err(ConvertError::NotBoolean)
    }
}

/// `text` as an IP address, with the trimmed text it was read from.
///
/// Whitespace around the address is dropped. The rest is read as
/// `str::parse` reads an [`IpAddr`]: dotted IPv4 with no leading zeros, or
/// IPv6 with no zone.
///
/// # Errors
///
/// [`ConvertError::NotIp`] when the text isn't an address.
pub fn parse_ip(text: &str) -> Result<IpText<'_>, ConvertError> {
    let text = text.trim();
    let addr: IpAddr = text.parse().map_err(|_| ConvertError::NotIp)?;
    Ok(IpText { text, addr })
}

/// `value` truncated toward zero to an `i64`.
///
/// # Errors
///
/// [`ConvertError::OutOfRange`] for a value outside `i64`, an infinity
/// included, where a cast would clamp to the bound, and
/// [`ConvertError::NotInteger`] for `NaN`.
pub fn truncate(value: f64) -> Result<i64, ConvertError> {
    // 2^63: i64::MIN is -2^63 exactly, and every f64 below 2^63 truncates into range.
    const BOUND: f64 = 9_223_372_036_854_775_808.0;
    if value.is_nan() {
        return Err(ConvertError::NotInteger);
    }
    if !(-BOUND..BOUND).contains(&value) {
        return Err(ConvertError::OutOfRange);
    }
    #[allow(clippy::cast_possible_truncation, reason = "range checked above")]
    Ok(value as i64)
}

/// An `f32` widened through its shortest decimal.
fn widen(single: f32) -> f64 {
    // A whole number under 2^24 is its own shortest decimal.
    const EXACT: f32 = 16_777_216.0;
    if !single.is_finite() || (single.abs() < EXACT && single.fract() == 0.0) {
        return f64::from(single);
    }
    let mut digits = Digits::default();
    if write!(digits, "{single:e}").is_err() {
        return f64::from(single);
    }
    std::str::from_utf8(digits.as_bytes())
        .ok()
        .and_then(|text| text.parse::<f64>().ok())
        .unwrap_or_else(|| f64::from(single))
}

/// A stack buffer for one `f32` written in exponent form, at most 15 bytes.
#[derive(Default)]
struct Digits {
    bytes: [u8; 32],
    len: usize,
}

impl Digits {
    fn as_bytes(&self) -> &[u8] {
        self.bytes.get(..self.len).unwrap_or_default()
    }
}

impl std::fmt::Write for Digits {
    fn write_str(&mut self, text: &str) -> std::fmt::Result {
        let end = self.len + text.len();
        let slot = self.bytes.get_mut(self.len..end).ok_or(std::fmt::Error)?;
        slot.copy_from_slice(text.as_bytes());
        self.len = end;
        Ok(())
    }
}

#[cfg(test)]
mod tests;