grippo 0.2.4

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

use std::sync::LazyLock;

use proptest::prelude::*;
use regex::Regex;

use super::Number;
use crate::parse::{FieldValue, Hint};

fn read(text: &str, hint: Hint) -> Option<Number> {
    FieldValue::borrowed(text.as_bytes(), hint).number()
}

/// A `Float` hint's value as bits, so `-0.0` isn't taken for `0.0`.
fn float_bits(text: &str) -> Option<u64> {
    match read(text, Hint::Float)? {
        Number::Float(value) => Some(value.to_bits()),
        other => panic!("{text}: {other:?} under a Float hint"),
    }
}

/// Text that is no decimal number, under either hint.
const NOT_NUMBERS: &[&str] = &[
    "",
    "-",
    "+",
    ".",
    "e5",
    "1e",
    "1e+",
    "--1",
    "+-1",
    "1+2",
    "1 ",
    " 1",
    "1\n",
    "0x10",
    "1_000",
    "1,5",
    "NaN",
    "nan",
    "inf",
    "-inf",
    "infinity",
    "\u{661}\u{662}",
];

#[test]
fn an_int_hint_reads_whole_numbers() {
    let cases: &[(&str, Option<Number>)] = &[
        ("0", Some(Number::Int(0))),
        ("42", Some(Number::Int(42))),
        ("-7", Some(Number::Int(-7))),
        ("+5", Some(Number::Int(5))),
        ("07", Some(Number::Int(7))),
        ("000", Some(Number::Int(0))),
        ("-0", Some(Number::Int(0))),
        ("-9223372036854775808", Some(Number::Int(i64::MIN))),
        ("-9223372036854775809", None),
        ("9223372036854775807", Some(Number::Int(i64::MAX))),
        ("9223372036854775808", Some(Number::UInt(1 << 63))),
        ("18446744073709551615", Some(Number::UInt(u64::MAX))),
        ("18446744073709551616", None),
        (
            "000000000000000000000018446744073709551615",
            Some(Number::UInt(u64::MAX)),
        ),
        ("99999999999999999999999999999999999999999", None),
        ("9007199254740993", Some(Number::Int(9_007_199_254_740_993))),
        ("1.5", None),
        ("1.0", None),
        ("1e3", None),
        ("1E+3", None),
        (".5", None),
        ("5.", None),
    ];
    for (text, want) in cases {
        assert_eq!(read(text, Hint::Int), *want, "{text}");
    }
    for text in NOT_NUMBERS {
        assert_eq!(read(text, Hint::Int), None, "{text:?}");
    }
}

#[test]
fn a_float_hint_reads_any_decimal_as_a_float() {
    let cases: &[(&str, Option<f64>)] = &[
        ("0", Some(0.0)),
        ("42", Some(42.0)),
        ("-7", Some(-7.0)),
        ("+5", Some(5.0)),
        ("07", Some(7.0)),
        ("-0", Some(-0.0)),
        ("-0.0", Some(-0.0)),
        ("-0e5", Some(-0.0)),
        ("1.5", Some(1.5)),
        ("1.50", Some(1.5)),
        ("0.1", Some(0.1)),
        ("1e3", Some(1000.0)),
        ("1E+3", Some(1000.0)),
        ("1e01", Some(10.0)),
        ("-2.5E-3", Some(-0.0025)),
        (".5", Some(0.5)),
        ("5.", Some(5.0)),
        ("5.e2", Some(500.0)),
        ("9007199254740993", Some(9_007_199_254_740_992.0)),
        ("9007199254740993.0", Some(9_007_199_254_740_992.0)),
        ("18446744073709551616", Some(18_446_744_073_709_551_616.0)),
        ("-9223372036854775809", Some(-9_223_372_036_854_775_808.0)),
        ("1.7976931348623157e308", Some(f64::MAX)),
        ("1e-9999", Some(0.0)),
        ("-1e-9999", Some(-0.0)),
        ("1e309", None),
        ("-1e309", None),
        ("1e999999", None),
    ];
    for (text, want) in cases {
        assert_eq!(float_bits(text), want.map(f64::to_bits), "{text}");
    }
    for text in NOT_NUMBERS {
        assert_eq!(read(text, Hint::Float), None, "{text:?}");
    }
}

#[test]
fn only_a_numeric_hint_reads_a_number() {
    for hint in [
        Hint::Text,
        Hint::Bool,
        Hint::Ip,
        Hint::Timestamp,
        Hint::Json,
    ] {
        assert_eq!(read("42", hint), None, "{hint:?}");
    }
    for hint in [Hint::Int, Hint::Float] {
        let not_utf8 = FieldValue::borrowed(b"1\xff", hint);
        assert_eq!(not_utf8.number(), None, "{hint:?}");
    }
}

#[test]
fn reading_a_number_leaves_the_value_as_it_was() {
    let value = FieldValue::borrowed(b"007", Hint::Int);
    assert_eq!(value.number(), Some(Number::Int(7)));
    assert_eq!((&*value.bytes, value.hint), (&b"007"[..], Hint::Int));
}

static WHOLE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[+-]?[0-9]+$").unwrap());
static DECIMAL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?$").unwrap());

proptest! {
    #![proptest_config(ProptestConfig::with_cases(2_000))]

    #[test]
    fn every_i64_reads_back(n in any::<i64>()) {
        prop_assert_eq!(read(&n.to_string(), Hint::Int), Some(Number::Int(n)));
    }

    #[test]
    fn every_u64_reads_back(n in any::<u64>()) {
        let want = i64::try_from(n).map_or(Number::UInt(n), Number::Int);
        prop_assert_eq!(read(&n.to_string(), Hint::Int), Some(want));
    }

    #[test]
    fn every_finite_f64_reads_back(x in any::<f64>().prop_filter("finite", |x| x.is_finite())) {
        for text in [format!("{x}"), format!("{x:e}"), format!("{x:E}")] {
            prop_assert_eq!(float_bits(&text), Some(x.to_bits()), "{}", text);
        }
    }

    /// Text that looks like a number, and short text from the bytes one is made
    /// of with a few it isn't.
    #[test]
    fn text_reads_as_a_number_only_where_the_grammar_says(
        text in prop_oneof![
            "[-+]?[0-9]{0,6}\\.?[0-9]{0,4}([eE][-+]?[0-9]{0,3})?",
            "[-+.eE0-9 xnaif]{0,12}",
        ],
    ) {
        prop_assert_eq!(read(&text, Hint::Int).is_some(), WHOLE.is_match(&text), "{}", &text);
        let finite = text.parse::<f64>().is_ok_and(f64::is_finite);
        prop_assert_eq!(
            read(&text, Hint::Float).is_some(),
            DECIMAL.is_match(&text) && finite,
            "{}",
            &text
        );
    }

    #[test]
    fn any_bytes_read_without_a_panic(bytes in proptest::collection::vec(any::<u8>(), 0..40)) {
        for hint in [Hint::Int, Hint::Float] {
            if FieldValue::borrowed(&bytes, hint).number().is_some() {
                let text = std::str::from_utf8(&bytes);
                prop_assert!(text.is_ok_and(|text| DECIMAL.is_match(text)), "{:?}", bytes);
            }
        }
    }
}