fn value(b: u8) -> Option<u32> {
match b {
b'A'..=b'Z' => Some(u32::from(b - b'A')),
b'a'..=b'z' => Some(u32::from(b - b'a') + 26),
b'0'..=b'9' => Some(u32::from(b - b'0') + 52),
b'+' | b'-' => Some(62),
b'/' | b'_' => Some(63),
_ => None,
}
}
pub(crate) fn decode(s: &str) -> Option<Vec<u8>> {
let body = s.trim_end_matches('=');
let mut out = Vec::with_capacity(body.len() / 4 * 3 + 2);
let mut acc = 0u32;
let mut bits = 0u32;
for &b in body.as_bytes() {
acc = (acc << 6) | value(b)?;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
acc &= (1 << bits) - 1;
}
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::decode;
#[test]
fn decodes_known_vectors() {
assert_eq!(decode("").unwrap(), b"");
assert_eq!(decode("Zg==").unwrap(), b"f");
assert_eq!(decode("Zm8=").unwrap(), b"fo");
assert_eq!(decode("Zm9v").unwrap(), b"foo");
assert_eq!(decode("Zm9vYg").unwrap(), b"foob");
assert_eq!(decode("Zm9vYmFy").unwrap(), b"foobar");
assert!(decode("Zm9v!").is_none());
}
}