Skip to main content

qr_base45/
lib.rs

1//! qr-base45: Base45 encoder/decoder for arbitrary bytes (RFC 9285) using the QR alphanumeric alphabet.
2//! - Encoding groups: 2 bytes -> 3 chars; 1 byte -> 2 chars.
3//! - Alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
4//! - Public API encodes &[u8] -> String and decodes &str -> Vec<u8>.
5
6#[derive(Debug, thiserror::Error)]
7pub enum Base45Error {
8    #[error("invalid base45 character")]
9    InvalidChar,
10    #[error("dangling character group")]
11    Dangling,
12    #[error("value overflow")]
13    Overflow,
14}
15
16/// Base45 alphabet as per RFC 9285
17pub const BASE45_ALPHABET: &[u8; 45] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
18
19#[inline]
20fn b45_val(ch: u8) -> Option<u16> {
21    match ch {
22        b'0'..=b'9' => Some((ch - b'0') as u16),
23        b'A'..=b'Z' => Some(10 + (ch - b'A') as u16),
24        b' ' => Some(36),
25        b'$' => Some(37),
26        b'%' => Some(38),
27        b'*' => Some(39),
28        b'+' => Some(40),
29        b'-' => Some(41),
30        b'.' => Some(42),
31        b'/' => Some(43),
32        b':' => Some(44),
33        _ => None,
34    }
35}
36
37/// Encode arbitrary bytes into a Base45 string.
38/// Groups of 2 bytes produce 3 characters; a final single byte produces 2 characters.
39pub fn encode(input: &[u8]) -> String {
40    let mut out = String::with_capacity((input.len() * 3).div_ceil(2));
41    let mut i = 0;
42    while i + 1 < input.len() {
43        let x = (input[i] as u16) * 256 + (input[i + 1] as u16);
44        let c = x % 45; // least significant digit
45        let x = x / 45;
46        let b = x % 45;
47        let a = x / 45; // most significant digit (0..=8)
48                        // Base45 outputs least-significant digit first
49        out.push(BASE45_ALPHABET[c as usize] as char);
50        out.push(BASE45_ALPHABET[b as usize] as char);
51        out.push(BASE45_ALPHABET[a as usize] as char);
52        i += 2;
53    }
54    if i < input.len() {
55        let x = input[i] as u16;
56        let b = x % 45;
57        let a = x / 45;
58        // Base45 outputs least-significant digit first for single byte too
59        out.push(BASE45_ALPHABET[b as usize] as char);
60        out.push(BASE45_ALPHABET[a as usize] as char);
61    }
62    out
63}
64
65/// Decode a Base45 string back to raw bytes.
66/// Accepts only the RFC 9285 alphabet; returns errors for invalid chars, dangling final char, or overflow.
67pub fn decode(s: &str) -> Result<Vec<u8>, Base45Error> {
68    let bytes = s.as_bytes();
69    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
70    let mut i = 0;
71    while i + 2 < bytes.len() {
72        // Input is least-significant digit first: c (lsd), b, a (msd)
73        let c0 = b45_val(bytes[i]).ok_or(Base45Error::InvalidChar)? as u32;
74        let c1 = b45_val(bytes[i + 1]).ok_or(Base45Error::InvalidChar)? as u32;
75        let c2 = b45_val(bytes[i + 2]).ok_or(Base45Error::InvalidChar)? as u32;
76        let x: u32 = c2 * 45 * 45 + c1 * 45 + c0; // 0..(45^3 - 1)
77        if x > 65535 {
78            return Err(Base45Error::Overflow);
79        }
80        out.push((x / 256) as u8);
81        out.push((x % 256) as u8);
82        i += 3;
83    }
84    if i < bytes.len() {
85        if i + 1 >= bytes.len() {
86            return Err(Base45Error::Dangling);
87        }
88        let c0 = b45_val(bytes[i]).ok_or(Base45Error::InvalidChar)? as u32;
89        let c1 = b45_val(bytes[i + 1]).ok_or(Base45Error::InvalidChar)? as u32;
90        let x: u32 = c1 * 45 + c0; // 0..(45^2 - 1)
91        if x > 255 {
92            return Err(Base45Error::Overflow);
93        }
94        out.push(x as u8);
95    }
96    Ok(out)
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn roundtrips() {
105        let cases: &[&[u8]] = &[
106            b"",
107            b"A",
108            b"AB",
109            b"Hello, world!",
110            &[0x00],
111            &[0x00, 0x01, 0xFF, 0x80, 0x7F],
112        ];
113        for &case in cases {
114            let s = encode(case);
115            let dec = decode(&s).unwrap();
116            assert_eq!(case, dec.as_slice());
117        }
118    }
119
120    #[test]
121    fn known_vectors() {
122        // From RFC examples and common vectors
123        assert_eq!(encode(b"AB"), "BB8");
124        assert_eq!(encode(b"Hello!!"), "%69 VD92EX0");
125        assert_eq!(encode(b"base-45"), "UJCLQE7W581");
126        assert_eq!(encode(b"ietf!"), "QED8WEX0");
127
128        assert_eq!(decode("BB8").unwrap(), b"AB");
129        assert_eq!(decode("QED8WEX0").unwrap(), b"ietf!");
130    }
131
132    #[test]
133    fn errors() {
134        assert!(matches!(decode("A"), Err(Base45Error::Dangling)));
135        assert!(matches!(decode("😀"), Err(Base45Error::InvalidChar)));
136    }
137}