From 2bce8cfc3f748c2adf46b2c62add9073a68a9585 Mon Sep 17 00:00:00 2001 From: RunasSudo Date: Fri, 19 Aug 2022 00:16:29 +1000 Subject: [PATCH] Avoid String allocations in BLT parser --- src/parser/blt.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/parser/blt.rs b/src/parser/blt.rs index 85a1cf0..e8a080a 100644 --- a/src/parser/blt.rs +++ b/src/parser/blt.rs @@ -191,10 +191,23 @@ impl> BLTParser { /// Parse an integer into a [usize] fn usize(&mut self) -> Result { - 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 { let mut result = String::from(self.digit_nonzero()?); loop { @@ -204,7 +217,7 @@ impl> BLTParser { } } return Ok(result); - } + }*/ /// Parse a number as an instance of N fn ballot_value(&mut self) -> Result<(), ParseError> {