const STD: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub(crate) fn encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
let chars = chunk.len() + 1;
for i in 0..4 {
if i < chars {
out.push(STD[((n >> (18 - 6 * i)) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
fn symbol(c: u8) -> Option<u32> {
STD.iter().position(|&t| t == c).map(|p| p as u32)
}
pub(crate) fn decode(s: &str) -> Result<Vec<u8>, &'static str> {
let bytes = s.as_bytes();
if !bytes.len().is_multiple_of(4) {
return Err("length is not a multiple of 4");
}
if bytes.is_empty() {
return Ok(Vec::new());
}
let mut pad = 0;
while pad < 2 && bytes[bytes.len() - 1 - pad] == b'=' {
pad += 1;
}
let body = &bytes[..bytes.len() - pad];
let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
for chunk in body.chunks(4) {
let mut n = 0u32;
for (i, &c) in chunk.iter().enumerate() {
if c == b'=' {
return Err("padding inside data");
}
let v = symbol(c).ok_or("invalid symbol")?;
n |= v << (18 - 6 * i);
}
let bytes_out = chunk.len() - 1;
let full = n.to_be_bytes();
out.extend_from_slice(&full[1..1 + bytes_out]);
if chunk.len() < 4 && (n & ((1 << (24 - 8 * bytes_out)) - 1)) != 0 {
return Err("non-canonical tail");
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vectors() {
assert_eq!(encode(b""), "");
assert_eq!(encode(b"f"), "Zg==");
assert_eq!(encode(b"fo"), "Zm8=");
assert_eq!(encode(b"foo"), "Zm9v");
assert_eq!(encode(b"foobar"), "Zm9vYmFy");
assert_eq!(encode(&[0xff, 0xfe, 0xfd]), "//79");
assert_eq!(decode("//79").unwrap(), vec![0xff, 0xfe, 0xfd]);
}
#[test]
fn roundtrip() {
assert_eq!(decode("").unwrap(), Vec::<u8>::new());
for len in 0..64usize {
let data: Vec<u8> = (0..len).map(|i| (i * 31 + 7) as u8).collect();
assert_eq!(decode(&encode(&data)).unwrap(), data);
}
let all: Vec<u8> = (0..=255).collect();
assert_eq!(decode(&encode(&all)).unwrap(), all);
}
#[test]
fn rejects() {
for s in [
"a", "abc", "a====", "====", "a===", "AB=C", "a=b=", "a$b=", "a-b=", "Zh==", "Ah==",
"-i-d",
] {
assert!(decode(s).is_err(), "{s}");
}
}
}