Avoid String allocations in BLT parser

This commit is contained in:
RunasSudo 2022-08-19 00:16:29 +10:00
parent 35104055d9
commit 2bce8cfc3f
Signed by: RunasSudo
GPG Key ID: 7234E476BF21C61A
1 changed files with 16 additions and 3 deletions

View File

@ -191,10 +191,23 @@ impl<N: Number, I: Iterator<Item=char>> BLTParser<N, I> {
/// Parse an integer into a [usize]
fn usize(&mut self) -> Result<usize, ParseError> {
return Ok(self.integer()?.parse().expect("Invalid usize"));
// return Ok(self.integer()?.parse().expect("Invalid usize"));
// Use a separate implementation to avoid allocating String
let mut result = self.digit_nonzero()?.to_digit(10).unwrap() as usize;
loop {
match self.digit() {
Err(_) => { break; }
Ok(d) => {
result = result.checked_mul(10).expect("Integer overflows usize");
result = result.checked_add(d.to_digit(10).unwrap() as usize).expect("Integer overflows usize");
}
}
}
return Ok(result);
}
/// Parse an integer as a [String]
/*/// Parse an integer as a [String]
fn integer(&mut self) -> Result<String, ParseError> {
let mut result = String::from(self.digit_nonzero()?);
loop {
@ -204,7 +217,7 @@ impl<N: Number, I: Iterator<Item=char>> BLTParser<N, I> {
}
}
return Ok(result);
}
}*/
/// Parse a number as an instance of N
fn ballot_value(&mut self) -> Result<(), ParseError> {