use super::base64;
#[test]
fn the_rfc_4648_vectors_are_what_it_writes() {
assert_eq!(base64(b""), "");
assert_eq!(base64(b"f"), "Zg==");
assert_eq!(base64(b"fo"), "Zm8=");
assert_eq!(base64(b"foo"), "Zm9v");
assert_eq!(base64(b"foob"), "Zm9vYg==");
assert_eq!(base64(b"fooba"), "Zm9vYmE=");
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
}
#[test]
fn the_two_symbols_are_the_standard_alphabets() {
assert_eq!(base64(&[0xff, 0xff, 0xfe]), "///+");
assert!(!base64(&[0xff, 0xff, 0xfe]).contains(['-', '_']));
}
#[test]
fn every_output_is_a_whole_number_of_groups() {
for len in 0..32_usize {
let bytes = vec![0xa5; len];
let encoded = base64(&bytes);
assert_eq!(encoded.len() % 4, 0, "{len}: {encoded}");
assert_eq!(encoded.len(), len.div_ceil(3) * 4, "{len}: {encoded}");
}
}
#[test]
fn every_byte_round_trips() {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let bytes: Vec<u8> = (0..=255).collect();
let encoded = base64(&bytes);
let mut decoded = Vec::with_capacity(bytes.len());
for group in encoded.as_bytes().chunks(4) {
let symbols: Vec<u8> = group
.iter()
.take_while(|symbol| **symbol != b'=')
.map(|symbol| {
ALPHABET
.iter()
.position(|candidate| candidate == symbol)
.expect("every symbol is in the alphabet") as u8
})
.collect();
let mut packed = 0u32;
for (i, six) in symbols.iter().enumerate() {
packed |= u32::from(*six) << (18 - i * 6);
}
for i in 0..symbols.len() - 1 {
decoded.push(((packed >> (16 - i * 8)) & 0xff) as u8);
}
}
assert_eq!(decoded, bytes);
}