| 1 |
// Copyright (c) 2021 DutchGhost |
| 2 |
// Copyright (c) 2021 matrixmultiply authors |
| 3 |
// |
| 4 |
// Incorporpated in matrixmultiply under these terms, see main license files. |
| 5 |
// |
| 6 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 8 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 9 |
// option. This file may not be copied, modified, or distributed |
| 10 |
// except according to those terms. |
| 11 |
|
| 12 |
#[derive(Clone, Copy)] |
| 13 |
pub(crate) enum ParseIntError { |
| 14 |
InvalidDigit, |
| 15 |
} |
| 16 |
|
| 17 |
const fn parse_byte(b: u8, pow10: usize) -> Result<usize, ParseIntError> { |
| 18 |
let r = b.wrapping_sub(48); |
| 19 |
|
| 20 |
if r > 9 { |
| 21 |
Err(ParseIntError::InvalidDigit) |
| 22 |
} else { |
| 23 |
Ok((r as usize) * pow10) |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
pub(crate) const POW10: [usize; 20] = { |
| 28 |
let mut array = [0; 20]; |
| 29 |
let mut pow10 = 1usize; |
| 30 |
|
| 31 |
let mut index = 20; |
| 32 |
|
| 33 |
loop { |
| 34 |
index -= 1; |
| 35 |
array[index] = pow10; |
| 36 |
|
| 37 |
if index == 0 { break } |
| 38 |
|
| 39 |
let (new_power, overflow) = pow10.overflowing_mul(10); |
| 40 |
pow10 = new_power; |
| 41 |
if overflow { break; } |
| 42 |
} |
| 43 |
|
| 44 |
array |
| 45 |
|
| 46 |
}; |
| 47 |
|
| 48 |
/// Parse the input to integer; or otherwise cause |
| 49 |
/// a const error, an "unwarp" in space and time. |
| 50 |
pub(crate) const fn parse_unwarp(b: &str) -> usize { |
| 51 |
match parse(b) { |
| 52 |
Ok(t) => t, |
| 53 |
res @ Err(_) => { |
| 54 |
[0, /* const error: failed to parse environment variable */][res.is_err() as usize] |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
/// Parse the input to usize |
| 60 |
pub(crate) const fn parse(b: &str) -> Result<usize, ParseIntError> { |
| 61 |
let bytes = b.as_bytes(); |
| 62 |
|
| 63 |
let mut result: usize = 0; |
| 64 |
|
| 65 |
let len = bytes.len(); |
| 66 |
|
| 67 |
// Start at the correct index of the table, |
| 68 |
// (skip the power's that are too large) |
| 69 |
let mut index_const_table = POW10.len().wrapping_sub(len); |
| 70 |
let mut index = 0; |
| 71 |
|
| 72 |
while index < b.len() { |
| 73 |
let a = bytes[index]; |
| 74 |
let p = POW10[index_const_table]; |
| 75 |
|
| 76 |
let r = match parse_byte(a, p) { |
| 77 |
Err(e) => return Err(e), |
| 78 |
Ok(d) => d, |
| 79 |
}; |
| 80 |
|
| 81 |
result = result.wrapping_add(r); |
| 82 |
|
| 83 |
index += 1; |
| 84 |
index_const_table += 1; |
| 85 |
} |
| 86 |
|
| 87 |
Ok(result) |
| 88 |
} |
| 89 |
|
| 90 |
#[test] |
| 91 |
fn test_parse() { |
| 92 |
for i in 0..500 { |
| 93 |
assert_eq!(parse_unwarp(&i.to_string()), i); |
| 94 |
} |
| 95 |
|
| 96 |
for bits in 0..std::mem::size_of::<usize>() * 8 { |
| 97 |
let i = (1 << bits) - 1; |
| 98 |
assert_eq!(parse_unwarp(&i.to_string()), i); |
| 99 |
} |
| 100 |
} |