Skip to content

Commit

Permalink
error for leading zeros in integers
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Oct 9, 2024
1 parent 4524aae commit 65c256f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ printf "3:ab" | cargo run
Error: Unexpected end of input parsing string value
```

```console
echo "i00e" | cargo run
Error: Leading zeros in integers are not allowed, for example b'i00e'
```

## Library

todo
Expand Down
3 changes: 3 additions & 0 deletions src/parsers/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ pub enum Error {
#[error("Unexpected end of input parsing integer")]
UnexpectedEndOfInputParsingInteger,

#[error("Leading zeros in integers are not allowed, for example b'i00e'")]
LeadingZerosInIntegersNotAllowed,

// Strings
#[error("Invalid string length byte, expected a digit, received byte: {0}, char: {1}")]
InvalidStringLengthByte(u8, char),
Expand Down
20 changes: 20 additions & 0 deletions src/parsers/integer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ pub fn parse<R: Read, W: Writer>(
_initial_byte: u8,
) -> Result<(), Error> {
let mut state = StateExpecting::DigitOrSign;
let mut first_digit_is_zero = false;

loop {
let byte = next_byte(reader)?;
Expand All @@ -43,6 +44,7 @@ pub fn parse<R: Read, W: Writer>(
StateExpecting::DigitOrSign => {
if char.is_ascii_digit() {
writer.write_byte(byte)?;
first_digit_is_zero = true;
StateExpecting::DigitOrEnd
} else if char == '-' {
writer.write_byte(byte)?;
Expand All @@ -61,6 +63,10 @@ pub fn parse<R: Read, W: Writer>(
}
StateExpecting::DigitOrEnd => {
if char.is_ascii_digit() {
if char == '0' && first_digit_is_zero {
return Err(Error::LeadingZerosInIntegersNotAllowed);
}

writer.write_byte(byte)?;
StateExpecting::DigitOrEnd
} else if byte == BENCODE_END_INTEGER {
Expand Down Expand Up @@ -158,4 +164,18 @@ mod tests {
Err(Error::UnexpectedByteParsingInteger(97, 'a'))
));
}

#[test]
fn it_should_fail_when_it_finds_leading_zeros() {
// Leading zeros are not allowed.Only the zero integer can start with zero.

let int_with_invalid_byte = b"i00e";

let result = try_bencode_to_json(int_with_invalid_byte);

assert!(matches!(
result,
Err(Error::LeadingZerosInIntegersNotAllowed)
));
}
}

0 comments on commit 65c256f

Please sign in to comment.