Generic, JavaScript-style parseInt() and parseFloat() functions for Rust.
This crate is intended to provide a fast and generic parseInt()- and parseFloat()-like implementation for Rust, which mostly follows the specification described in the MDN documentation for parseInt() and parseFloat().
parse_int() and parse_uint() are generic interfaces to parse integers from strings or character-emitting iterators. Whitespace in front of the parsed number is being ignored, same as anything beyond a valid number.
assert_eq!(parse_uint::<i32>("+123 as i32 "), Some(123i32));
assert_eq!(parse_int::<i32>(" -123 as i32 "), Some(-123i32));
assert_eq!(parse_uint::<i64>("+123 as i64 "), Some(123i64));
assert_eq!(parse_int::<i64>(" -123 as i64 "), Some(-123i64));
assert_eq!(parse_int::<i64>(" - 1 is invalid "), None);
assert_eq!(
parse_uint::<u64>(" -123 as u64, parse_int() not available for this type "),
None
);
assert_eq!(
parse_uint::<usize>(" 0xcafebabe triggers hex-mode parsing "),
Some(0xCAFEBABE)
);parse_float() and parse_ufloat() are generic interfaces to parse floating point numbers from strings or character-emitting iterators. Whitespace in front of the parsed number is being ignored, same as anything beyond a valid number.
assert_eq!(parse_ufloat::<f32>("+123.45 as f32 "), Some(123.45f32));
assert_eq!(parse_float::<f32>(" -123.45 as f32 "), Some(-123.45f32));
assert_eq!(parse_ufloat::<f64>("+123.45 as f64 "), Some(123.45f64));
assert_eq!(parse_float::<f64>(" -123.45 as f64 "), Some(-123.45f64));
assert_eq!(parse_ufloat::<f32>("0"), Some(0f32));
assert_eq!(parse_float::<f64>(" 123 as f64 "), Some(123f64));
assert_eq!(parse_float::<f64>(" - 1.0 is invalid "), None);
assert_eq!(
parse_ufloat::<f64>(" -123.45 as f64, parse_float() not available for this value "),
None
);This crate is required by and implemented together with the Tokay programming language to parse and calculate numerical values from a PeekableIterator-trait, which is also defined here. A JavaScript-like numerical parsing was thought to be useful for other projects as well.