From c5bae99685cd3667300cee227c524b13a266b6af Mon Sep 17 00:00:00 2001 From: Marc de Jonge Date: Fri, 31 Jan 2025 08:40:02 +0100 Subject: [PATCH] Improve the floating point implementation to not depend on the ParseTo trait --- Cargo.toml | 2 +- src/lib.rs | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2761634..499d6b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "nom-parse-trait" description = "Adding traits to make parsing types easier" -version = "0.3.1" +version = "0.3.2" license = "MIT/Apache-2.0" keywords = ["nom", "parser", "parsable"] categories = ["parsing"] diff --git a/src/lib.rs b/src/lib.rs index 232c271..a9b19d4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -108,24 +108,32 @@ macro_rules! signed_parsable { signed_parsable!(i8 i16 i32 i64 i128); macro_rules! floating_parsable { - ($($ty:ty => $fn:tt),+) => { + ($($ty:tt)+) => { $( impl> ParseFrom for $ty where - I: Input + Offset + AsBytes + ParseTo<$ty> + Compare<&'static str>, + I: Input + Offset + AsBytes + Compare<&'static str>, ::Item: AsChar, ::Iter: Clone, I: for<'a> Compare<&'a [u8]>, { fn parse(input: I) -> nom::IResult { - nom::number::complete::$fn(input) + use std::str::FromStr; + use nom::number::complete::recognize_float_or_exceptions; + use std::str::from_utf8; + + let (i, s) = recognize_float_or_exceptions(input)?; + match from_utf8(s.as_bytes()).ok().and_then(|s| $ty::from_str(s).ok()) { + Some(f) => Ok((i, f)), + None => Err(nom::Err::Error(E::from_error_kind(i, nom::error::ErrorKind::Float))), + } } } )* } } -floating_parsable!(f32 => float, f64 => double); +floating_parsable!(f32 f64); /// Support reading the words "true" or "false" from the input and interpreting them as boolean values. impl> ParseFrom for bool