1const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
6
7pub fn encode(data: &[u8]) -> String {
14 let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
15 for chunk in data.chunks(3) {
16 let bytes = [
17 chunk[0],
18 chunk.get(1).copied().unwrap_or(0),
19 chunk.get(2).copied().unwrap_or(0),
20 ];
21 let n = u32::from(bytes[0]) << 16 | u32::from(bytes[1]) << 8 | u32::from(bytes[2]);
22 let symbols =
23 [18, 12, 6, 0].map(|shift| char::from(ALPHABET[((n >> shift) & 63) as usize]));
24 let kept = chunk.len() + 1;
25 out.extend(&symbols[..kept]);
26 out.extend(std::iter::repeat_n('=', 4 - kept));
27 }
28 out
29}
30
31pub fn encode_lines(data: &[u8]) -> String {
40 data.chunks(57).map(|chunk| encode(chunk) + "\n").collect()
42}
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Base64Error {
47 InvalidCharacter(usize),
50 InvalidLength,
53}
54
55impl std::fmt::Display for Base64Error {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 match self {
58 Self::InvalidCharacter(at) => write!(f, "invalid base64 character at offset {at}"),
59 Self::InvalidLength => f.write_str("base64 text is not a whole number of groups"),
60 }
61 }
62}
63
64impl std::error::Error for Base64Error {}
65
66pub fn decode(text: &str) -> Result<Vec<u8>, Base64Error> {
80 let mut symbols = Vec::with_capacity(text.len());
81 for (at, byte) in text.bytes().enumerate() {
82 match byte {
83 b'\n' | b'\r' => {}
84 b'=' => symbols.push(None),
85 _ => {
86 let value = (0_u32..)
87 .zip(ALPHABET)
88 .find_map(|(value, &c)| (c == byte).then_some(value))
89 .ok_or(Base64Error::InvalidCharacter(at))?;
90 symbols.push(Some(value));
91 }
92 }
93 }
94 if symbols.len() % 4 != 0 {
95 return Err(Base64Error::InvalidLength);
96 }
97 let groups = symbols.len() / 4;
98 let mut out = Vec::with_capacity(groups * 3);
99 for (index, group) in symbols.as_chunks::<4>().0.iter().enumerate() {
100 let kept = group.iter().take_while(|s| s.is_some()).count();
101 let padded_properly = group[kept..].iter().all(Option::is_none);
102 if kept < 2 || !padded_properly || (kept < 4 && index + 1 != groups) {
103 return Err(Base64Error::InvalidLength);
104 }
105 let n = group
106 .iter()
107 .fold(0, |n, symbol| n << 6 | symbol.unwrap_or(0));
108 out.extend_from_slice(&n.to_be_bytes()[1..kept]);
109 }
110 Ok(out)
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116
117 #[test]
118 fn rfc_4648_vectors() {
119 let cases = [
120 ("", ""),
121 ("f", "Zg=="),
122 ("fo", "Zm8="),
123 ("foo", "Zm9v"),
124 ("foob", "Zm9vYg=="),
125 ("fooba", "Zm9vYmE="),
126 ("foobar", "Zm9vYmFy"),
127 ];
128 for (plain, coded) in cases {
129 assert_eq!(encode(plain.as_bytes()), coded);
130 }
131 assert_eq!(encode(&[0xff, 0xfe]), "//4=");
132 assert_eq!(encode_lines(b""), "");
133 for (plain, coded) in cases {
134 assert_eq!(decode(coded), Ok(plain.as_bytes().to_vec()));
135 }
136 }
137
138 #[test]
139 fn decoding_reverses_encoding() {
140 let data: Vec<u8> = (0..=255)
141 .chain((0..100_u32).map(|i| (i * 7 % 256) as u8))
142 .collect();
143 for len in 0..data.len() {
144 assert_eq!(decode(&encode(&data[..len])).as_deref(), Ok(&data[..len]));
145 }
146 assert_eq!(decode(&encode_lines(&data)), Ok(data));
147 }
148
149 #[test]
150 fn bad_text_is_rejected() {
151 assert_eq!(decode("ab$d"), Err(Base64Error::InvalidCharacter(2)));
152 assert_eq!(decode("abc"), Err(Base64Error::InvalidLength));
153 assert_eq!(decode("a==="), Err(Base64Error::InvalidLength));
154 assert_eq!(decode("ab=c"), Err(Base64Error::InvalidLength));
155 assert_eq!(decode("ab==cdef"), Err(Base64Error::InvalidLength));
156 }
157}