From 0f85c34a26bab92e6ba7cf3380b8d5b278254103 Mon Sep 17 00:00:00 2001 From: Clar Charr Date: Fri, 9 Mar 2018 13:44:35 -0500 Subject: [PATCH] Allow "infinity" and ignore case when parsing floats. --- src/libcore/num/dec2flt/mod.rs | 18 +++++++++++++----- src/libcore/tests/num/dec2flt/mod.rs | 14 +++++++++++--- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/libcore/num/dec2flt/mod.rs b/src/libcore/num/dec2flt/mod.rs index f93564c2849f5..be34541841fe7 100644 --- a/src/libcore/num/dec2flt/mod.rs +++ b/src/libcore/num/dec2flt/mod.rs @@ -123,7 +123,8 @@ macro_rules! from_str_float_impl { /// * '2.5E-10' /// * '5.' /// * '.5', or, equivalently, '0.5' - /// * 'inf', '-inf', 'NaN' + /// * 'inf', `-inf`, or equivalently 'infinity', `-infinity` (case-insensitive) + /// * 'NaN' (case-insensitive) /// /// Leading and trailing whitespace represent an error. /// @@ -215,10 +216,17 @@ fn dec2flt(s: &str) -> Result { ParseResult::Valid(decimal) => convert(decimal)?, ParseResult::ShortcutToInf => T::INFINITY, ParseResult::ShortcutToZero => T::ZERO, - ParseResult::Invalid => match s { - "inf" => T::INFINITY, - "NaN" => T::NAN, - _ => { return Err(pfe_invalid()); } + ParseResult::Invalid => { + let buf = [0; 8] + .get_mut(..s.len()) + .ok_or_else(pfe_invalid)?; + buf.copy_from_slice(s.as_bytes()); + buf.make_ascii_uppercase(); + match &*buf { + b"INFINITY" | b"INF" => T::INFINITY, + b"NAN" => T::NAN, + _ => { return Err(pfe_invalid()); } + } } }; diff --git a/src/libcore/tests/num/dec2flt/mod.rs b/src/libcore/tests/num/dec2flt/mod.rs index 17b2f59cd4df2..2e75cbafdc8b8 100644 --- a/src/libcore/tests/num/dec2flt/mod.rs +++ b/src/libcore/tests/num/dec2flt/mod.rs @@ -122,15 +122,23 @@ fn whitespace() { #[test] fn nan() { assert!("NaN".parse::().unwrap().is_nan()); + assert!("NAN".parse::().unwrap().is_nan()); + assert!("nan".parse::().unwrap().is_nan()); assert!("NaN".parse::().unwrap().is_nan()); + assert!("NAN".parse::().unwrap().is_nan()); + assert!("nan".parse::().unwrap().is_nan()); } #[test] fn inf() { - assert_eq!("inf".parse(), Ok(f64::INFINITY)); - assert_eq!("-inf".parse(), Ok(f64::NEG_INFINITY)); - assert_eq!("inf".parse(), Ok(f32::INFINITY)); + assert_eq!("INF".parse(), Ok(f32::INFINITY)); assert_eq!("-inf".parse(), Ok(f32::NEG_INFINITY)); + assert_eq!("INFINITy".parse(), Ok(f32::INFINITY)); + assert_eq!("-infinitY".parse(), Ok(f32::NEG_INFINITY)); + assert_eq!("INF".parse(), Ok(f64::INFINITY)); + assert_eq!("-inf".parse(), Ok(f64::NEG_INFINITY)); + assert_eq!("INFINITy".parse(), Ok(f64::INFINITY)); + assert_eq!("-infinitY".parse(), Ok(f64::NEG_INFINITY)); } #[test]