Skip to content

Instantly share code, notes, and snippets.

@DutchGhost
Last active November 19, 2021 19:30
Show Gist options
  • Save DutchGhost/d8604a3c796479777fe9f5e25d855cfd to your computer and use it in GitHub Desktop.
Save DutchGhost/d8604a3c796479777fe9f5e25d855cfd to your computer and use it in GitHub Desktop.
Const parsing of &str -> usize in Rust
MIT License
Copyright (c) 2021 DutchGhost
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#[derive(Clone, Copy, Debug)]
enum ParseIntError {
InvalidDigit,
}
const fn parse_byte(b: u8, pow10: usize) -> Result<usize, ParseIntError> {
let r = b.wrapping_sub(48);
if r > 9 {
Err(ParseIntError::InvalidDigit)
} else {
Ok((r as usize) * pow10)
}
}
pub(crate) const POW10: [usize; 20] = {
let mut array = [0; 20];
let mut current = 1;
let mut index = 20;
loop {
index -= 1;
array[index] = current;
if index == 0 { break }
current *= 10;
}
array
};
const fn parse(b: &str) -> Result<usize, ParseIntError> {
let bytes = b.as_bytes();
let mut result: usize = 0;
let len = bytes.len();
// Start at the correct index of the table,
// (skip the power's that are too large)
let mut index_const_table = POW10.len().wrapping_sub(len);
let mut index = 0;
while index < b.len() {
let a = bytes[index];
let p = POW10[index_const_table];
let r = match parse_byte(a, p) {
Err(e) => return Err(e),
Ok(d) => d,
};
result = result.wrapping_add(r);
index += 1;
index_const_table += 1;
}
Ok(result)
}
const fn unwarp(opt: Result<usize, ParseIntError>) -> usize {
match opt {
Ok(t) => t,
_ => loop {}
}
}
fn main() {
const P: usize = unwarp(parse("9999912"));
println!("{:?}", P);
}
@bluss
Copy link

bluss commented Nov 19, 2021

Thank you again! I did these changes to use this in 32-bit, which I donate to use under the same license as stated here (they are trivial anyway), for simplicity, if necessary. https://github.com/bluss/matrixmultiply/pull/64/files I guess it could be made more optimal for 32-bit but didn't need to look into it.

@DutchGhost
Copy link
Author

DutchGhost commented Nov 19, 2021

Thank you again! I did these changes to use this in 32-bit, which I donate to use under the same license as stated here (they are trivial anyway), for simplicity, if necessary. https://github.com/bluss/matrixmultiply/pull/64/files I guess it could be made more optimal for 32-bit but didn't need to look into it.

Thanks! Happy this code is usefull.
As for performance, perhaps something could be made faster. The algorithm used is invented by Andrei Alexandrescu, in one of his fastware talks.

https://youtu.be/o4-CwDo2zpg (on 00:40:00)

@bluss
Copy link

bluss commented Nov 19, 2021

I like those talks. For now, parsing at compile time feels free, performance cost is 0 at runtime, which is the best part, and for my use case I'm at most parsing usize 12 times, which I assume has a negligible cost.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment