Skip to content

Commit

Permalink
Merge pull request #144 from untitaker/invalid-bytes-not-length
Browse files Browse the repository at this point in the history
Give better error messages when decoding data with trailing newlines
  • Loading branch information
marshallpierce authored Sep 30, 2020
2 parents 5b40e0c + 27ccb65 commit 6bb3556
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
22 changes: 21 additions & 1 deletion src/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,17 @@ fn decode_helper(
// and the fast decode logic cannot handle padding
0 => INPUT_CHUNK_LEN,
// 1 and 5 trailing bytes are illegal: can't decode 6 bits of input into a byte
1 | 5 => return Err(DecodeError::InvalidLength),
1 | 5 => {
// trailing whitespace is so common that it's worth it to check the last byte to
// possibly return a better error message
if let Some(b) = input.last() {
if *b != b'=' && decode_table[*b as usize] == tables::INVALID_VALUE {
return Err(DecodeError::InvalidByte(input.len() - 1, *b));
}
}

return Err(DecodeError::InvalidLength);
}
// This will decode to one output byte, which isn't enough to overwrite the 2 extra bytes
// written by the fast decode loop. So, we have to ignore both these 2 bytes and the
// previous chunk.
Expand Down Expand Up @@ -865,4 +875,14 @@ mod tests {
decode_config(b"+//+", crate::STANDARD_NO_PAD)
);
}

#[test]
fn decode_invalid_trailing_bytes() {
// The case of trailing newlines is common enough to warrant a test for a good error
// message.
assert_eq!(
decode(b"Zm9vCg==\n"),
Err(DecodeError::InvalidByte(8, b'\n'))
);
}
}
2 changes: 1 addition & 1 deletion tests/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ fn decode_reject_invalid_bytes_with_correct_error() {
index
);

if length % 4 == 1 {
if length % 4 == 1 && !suffix.is_empty() {
assert_eq!(DecodeError::InvalidLength, decode(&input).unwrap_err());
} else {
assert_eq!(
Expand Down

0 comments on commit 6bb3556

Please sign in to comment.