瀏覽代碼

bigint: fix parsing leading _ and test more

Josh Stone 7 年之前
父節點
當前提交
2a1fe6e7ef
共有 2 個文件被更改,包括 13 次插入0 次删除
  1. 7 0
      bigint/src/biguint.rs
  2. 6 0
      bigint/src/tests/biguint.rs

+ 7 - 0
bigint/src/biguint.rs

@@ -236,6 +236,13 @@ impl Num for BigUint {
             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
         let mut v = Vec::with_capacity(s.len());
         for b in s.bytes() {

+ 6 - 0
bigint/src/tests/biguint.rs

@@ -1541,6 +1541,8 @@ fn test_from_str_radix() {
     assert_eq!(zed, None);
     let blank = BigUint::from_str_radix("_", 2).ok();
     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();
     assert_eq!(plus_one, Some(BigUint::from_slice(&[1])));
     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);
     let zero_plus_two = BigUint::from_str_radix("0+2", 10).ok();
     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]