bigint: fix parsing leading _ and test more

This commit is contained in:
Josh Stone 2017-10-22 14:57:52 -07:00
parent 720893f67b
commit 2a1fe6e7ef
2 changed files with 13 additions and 0 deletions

View File

@ -236,6 +236,13 @@ impl Num for BigUint {
return Err(e.into()); return Err(e.into());
} }
if s.starts_with('_') {
// Must lead with a real digit!
// create ParseIntError::InvalidDigit
let e = u64::from_str_radix(s, radix).unwrap_err();
return Err(e.into());
}
// First normalize all characters to plain digit values // First normalize all characters to plain digit values
let mut v = Vec::with_capacity(s.len()); let mut v = Vec::with_capacity(s.len());
for b in s.bytes() { for b in s.bytes() {

View File

@ -1541,6 +1541,8 @@ fn test_from_str_radix() {
assert_eq!(zed, None); assert_eq!(zed, None);
let blank = BigUint::from_str_radix("_", 2).ok(); let blank = BigUint::from_str_radix("_", 2).ok();
assert_eq!(blank, None); assert_eq!(blank, None);
let blank_one = BigUint::from_str_radix("_1", 2).ok();
assert_eq!(blank_one, None);
let plus_one = BigUint::from_str_radix("+1", 10).ok(); let plus_one = BigUint::from_str_radix("+1", 10).ok();
assert_eq!(plus_one, Some(BigUint::from_slice(&[1]))); assert_eq!(plus_one, Some(BigUint::from_slice(&[1])));
let plus_plus_one = BigUint::from_str_radix("++1", 10).ok(); let plus_plus_one = BigUint::from_str_radix("++1", 10).ok();
@ -1549,6 +1551,10 @@ fn test_from_str_radix() {
assert_eq!(minus_one, None); assert_eq!(minus_one, None);
let zero_plus_two = BigUint::from_str_radix("0+2", 10).ok(); let zero_plus_two = BigUint::from_str_radix("0+2", 10).ok();
assert_eq!(zero_plus_two, None); assert_eq!(zero_plus_two, None);
let three = BigUint::from_str_radix("1_1", 2).ok();
assert_eq!(three, Some(BigUint::from_slice(&[3])));
let ff = BigUint::from_str_radix("1111_1111", 2).ok();
assert_eq!(ff, Some(BigUint::from_slice(&[0xff])));
} }
#[test] #[test]