126: Fix num parsing for invalid multi-byte sign chars r=cuviper a=HeroicKatora

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.

Closes: #125 

Co-authored-by: Andreas Molzer <andreas.molzer@gmx.de>
This commit is contained in:
bors[bot] 2019-08-30 21:26:40 +00:00 committed by GitHub
commit 45067c1357
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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) {}