Skip to content

Commit

Permalink
refactor: simplify string parser for length
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Oct 8, 2024
1 parent 6407dda commit 1640f41
Showing 1 changed file with 4 additions and 31 deletions.
35 changes: 4 additions & 31 deletions src/parsers/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,28 +71,11 @@ impl Length {

self.bytes.push(byte);

Ok(())
}
let digit = (byte - b'0') as usize;

/// This function convert the current bytes representing the length to a
/// number.
///
/// # Panics
///
/// Will panic if the length bytes contain invalid UTF-8 chars or don't
/// represent a valid zero or positive integer.
fn convert_to_number(&mut self) -> usize {
// todo: maybe we should simply fail when we receive a byte that is not a digit (0..9).
// This error cannot be understood by users because we first convert into a UTF-8 string
// and later into a number.
let length_str =
str::from_utf8(&self.bytes).expect("invalid string length, non UTF-8 string length");

self.number = length_str
.parse::<usize>()
.expect("invalid string length, non zero or positive integer");

self.number
self.number = (self.number * 10) + digit;

Ok(())
}
}

Expand Down Expand Up @@ -149,8 +132,6 @@ impl StringParser {
reader: &mut ByteReader<R>,
initial_byte: u8,
) -> Result<(), Error> {
// code-review: length can be calculated on the fly as the original C implementation.

self.length.add_byte(initial_byte)?;

loop {
Expand All @@ -170,8 +151,6 @@ impl StringParser {
match byte {
b':' => {
// End of string length
self.process_end_of_string_length();
self.length.convert_to_number();
break;
}
_ => {
Expand Down Expand Up @@ -206,12 +185,6 @@ impl StringParser {
Ok(())
}

/// This function is called when we receive the ':' byte which is the
/// delimiter for the end of bytes representing the string length.
fn process_end_of_string_length(&mut self) -> usize {
self.length.convert_to_number()
}

fn utf8(&self) -> String {
self.value.utf8()
}
Expand Down

0 comments on commit 1640f41

Please sign in to comment.