use core::fmt;
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const PAD: u8 = b'=';
const INVALID: u8 = 0xFF;
const DECODE_TABLE: [u8; 256] = {
let mut table = [INVALID; 256];
let mut index = 0usize;
while index < 64 {
table[ALPHABET[index] as usize] = index as u8;
index += 1;
}
table
};
pub const DEFAULT_MAX_DECODED_LEN: usize = 16 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Base64Error {
UnalignedLength {
len: usize,
},
InvalidByte {
index: usize,
byte: u8,
},
MisplacedPadding {
index: usize,
},
NonCanonicalTail,
TooLong {
len: usize,
max: usize,
},
}
impl fmt::Display for Base64Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnalignedLength { len } => {
write!(f, "base64 length {len} is not a multiple of four")
}
Self::InvalidByte { index, byte } => {
write!(f, "byte 0x{byte:02x} at offset {index} is not base64")
}
Self::MisplacedPadding { index } => {
write!(f, "base64 padding at offset {index} is not at the end")
}
Self::NonCanonicalTail => f.write_str("base64 tail has non-zero unused bits"),
Self::TooLong { len, max } => {
write!(
f,
"base64 would decode to {len} bytes, over the {max}-byte limit"
)
}
}
}
}
impl std::error::Error for Base64Error {}
#[must_use]
pub const fn encoded_len(len: usize) -> usize {
len.div_ceil(3) * 4
}
#[must_use]
const fn decoded_len(len: usize, pad: usize) -> usize {
(len / 4) * 3 - pad
}
#[must_use]
pub fn encode(bytes: &[u8]) -> String {
let mut out = String::with_capacity(encoded_len(bytes.len()));
encode_into(bytes, &mut out);
out
}
pub fn encode_into(bytes: &[u8], out: &mut String) {
out.reserve(encoded_len(bytes.len()));
let (groups, tail) = bytes.as_chunks::<3>();
for &[high, mid, low] in groups {
let group = (u32::from(high) << 16) | (u32::from(mid) << 8) | u32::from(low);
push_symbol(out, (group >> 18) & 0x3F);
push_symbol(out, (group >> 12) & 0x3F);
push_symbol(out, (group >> 6) & 0x3F);
push_symbol(out, group & 0x3F);
}
match tail.len() {
1 => {
let group = u32::from(tail[0]) << 16;
push_symbol(out, (group >> 18) & 0x3F);
push_symbol(out, (group >> 12) & 0x3F);
out.push('=');
out.push('=');
}
2 => {
let group = (u32::from(tail[0]) << 16) | (u32::from(tail[1]) << 8);
push_symbol(out, (group >> 18) & 0x3F);
push_symbol(out, (group >> 12) & 0x3F);
push_symbol(out, (group >> 6) & 0x3F);
out.push('=');
}
_ => {}
}
}
fn push_symbol(out: &mut String, index: u32) {
let symbol = ALPHABET.get(index as usize).copied().unwrap_or(b'A');
out.push(char::from(symbol));
}
pub fn decode(text: &str) -> Result<Vec<u8>, Base64Error> {
decode_with_limit(text, DEFAULT_MAX_DECODED_LEN)
}
pub fn decode_with_limit(text: &str, max_decoded_len: usize) -> Result<Vec<u8>, Base64Error> {
let bytes = text.as_bytes();
let len = bytes.len();
if len == 0 {
return Ok(Vec::new());
}
if !len.is_multiple_of(4) {
return Err(Base64Error::UnalignedLength { len });
}
let mut pad = 0usize;
if bytes[len - 1] == PAD {
pad = 1;
if len >= 2 && bytes[len - 2] == PAD {
pad = 2;
}
}
let out_len = decoded_len(len, pad);
if out_len > max_decoded_len {
return Err(Base64Error::TooLong {
len: out_len,
max: max_decoded_len,
});
}
let mut out = Vec::with_capacity(out_len);
let groups = len / 4;
for group_index in 0..groups {
let base = group_index * 4;
let last_group = group_index + 1 == groups;
let mut symbols = [0u8; 4];
for (offset, symbol) in symbols.iter_mut().enumerate() {
let index = base + offset;
let byte = bytes[index];
if byte == PAD {
let padding_starts_at = 4 - pad;
if !last_group || pad == 0 || offset < padding_starts_at {
return Err(Base64Error::MisplacedPadding { index });
}
*symbol = 0;
continue;
}
let decoded = DECODE_TABLE[byte as usize];
if decoded == INVALID {
return Err(Base64Error::InvalidByte { index, byte });
}
*symbol = decoded;
}
let group = (u32::from(symbols[0]) << 18)
| (u32::from(symbols[1]) << 12)
| (u32::from(symbols[2]) << 6)
| u32::from(symbols[3]);
let keep = if last_group { 3 - pad } else { 3 };
if keep >= 1 {
out.push(((group >> 16) & 0xFF) as u8);
}
if keep >= 2 {
out.push(((group >> 8) & 0xFF) as u8);
}
if keep >= 3 {
out.push((group & 0xFF) as u8);
}
if last_group && pad > 0 {
let discarded_bits = pad * 8;
let mask = (1u32 << discarded_bits) - 1;
if group & mask != 0 {
return Err(Base64Error::NonCanonicalTail);
}
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
const RFC_VECTORS: &[(&[u8], &str)] = &[
(b"", ""),
(b"f", "Zg=="),
(b"fo", "Zm8="),
(b"foo", "Zm9v"),
(b"foob", "Zm9vYg=="),
(b"fooba", "Zm9vYmE="),
(b"foobar", "Zm9vYmFy"),
];
#[test]
fn the_rfc_vectors_encode_and_decode() {
for (bytes, text) in RFC_VECTORS {
assert_eq!(&encode(bytes), text, "encoding {bytes:?}");
assert_eq!(&decode(text).unwrap(), bytes, "decoding {text}");
assert_eq!(encoded_len(bytes.len()), text.len());
}
}
#[test]
fn every_byte_value_survives_a_round_trip() {
let all: Vec<u8> = (0..=255u8).collect();
for len in 0..=all.len() {
let slice = &all[..len];
let text = encode(slice);
assert_eq!(text.len(), encoded_len(len));
assert_eq!(decode(&text).unwrap(), slice, "length {len}");
}
}
#[test]
fn the_alphabet_is_covered_in_both_directions() {
for (index, symbol) in ALPHABET.iter().enumerate() {
assert_eq!(usize::from(DECODE_TABLE[*symbol as usize]), index);
}
assert_eq!(DECODE_TABLE[PAD as usize], INVALID);
assert_eq!(DECODE_TABLE[b' ' as usize], INVALID);
assert_eq!(
DECODE_TABLE[b'-' as usize], INVALID,
"url alphabet is not accepted"
);
assert_eq!(
DECODE_TABLE[b'_' as usize], INVALID,
"url alphabet is not accepted"
);
}
#[test]
fn an_unaligned_length_is_refused() {
for text in ["a", "ab", "abc", "Zm9vYmFyZ"] {
assert!(matches!(
decode(text),
Err(Base64Error::UnalignedLength { .. })
));
}
}
#[test]
fn whitespace_and_newlines_are_not_skipped() {
for text in ["Zm9v Ym8", "Zm9v\nYm8", "Zm9v\tYm8", "Z m9"] {
assert!(
matches!(decode(text), Err(Base64Error::InvalidByte { .. })),
"{text}"
);
}
assert!(matches!(
decode("Zm9v YmFy"),
Err(Base64Error::UnalignedLength { len: 9 })
));
}
#[test]
fn misplaced_padding_is_refused() {
for text in ["Zg==Zg==", "Z=g=", "=Zm9", "Zm=v"] {
let err = decode(text).unwrap_err();
assert!(
matches!(
err,
Base64Error::MisplacedPadding { .. } | Base64Error::InvalidByte { .. }
),
"{text}: {err}"
);
}
}
#[test]
fn non_canonical_tails_are_refused() {
assert_eq!(decode("Zg==").unwrap(), b"f");
assert!(matches!(decode("Zh=="), Err(Base64Error::NonCanonicalTail)));
assert_eq!(decode("Zm8=").unwrap(), b"fo");
assert!(matches!(
decode("Zm9=").unwrap_err(),
Base64Error::NonCanonicalTail
));
}
#[test]
fn the_limit_is_checked_before_allocating() {
let text = encode(&[7u8; 3_000]);
assert!(matches!(
decode_with_limit(&text, 1_024),
Err(Base64Error::TooLong {
len: 3_000,
max: 1_024
})
));
assert_eq!(decode_with_limit(&text, 3_000).unwrap().len(), 3_000);
}
#[test]
fn encode_into_appends_rather_than_replacing() {
let mut buffer = String::from("prefix:");
encode_into(b"foobar", &mut buffer);
assert_eq!(buffer, "prefix:Zm9vYmFy");
encode_into(b"", &mut buffer);
assert_eq!(buffer, "prefix:Zm9vYmFy");
}
#[test]
fn errors_describe_themselves() {
let errors = [
Base64Error::UnalignedLength { len: 3 },
Base64Error::InvalidByte {
index: 1,
byte: b' ',
},
Base64Error::MisplacedPadding { index: 0 },
Base64Error::NonCanonicalTail,
Base64Error::TooLong { len: 9, max: 8 },
];
for error in errors {
assert!(!error.to_string().is_empty());
let _: &dyn std::error::Error = &error;
}
}
}