Skip to content

Commit d15cd38

Browse files
committed
Give better error messages when decoding data with trailing newlines
1 parent 2dc0296 commit d15cd38

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

src/decode.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,17 @@ fn decode_helper(
212212
// and the fast decode logic cannot handle padding
213213
0 => INPUT_CHUNK_LEN,
214214
// 1 and 5 trailing bytes are illegal: can't decode 6 bits of input into a byte
215-
1 | 5 => return Err(DecodeError::InvalidLength),
215+
1 | 5 => {
216+
// trailing whitespace is so common that it's worth it to check the last byte to
217+
// possibly return a better error message
218+
if let Some(b) = input.last() {
219+
if decode_table[*b as usize] == tables::INVALID_VALUE {
220+
return Err(DecodeError::InvalidByte(input.len() - 1, *b));
221+
}
222+
}
223+
224+
return Err(DecodeError::InvalidLength);
225+
}
216226
// This will decode to one output byte, which isn't enough to overwrite the 2 extra bytes
217227
// written by the fast decode loop. So, we have to ignore both these 2 bytes and the
218228
// previous chunk.
@@ -865,4 +875,14 @@ mod tests {
865875
decode_config(b"+//+", crate::STANDARD_NO_PAD)
866876
);
867877
}
878+
879+
#[test]
880+
fn decode_invalid_trailing_bytes() {
881+
// The case of trailing newlines is common enough to warrant a test for a good error
882+
// message.
883+
assert_eq!(
884+
decode(b"Zm9vCg==\n"),
885+
Err(DecodeError::InvalidByte(8, b'\n'))
886+
);
887+
}
868888
}

0 commit comments

Comments
 (0)