Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow "infinity" and ignore case when parsing floats. #48886

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions src/libcore/num/dec2flt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -215,10 +216,17 @@ fn dec2flt<T: RawFloat>(s: &str) -> Result<T, ParseFloatError> {
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()); }
}
}
};

Expand Down
14 changes: 11 additions & 3 deletions src/libcore/tests/num/dec2flt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,23 @@ fn whitespace() {
#[test]
fn nan() {
assert!("NaN".parse::<f32>().unwrap().is_nan());
assert!("NAN".parse::<f32>().unwrap().is_nan());
assert!("nan".parse::<f32>().unwrap().is_nan());
assert!("NaN".parse::<f64>().unwrap().is_nan());
assert!("NAN".parse::<f64>().unwrap().is_nan());
assert!("nan".parse::<f64>().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]
Expand Down