Skip to main content

bilingua_model/
b64.rs

1//! Raw bytes in JSON as a base64 string (standard alphabet, padded). Reading also accepts the old form, an
2//! array of integers, so skeletons saved before this change still load.
3
4use serde::de::{self, SeqAccess, Visitor};
5use serde::{Deserializer, Serializer};
6use std::fmt;
7
8const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
9
10/// Standard base64 with padding.
11pub fn encode(data: &[u8]) -> String {
12    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
13    for chunk in data.chunks(3) {
14        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
15        let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
16        out.push(ALPHABET[(n >> 18) as usize & 63] as char);
17        out.push(ALPHABET[(n >> 12) as usize & 63] as char);
18        out.push(if chunk.len() > 1 { ALPHABET[(n >> 6) as usize & 63] as char } else { '=' });
19        out.push(if chunk.len() > 2 { ALPHABET[n as usize & 63] as char } else { '=' });
20    }
21    out
22}
23
24/// Decodes standard base64 (padding optional); the error says what is wrong.
25pub fn decode(s: &str) -> Result<Vec<u8>, String> {
26    let b = s.as_bytes();
27    if !b.len().is_multiple_of(4) {
28        return Err("base64 length is not a multiple of 4".into());
29    }
30    // A lookup table: a linear search of the alphabet made a 20 MB skeleton take seconds to read.
31    const BAD: u8 = 0xFF;
32    const TABLE: [u8; 256] = {
33        let mut t = [BAD; 256];
34        let mut i = 0;
35        while i < 64 {
36            t[ALPHABET[i] as usize] = i as u8;
37            i += 1;
38        }
39        t
40    };
41    let val = |c: u8| -> Result<u32, String> {
42        match TABLE[c as usize] {
43            BAD => Err(format!("bad base64 byte 0x{c:02x}")),
44            v => Ok(v as u32),
45        }
46    };
47    let mut out = Vec::with_capacity(b.len() / 4 * 3);
48    for (i, q) in b.chunks(4).enumerate() {
49        let last = (i + 1) * 4 == b.len();
50        let pad = q.iter().rev().take_while(|&&c| c == b'=').count();
51        if pad > 2 || (pad > 0 && !last) {
52            return Err("misplaced base64 padding".into());
53        }
54        let mut n = 0u32;
55        for &c in &q[..4 - pad] {
56            n = (n << 6) | val(c)?;
57        }
58        n <<= 6 * pad as u32;
59        out.push((n >> 16) as u8);
60        if pad < 2 {
61            out.push((n >> 8) as u8);
62        }
63        if pad < 1 {
64            out.push(n as u8);
65        }
66    }
67    Ok(out)
68}
69
70/// Serde: bytes as a base64 string.
71pub fn serialize<S: Serializer>(data: &[u8], s: S) -> Result<S::Ok, S::Error> {
72    s.serialize_str(&encode(data))
73}
74
75/// Serde: a base64 string, or the old array of integers.
76pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
77    struct V;
78    impl<'de> Visitor<'de> for V {
79        type Value = Vec<u8>;
80        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81            f.write_str("a base64 string or an array of bytes")
82        }
83        fn visit_str<E: de::Error>(self, v: &str) -> Result<Vec<u8>, E> {
84            decode(v).map_err(E::custom)
85        }
86        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u8>, A::Error> {
87            let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(1 << 20));
88            while let Some(b) = seq.next_element::<u8>()? {
89                out.push(b);
90            }
91            Ok(out)
92        }
93    }
94    d.deserialize_any(V)
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn known_vectors() {
103        for (raw, enc) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
104            assert_eq!(encode(raw.as_bytes()), enc);
105            assert_eq!(decode(enc).unwrap(), raw.as_bytes());
106        }
107    }
108
109    #[test]
110    fn all_bytes_round_trip() {
111        let all: Vec<u8> = (0..=255).collect();
112        for n in [0, 1, 2, 3, 255, 256] {
113            assert_eq!(decode(&encode(&all[..n])).unwrap(), &all[..n]);
114        }
115    }
116
117    #[test]
118    fn bad_input_is_an_error() {
119        for bad in ["abc", "ab!d", "=abc", "a===", "Zg==Zg=="] {
120            assert!(decode(bad).is_err(), "{bad}");
121        }
122        // Non-ASCII and control bytes are errors, not panics.
123        for bad in ["\u{e9}abc", "ab\u{645}", "ab\n=", "\0\0\0\0"] {
124            assert!(decode(bad).is_err(), "{bad:?}");
125        }
126    }
127
128    #[test]
129    fn large_input_round_trips_quickly() {
130        let data: Vec<u8> = (0..8_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();
131        let enc = encode(&data);
132        let t = std::time::Instant::now();
133        let back = decode(&enc).unwrap();
134        eprintln!("decode of {} base64 chars: {:?}", enc.len(), t.elapsed());
135        assert_eq!(back, data);
136    }
137}