From cd877fe0ffe29875dfa887798d9150afa700eb59 Mon Sep 17 00:00:00 2001 From: Trevor Spiteri Date: Thu, 15 Apr 2021 20:15:46 +0200 Subject: [PATCH] Ignore case for float parsing of text special values This copies some of the standard library fixes of . --- src/lib.rs | 48 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index ca598f79..aa16770c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -210,6 +210,14 @@ impl fmt::Display for ParseFloatError { } } +fn str_to_ascii_lower_eq_str(a: &str, b: &str) -> bool { + a.len() == b.len() + && a.bytes().zip(b.bytes()).all(|(a, b)| { + let a_to_ascii_lower = a | (((b'A' <= a && a <= b'Z') as u8) << 5); + a_to_ascii_lower == b + }) +} + // FIXME: The standard library from_str_radix on floats was deprecated, so we're stuck // with this implementation ourselves until we want to make a breaking change. // (would have to drop it from `Num` though) @@ -232,12 +240,18 @@ macro_rules! float_trait_impl { } // Special values - match src { - "inf" => return Ok(core::$t::INFINITY), - "-inf" => return Ok(core::$t::NEG_INFINITY), - "NaN" => return Ok(core::$t::NAN), - "-NaN" => return Ok(-core::$t::NAN), - _ => {}, + if str_to_ascii_lower_eq_str(src, "inf") + || str_to_ascii_lower_eq_str(src, "infinity") + { + return Ok(core::$t::INFINITY); + } else if str_to_ascii_lower_eq_str(src, "-inf") + || str_to_ascii_lower_eq_str(src, "-infinity") + { + return Ok(core::$t::NEG_INFINITY); + } else if str_to_ascii_lower_eq_str(src, "nan") { + return Ok(core::$t::NAN); + } else if str_to_ascii_lower_eq_str(src, "-nan") { + return Ok(-core::$t::NAN); } fn slice_shift_char(src: &str) -> Option<(char, &str)> { @@ -516,6 +530,28 @@ fn from_str_radix_multi_byte_fail() { assert!(f32::from_str_radix("0.2E™1", 10).is_err()); } +#[test] +fn from_str_radix_ignore_case() { + assert_eq!( + f32::from_str_radix("InF", 16).unwrap(), + ::core::f32::INFINITY + ); + assert_eq!( + f32::from_str_radix("InfinitY", 16).unwrap(), + ::core::f32::INFINITY + ); + assert_eq!( + f32::from_str_radix("-InF", 8).unwrap(), + ::core::f32::NEG_INFINITY + ); + assert_eq!( + f32::from_str_radix("-InfinitY", 8).unwrap(), + ::core::f32::NEG_INFINITY + ); + assert!(f32::from_str_radix("nAn", 4).unwrap().is_nan()); + assert!(f32::from_str_radix("-nAn", 4).unwrap().is_nan()); +} + #[test] fn wrapping_is_num() { fn require_num(_: &T) {}