Skip to content

Commit 0b58116

Browse files
committed
Add base64 decoding to Vec
1 parent cfe91f8 commit 0b58116

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

src/lib.rs

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -81,13 +81,19 @@ impl<'a> DataUrl<'a> {
8181
pub fn decode_to_vec(&self)
8282
-> Result<(Vec<u8>, Option<FragmentIdentifier<'a>>), InvalidBase64>
8383
{
84-
enum Impossible {}
8584
let mut body = Vec::new();
86-
let result = self.decode::<_, Impossible>(|bytes| Ok(body.extend_from_slice(bytes)));
87-
match result {
88-
Ok(url_fragment) => Ok((body, url_fragment)),
89-
Err(DecodeError::InvalidBase64(e)) => Err(e),
90-
Err(DecodeError::WriteError(e)) => match e {}
85+
let fragment = self.decode(|bytes| Ok(body.extend_from_slice(bytes)))?;
86+
Ok((body, fragment))
87+
}
88+
}
89+
90+
enum Impossible {}
91+
92+
impl From<DecodeError<Impossible>> for InvalidBase64 {
93+
fn from(e: DecodeError<Impossible>) -> Self {
94+
match e {
95+
DecodeError::InvalidBase64(e) => e,
96+
DecodeError::WriteError(e) => match e {}
9197
}
9298
}
9399
}
@@ -312,6 +318,19 @@ fn decode_with_base64<F, E>(encoded_body_plus_fragment: &str, write_bytes: F)
312318
Ok(fragment)
313319
}
314320

321+
/// <https://infra.spec.whatwg.org/#forgiving-base64-decode>
322+
///
323+
/// `input` is assumed to be in an ASCII-compatible encoding
324+
pub fn forgiving_base64_decode_to_vec(input: &[u8]) -> Result<Vec<u8>, InvalidBase64> {
325+
let mut v = Vec::new();
326+
{
327+
let mut decoder = ForgivingBase64Decoder::new(|bytes| Ok(v.extend_from_slice(bytes)));
328+
decoder.feed(input)?;
329+
decoder.finish()?;
330+
}
331+
Ok(v)
332+
}
333+
315334
/// <https://infra.spec.whatwg.org/#forgiving-base64-decode>
316335
pub struct ForgivingBase64Decoder<F, E> where F: FnMut(&[u8]) -> Result<(), E> {
317336
write_bytes: F,

0 commit comments

Comments
 (0)