use super::{decode, encode};
const VECTORS: [(&str, &str); 7] = [
("", ""),
("f", "Zg"),
("fo", "Zm8"),
("foo", "Zm9v"),
("foob", "Zm9vYg"),
("fooba", "Zm9vYmE"),
("foobar", "Zm9vYmFy"),
];
#[test]
fn the_encoding_is_rfc_4648_base64url_without_padding() {
for (plain, encoded) in VECTORS {
assert_eq!(encode(plain.as_bytes()), encoded, "encoding {plain:?}");
assert_eq!(
decode(encoded).as_deref(),
Some(plain.as_bytes()),
"decoding {encoded:?}"
);
}
}
#[test]
fn the_two_symbols_that_make_it_url_safe_are_the_url_safe_ones() {
assert_eq!(encode(&[0xfb, 0xff, 0xbf]), "-_-_");
assert_eq!(decode("-_-_"), Some(vec![0xfb, 0xff, 0xbf]));
assert_eq!(decode("+/+/"), None, "the §4 alphabet is not this one");
}
#[test]
fn every_byte_round_trips_at_every_alignment() {
for lead in 0..3usize {
let mut bytes = vec![0xa5; lead];
bytes.extend(0..=255u8);
assert_eq!(decode(&encode(&bytes)).as_deref(), Some(bytes.as_slice()));
}
}
#[test]
fn padding_is_refused() {
assert_eq!(decode("Zg=="), None);
assert_eq!(decode("Zm8="), None);
}
#[test]
fn a_trailing_group_of_one_symbol_is_refused() {
assert_eq!(decode("Z"), None);
assert_eq!(decode("Zm9vZ"), None);
}
#[test]
fn a_final_group_whose_spare_bits_are_set_is_refused() {
assert_eq!(decode("Zg"), Some(b"f".to_vec()));
for spelling in ["Zh", "Zi", "Zv"] {
assert_eq!(
decode(spelling),
None,
"{spelling} is a second spelling of `f`"
);
}
assert_eq!(decode("Zm8"), Some(b"fo".to_vec()));
assert_eq!(decode("Zm9"), None);
}
#[test]
fn a_symbol_outside_the_alphabet_is_refused() {
for spelling in ["Zm9v!", "Zm 9v", "Zm9v\n", "Zm9v.Zm9v"] {
assert_eq!(decode(spelling), None, "{spelling:?}");
}
}