grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/convert/java.rs
// Purpose:   Field text converted as Elasticsearch's convert processor reads it in Java
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The readings of Elasticsearch's `convert` processor.
//!
//! It calls Java's `Long.parseLong`, `Long.decode`, `Double.parseDouble`,
//! `Float.parseFloat` and its own IP check. Only ASCII digits are read, where
//! Java takes any Unicode decimal digit, and a hex float such as `0x1p3` is
//! refused.

use std::net::IpAddr;
use std::num::{IntErrorKind, ParseIntError};

use super::{ConvertError, IpText, Width, widen};

/// `text` as an `i64`, as `Long.decode` reads text starting `0x` or `-0x`
/// and `Long.parseLong` reads the rest.
///
/// Nothing is trimmed, so ` 443 ` is refused. `-0x1F` is -31, and `0X1F`,
/// `+0x1F` and `0x-1F` are refused. A leading `0` is decimal, so `010` is
/// 10. A JSON number with a fraction or exponent reaches here as its text,
/// such as `1.9` or `-9.223372036854776E18`, and is refused, as Elasticsearch
/// refuses it.
///
/// # 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 (negative, hex) = match (text.strip_prefix("0x"), text.strip_prefix("-0x")) {
        (Some(hex), _) => (false, hex),
        (_, Some(hex)) => (true, hex),
        _ => return text.parse::<i64>().map_err(|e| int_error(&e)),
    };
    if hex.starts_with(['+', '-']) {
        return Err(ConvertError::NotInteger);
    }
    let magnitude = u64::from_str_radix(hex, 16).map_err(|e| int_error(&e))?;
    if negative {
        0_i64.checked_sub_unsigned(magnitude)
    } else {
        i64::try_from(magnitude).ok()
    }
    .ok_or(ConvertError::OutOfRange)
}

const fn int_error(error: &ParseIntError) -> ConvertError {
    match error.kind() {
        IntErrorKind::PosOverflow | IntErrorKind::NegOverflow => ConvertError::OutOfRange,
        _ => ConvertError::NotInteger,
    }
}

/// `text` as a float at `width`, widened to `f64`, as `Double.parseDouble`
/// and `Float.parseFloat` read it.
///
/// Characters up to U+0020 are trimmed from both ends, as Java's
/// `String.trim` does, so a no-break space stays. `NaN` and `Infinity` are
/// read in that case only, with an optional sign, so `inf` and `nan` are
/// refused. A decimal may end in one `f`, `F`, `d` or `D`.
///
/// # 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_matches(|c: char| c <= ' ');
    let body = text.strip_prefix(['+', '-']).unwrap_or(text);
    let infinity = if text.starts_with('-') {
        f64::NEG_INFINITY
    } else {
        f64::INFINITY
    };
    match body {
        "NaN" => Ok(f64::NAN),
        "Infinity" => Ok(infinity),
        _ if body.starts_with(|c: char| c.is_ascii_alphabetic()) => Err(ConvertError::NotFloat),
        _ => {
            let number = text.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(text);
            match width {
                Width::Double => number.parse::<f64>(),
                Width::Single => number.parse::<f32>().map(widen),
            }
            .map_err(|_| ConvertError::NotFloat)
        }
    }
}

/// `text` as an IP address, as Elasticsearch's `InetAddresses` reads it.
///
/// Nothing is trimmed. An IPv6 address may carry a zone after `%`, such as
/// `fe80::1%eth0`, which [`IpText::text`] keeps and [`IpText::addr`] leaves
/// out. An IPv4 address with a zone is refused.
///
/// # Errors
///
/// [`ConvertError::NotIp`] when the text isn't an address.
pub fn parse_ip(text: &str) -> Result<IpText<'_>, ConvertError> {
    let address = match text.split_once('%') {
        Some((address, zone)) if address.contains(':') && !zone.is_empty() => address,
        Some(_) => return Err(ConvertError::NotIp),
        None => text,
    };
    let addr: IpAddr = address.parse().map_err(|_| ConvertError::NotIp)?;
    Ok(IpText { text, addr })
}