Fix num parsing for invalid multi-byte sign chars

Ensure that splitting the potential sign character from the remainder
respects UTF8 boundaries. This lets invalid characters fail correctly
with an error, instead of panicking.
This commit is contained in:
Andreas Molzer 2019-08-30 22:27:32 +02:00
parent 58f02a8677
commit cd0da1ae5e
1 changed files with 15 additions and 1 deletions

View File

@ -216,7 +216,12 @@ macro_rules! float_trait_impl {
} }
fn slice_shift_char(src: &str) -> Option<(char, &str)> { fn slice_shift_char(src: &str) -> Option<(char, &str)> {
src.chars().nth(0).map(|ch| (ch, &src[1..])) let mut chars = src.chars();
if let Some(ch) = chars.next() {
Some((ch, chars.as_str()))
} else {
None
}
} }
let (is_positive, src) = match slice_shift_char(src) { let (is_positive, src) = match slice_shift_char(src) {
@ -395,6 +400,15 @@ fn from_str_radix_unwrap() {
assert_eq!(f, 0.0); assert_eq!(f, 0.0);
} }
#[test]
fn from_str_radix_multi_byte_fail() {
// Ensure parsing doesn't panic, even on invalid sign characters
assert!(f32::from_str_radix("™0.2", 10).is_err());
// Even when parsing the exponent sign
assert!(f32::from_str_radix("0.2E™1", 10).is_err());
}
#[test] #[test]
fn wrapping_is_num() { fn wrapping_is_num() {
fn require_num<T: Num>(_: &T) {} fn require_num<T: Num>(_: &T) {}