Skip to main content

pltrs_codec/
base64.rs

1//! Base64 (RFC 4648, standard alphabet with padding), as used to embed
2//! images in HTML and SVG documents: encoding, and decoding.
3
4/// The standard alphabet.
5const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
6
7/// `data` in base64 on one line.
8///
9/// ```
10/// assert_eq!(pltrs_codec::base64::encode(b"plt"), "cGx0");
11/// assert_eq!(pltrs_codec::base64::encode(b"pl"), "cGw=");
12/// ```
13pub 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
31/// `data` in base64 in lines of 76 characters, each ending with a newline
32/// (Python's `base64.encodebytes`, MIME style).
33///
34/// ```
35/// let text = pltrs_codec::base64::encode_lines(&[0; 60]);
36/// assert_eq!(text.lines().map(str::len).collect::<Vec<_>>(), [76, 4]);
37/// assert!(text.ends_with('\n'));
38/// ```
39pub fn encode_lines(data: &[u8]) -> String {
40    // 57 bytes make 76 characters.
41    data.chunks(57).map(|chunk| encode(chunk) + "\n").collect()
42}
43
44/// Why text is not valid base64.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Base64Error {
47    /// A character outside the alphabet, padding and line breaks, at this
48    /// byte offset.
49    InvalidCharacter(usize),
50    /// The characters do not form whole groups of four, or padding is
51    /// misplaced.
52    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
66/// The bytes of base64 `text` (standard alphabet, with padding). Line
67/// breaks (`\n`, `\r`) are skipped, as in [`encode_lines`]'s output.
68///
69/// ```
70/// assert_eq!(pltrs_codec::base64::decode("cGx0"), Ok(b"plt".to_vec()));
71/// assert_eq!(pltrs_codec::base64::decode("cG\nw="), Ok(b"pl".to_vec()));
72/// assert!(pltrs_codec::base64::decode("cGw").is_err());
73/// ```
74///
75/// # Errors
76///
77/// When `text` holds other characters, or is not made of whole groups of
78/// four characters with padding only at the end.
79pub 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}