pub(crate) fn decode(text: &str) -> Result<Vec<u8>, String> {
let bytes = text.as_bytes();
let unpadded = match bytes {
[rest @ .., b'=', b'='] | [rest @ .., b'='] => {
if !bytes.len().is_multiple_of(4) {
return Err("is padded but isn't a multiple of 4 characters long".to_owned());
}
rest
}
_ => bytes,
};
if unpadded.len() % 4 == 1 {
return Err("has a length no base64 can have".to_owned());
}
let mut out = Vec::with_capacity(unpadded.len() / 4 * 3 + 2);
for (index, chunk) in unpadded.chunks(4).enumerate() {
let mut quad = [0u32; 4];
for (offset, &byte) in chunk.iter().enumerate() {
quad[offset] = u32::from(value(byte).ok_or_else(|| {
format!(
"holds `{}` at character {}, which isn't standard base64",
char::from(byte).escape_default(),
index * 4 + offset
)
})?);
}
let joined = quad[0] << 18 | quad[1] << 12 | quad[2] << 6 | quad[3];
let three = joined.to_be_bytes();
out.extend_from_slice(&three[1..chunk.len()]);
}
Ok(out)
}
const fn value(byte: u8) -> Option<u8> {
match byte {
b'A'..=b'Z' => Some(byte - b'A'),
b'a'..=b'z' => Some(byte - b'a' + 26),
b'0'..=b'9' => Some(byte - b'0' + 52),
b'+' => Some(62),
b'/' => Some(63),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::decode;
#[test]
fn the_rfc_vectors_decode_padded_or_not() {
for (encoded, plain) in [
("", ""),
("Zg==", "f"),
("Zm8=", "fo"),
("Zm9v", "foo"),
("Zm9vYg==", "foob"),
("Zm9vYmE=", "fooba"),
("Zm9vYmFy", "foobar"),
("Zg", "f"),
("Zm9vYmE", "fooba"),
] {
assert_eq!(decode(encoded).as_deref(), Ok(plain.as_bytes()), "{encoded}");
}
assert_eq!(decode("//+/").as_deref(), Ok(&[0xFF, 0xFF, 0xBF][..]));
}
#[test]
fn anything_else_is_refused() {
for bad in ["Z", "Zm9=v", "Zm9 v", "Zm-_", "Zg=", "Zm9vY"] {
assert!(decode(bad).is_err(), "{bad}");
}
}
}