Skip to content

Commit

Permalink
fix: error with leading zero after sign
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Oct 9, 2024
1 parent 0e31e94 commit f99ab25
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/parsers/integer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,15 @@ pub fn parse<R: Read, W: Writer>(
ExpectingState::DigitOrSign => {
if char.is_ascii_digit() {
writer.write_byte(byte)?;
first_digit_is_zero = true;

if char == '0' {
first_digit_is_zero = true;
}

ExpectingState::DigitOrEnd
} else if char == '-' {
writer.write_byte(byte)?;

ExpectingState::DigitAfterSign
} else {
return Err(Error::UnexpectedByteParsingInteger(byte, byte as char));
Expand All @@ -56,18 +61,24 @@ pub fn parse<R: Read, W: Writer>(
ExpectingState::DigitAfterSign => {
if char.is_ascii_digit() {
writer.write_byte(byte)?;

if char == '0' {
first_digit_is_zero = true;
}

ExpectingState::DigitOrEnd
} else {
return Err(Error::UnexpectedByteParsingInteger(byte, byte as char));
}
}
ExpectingState::DigitOrEnd => {
if char.is_ascii_digit() {
writer.write_byte(byte)?;

if char == '0' && first_digit_is_zero {
return Err(Error::LeadingZerosInIntegersNotAllowed);
}

writer.write_byte(byte)?;
ExpectingState::DigitOrEnd
} else if byte == BENCODE_END_INTEGER {
return Ok(());
Expand Down Expand Up @@ -178,4 +189,18 @@ mod tests {
Err(Error::LeadingZerosInIntegersNotAllowed)
));
}

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

let int_with_invalid_byte = b"i-00e";

let result = try_bencode_to_json(int_with_invalid_byte);

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

0 comments on commit f99ab25

Please sign in to comment.