Skip to content

Commit f18ed94

Browse files
committed
Add some detail to base64 errors
1 parent fb3174b commit f18ed94

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

src/forgiving_base64.rs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,26 @@
11
//! <https://infra.spec.whatwg.org/#forgiving-base64-decode>
22
33
#[derive(Debug)]
4-
pub struct InvalidBase64(());
4+
pub struct InvalidBase64(InvalidBase64Details);
5+
6+
#[derive(Debug)]
7+
enum InvalidBase64Details {
8+
UnexpectedSymbol(u8),
9+
AlphabetSymbolAfterPadding,
10+
LoneAlphabetSymbol,
11+
Padding,
12+
}
513

614
#[derive(Debug)]
715
pub enum DecodeError<E> {
816
InvalidBase64(InvalidBase64),
917
WriteError(E),
1018
}
1119

12-
impl<E> From<InvalidBase64> for DecodeError<E> {
13-
fn from(e: InvalidBase64) -> Self { DecodeError::InvalidBase64(e) }
20+
impl<E> From<InvalidBase64Details> for DecodeError<E> {
21+
fn from(e: InvalidBase64Details) -> Self {
22+
DecodeError::InvalidBase64(InvalidBase64(e))
23+
}
1424
}
1525

1626
pub(crate) enum Impossible {}
@@ -71,11 +81,10 @@ impl<F, E> Decoder<F, E> where F: FnMut(&[u8]) -> Result<(), E> {
7181
continue
7282
}
7383

74-
Err(InvalidBase64(()))?
84+
Err(InvalidBase64Details::UnexpectedSymbol(byte))?
7585
}
7686
if self.padding_symbols > 0 {
77-
// Alphabet symbols after padding
78-
Err(InvalidBase64(()))?
87+
Err(InvalidBase64Details::AlphabetSymbolAfterPadding)?
7988
}
8089
self.bit_buffer <<= 6;
8190
self.bit_buffer |= value as u32;
@@ -120,9 +129,11 @@ impl<F, E> Decoder<F, E> where F: FnMut(&[u8]) -> Result<(), E> {
120129
];
121130
(self.write_bytes)(&byte_buffer).map_err(DecodeError::WriteError)?;
122131
}
132+
(6, _) => {
133+
Err(InvalidBase64Details::LoneAlphabetSymbol)?
134+
}
123135
_ => {
124-
// No other combination is acceptable
125-
Err(InvalidBase64(()))?
136+
Err(InvalidBase64Details::Padding)?
126137
}
127138
}
128139
Ok(())

tests/wpt.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ fn run_base64(input: String, expected: Option<Vec<u8>>) {
6868
match (result, expected) {
6969
(Ok(bytes), Some(expected)) => assert_eq!(bytes, expected),
7070
(Ok(bytes), None) => panic!("Expected error, got {:?}", bytes),
71-
(Err(_), Some(expected)) => panic!("Expected {:?}, got error", expected),
71+
(Err(e), Some(expected)) => panic!("Expected {:?}, got error {:?}", expected, e),
7272
(Err(_), None) => {}
7373
}
7474
}

0 commit comments

Comments
 (0)