Skip to main content

qrcode_decode/
sa_parse.rs

1//! Structured Append bit-stream parser.
2//!
3//! Given one symbol's data bit stream (the bytes a decoder recovers from the
4//! data region of a single QR symbol), [`parse_sa_datastream`] reads the
5//! Structured Append header (mode `0011`, the symbol-sequence indicator, and
6//! the parity byte) and then decodes the data segments, returning the position,
7//! total, parity, and the recovered payload bytes.
8//!
9//! This is decoder-agnostic: it works on whatever bytes your decoder hands you.
10//! The `rqrr` adapter (behind the `rqrr` feature) can be paired with decoders
11//! that expose raw symbol bytes for an end-to-end encode/render/decode
12//! round-trip.
13
14#[cfg(not(feature = "std"))]
15#[allow(unused_imports)]
16use alloc::vec::Vec;
17
18use core::fmt::{Display, Error, Formatter};
19use qrcode_core::{Mode, Version};
20
21/// Errors returned while parsing a Structured Append data bit stream.
22#[non_exhaustive]
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum SaParseError {
25    /// The decoded bit stream does not begin with the Structured Append mode
26    /// indicator (`0011`).
27    NotStructuredAppend,
28    /// The bit stream was truncated or otherwise malformed while parsing a
29    /// Structured Append header or data segment.
30    MalformedStream,
31}
32
33impl Display for SaParseError {
34    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
35        match self {
36            Self::NotStructuredAppend => f.write_str("not a Structured Append symbol (no `0011` mode indicator)"),
37            Self::MalformedStream => f.write_str("malformed Structured Append bit stream"),
38        }
39    }
40}
41
42impl ::core::error::Error for SaParseError {}
43
44/// Reverse of the alphanumeric base-45 charset (ISO/IEC 18004 §8.4.3, Table 5):
45/// base-45 value (0..44) → character byte.
46const ALPHA_REV: [u8; 45] = *b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
47
48/// A Structured Append symbol parsed from a data bit stream (owned payload).
49///
50/// Produced by [`parse_sa_datastream`]. To recombine a sequence, rebuild
51/// Structured Append symbol values from each symbol's `position` / `total` /
52/// `parity` / `data` and pass them to the facade crate's reassembly helper.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct SaSymbolData {
55    /// 1-based position within the sequence (`1..=total`).
56    pub position: u8,
57    /// Total number of symbols in the sequence (`2..=16`).
58    pub total: u8,
59    /// The parity byte (XOR of the original full message; identical in every symbol).
60    pub parity: u8,
61    /// This symbol's recovered payload bytes.
62    pub data: Vec<u8>,
63}
64
65/// A big-endian (MSB-first) reader over a byte slice — the read-side mirror of
66/// the push-side `qrcode_core::bits::Bits`.
67struct BitReader<'a> {
68    data: &'a [u8],
69    pos: usize,
70}
71
72impl<'a> BitReader<'a> {
73    fn new(data: &'a [u8]) -> Self {
74        Self { data, pos: 0 }
75    }
76
77    /// Reads `n` bits big-endian, or `None` if not enough bits remain.
78    fn read_bits(&mut self, n: usize) -> Option<u32> {
79        if n == 0 {
80            return Some(0);
81        }
82        if self.pos.checked_add(n)? > self.data.len() * 8 {
83            return None;
84        }
85        let mut val: u32 = 0;
86        for _ in 0..n {
87            let byte = self.data[self.pos >> 3];
88            let bit = (byte >> (7 - (self.pos & 7))) & 1;
89            val = (val << 1) | u32::from(bit);
90            self.pos += 1;
91        }
92        Some(val)
93    }
94
95    fn remaining(&self) -> usize {
96        self.data.len() * 8 - self.pos
97    }
98}
99
100/// Parses a Structured Append data bit stream into its header and payload.
101///
102/// `bits` is one symbol's data region (as recovered by a decoder); `version`
103/// sets the character-count bit widths used by each data segment. The function
104/// reads the 20-bit Structured Append header, then decodes Numeric /
105/// Alphanumeric / Byte / Kanji segments until the terminator, returning the
106/// recovered bytes.
107///
108/// # Errors
109///
110/// Returns [`SaParseError::NotStructuredAppend`] if the stream does not begin
111/// with the Structured Append mode indicator (`0011`), or
112/// [`SaParseError::MalformedStream`] if the bits run out mid-field.
113pub fn parse_sa_datastream(bits: &[u8], version: Version) -> Result<SaSymbolData, SaParseError> {
114    let mut r = BitReader::new(bits);
115
116    let mode = r.read_bits(4).ok_or(SaParseError::MalformedStream)?;
117    if mode != 0b0011 {
118        return Err(SaParseError::NotStructuredAppend);
119    }
120    let sequence = r.read_bits(8).ok_or(SaParseError::MalformedStream)?;
121    let position = ((sequence >> 4) + 1) as u8;
122    let total = ((sequence & 0x0f) + 1) as u8;
123    if total < 2 || position > total {
124        return Err(SaParseError::MalformedStream);
125    }
126    let parity = r.read_bits(8).ok_or(SaParseError::MalformedStream)? as u8;
127
128    let mut data = Vec::new();
129    while r.remaining() >= 4 {
130        let segment_mode = r.read_bits(4).ok_or(SaParseError::MalformedStream)?;
131        match segment_mode {
132            0b0000 => break, // terminator
133            0b0001 => decode_numeric(&mut r, version, &mut data)?,
134            0b0010 => decode_alpha(&mut r, version, &mut data)?,
135            0b0100 => decode_byte(&mut r, version, &mut data)?,
136            0b1000 => decode_kanji(&mut r, version, &mut data)?,
137            // FNC1 / ECI / unknown — stop with the payload parsed so far.
138            _ => break,
139        }
140    }
141
142    Ok(SaSymbolData { position, total, parity, data })
143}
144
145fn decode_byte(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
146    let count = r.read_bits(Mode::Byte.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
147    for _ in 0..count {
148        let byte = r.read_bits(8).ok_or(SaParseError::MalformedStream)? as u8;
149        out.push(byte);
150    }
151    Ok(())
152}
153
154fn decode_numeric(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
155    let mut remaining =
156        r.read_bits(Mode::Numeric.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
157    while remaining >= 3 {
158        let v = r.read_bits(10).ok_or(SaParseError::MalformedStream)?;
159        out.push(b'0' + (v / 100) as u8);
160        out.push(b'0' + ((v / 10) % 10) as u8);
161        out.push(b'0' + (v % 10) as u8);
162        remaining -= 3;
163    }
164    if remaining == 2 {
165        let v = r.read_bits(7).ok_or(SaParseError::MalformedStream)?;
166        out.push(b'0' + (v / 10) as u8);
167        out.push(b'0' + (v % 10) as u8);
168    } else if remaining == 1 {
169        let v = r.read_bits(4).ok_or(SaParseError::MalformedStream)?;
170        out.push(b'0' + v as u8);
171    }
172    Ok(())
173}
174
175fn decode_alpha(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
176    let mut remaining =
177        r.read_bits(Mode::Alphanumeric.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
178    while remaining >= 2 {
179        let v = r.read_bits(11).ok_or(SaParseError::MalformedStream)? as usize;
180        let first = ALPHA_REV.get(v / 45).ok_or(SaParseError::MalformedStream)?;
181        let second = ALPHA_REV.get(v % 45).ok_or(SaParseError::MalformedStream)?;
182        out.push(*first);
183        out.push(*second);
184        remaining -= 2;
185    }
186    if remaining == 1 {
187        let v = r.read_bits(6).ok_or(SaParseError::MalformedStream)? as usize;
188        out.push(*ALPHA_REV.get(v).ok_or(SaParseError::MalformedStream)?);
189    }
190    Ok(())
191}
192
193fn decode_kanji(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
194    let count = r.read_bits(Mode::Kanji.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
195    for _ in 0..count {
196        let n = r.read_bits(13).ok_or(SaParseError::MalformedStream)?;
197        let high = n / 0xc0;
198        let low = n % 0xc0;
199        let bytes = (high << 8) | low;
200        let cp = if bytes < 0x1f00 { bytes + 0x8140 } else { bytes + 0xc140 };
201        out.push((cp >> 8) as u8);
202        out.push((cp & 0xff) as u8);
203    }
204    Ok(())
205}
206
207#[cfg(test)]
208mod tests {
209    use super::{SaParseError, parse_sa_datastream};
210    use alloc::vec::Vec;
211    use qrcode_core::bits::Bits;
212    use qrcode_core::{EcLevel, Version};
213
214    /// Builds a single symbol's data stream (SA header + `data` via `push`) and
215    /// returns the bytes, mirroring what a decoder would recover.
216    fn sa_bytes<F>(position: u8, total: u8, parity: u8, push: F) -> Vec<u8>
217    where
218        F: FnOnce(&mut Bits),
219    {
220        let mut bits = Bits::new(Version::Normal(1));
221        bits.push_structured_append_header(position, total, parity).unwrap();
222        push(&mut bits);
223        bits.push_terminator(EcLevel::M).unwrap();
224        bits.into_bytes()
225    }
226
227    #[test]
228    fn header_only_parses_back() {
229        // v1.5.0 header vector: position 1, total 3, parity 0x5a, no data.
230        let bytes = sa_bytes(1, 3, 0x5a, |_| {});
231        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
232        assert_eq!(parsed.position, 1);
233        assert_eq!(parsed.total, 3);
234        assert_eq!(parsed.parity, 0x5a);
235        assert!(parsed.data.is_empty());
236    }
237
238    #[test]
239    fn value_16_decodes_from_max_nibble() {
240        let bytes = sa_bytes(16, 16, 0x00, |_| {});
241        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
242        assert_eq!(parsed.position, 16);
243        assert_eq!(parsed.total, 16);
244    }
245
246    #[test]
247    fn invalid_header_range_is_rejected() {
248        // Position nibble 1 means position 2, total nibble 0 means total 1.
249        let bytes = [0x31, 0x00, 0x00];
250        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
251    }
252
253    #[test]
254    fn byte_segment_round_trips() {
255        let bytes = sa_bytes(1, 2, 0x03, |b| {
256            b.push_byte_data(b"ab").unwrap();
257        });
258        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
259        assert_eq!(parsed.data, b"ab");
260    }
261
262    #[test]
263    fn numeric_segment_round_trips() {
264        let bytes = sa_bytes(1, 2, 0x00, |b| {
265            b.push_numeric_data(b"01234567").unwrap();
266        });
267        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
268        assert_eq!(parsed.data, b"01234567");
269    }
270
271    #[test]
272    fn alphanumeric_segment_round_trips() {
273        let bytes = sa_bytes(1, 2, 0x00, |b| {
274            b.push_alphanumeric_data(b"AC-42").unwrap();
275        });
276        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
277        assert_eq!(parsed.data, b"AC-42");
278    }
279
280    #[test]
281    fn invalid_alphanumeric_pair_is_rejected_without_panicking() {
282        let mut bytes = sa_bytes(1, 2, 0x00, |b| {
283            b.push_alphanumeric_data(b"AA").unwrap();
284        });
285        // The pair value starts after the 20-bit SA header, 4-bit mode, and
286        // 9-bit v1 character count. Set all 11 value bits to an invalid
287        // base-45 pair (2047 > 44 * 45 + 44).
288        for bit in 33..44 {
289            bytes[bit / 8] |= 1 << (7 - bit % 8);
290        }
291        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
292    }
293
294    #[test]
295    fn invalid_alphanumeric_single_is_rejected_without_panicking() {
296        let mut bytes = sa_bytes(1, 2, 0x00, |b| {
297            b.push_alphanumeric_data(b"A").unwrap();
298        });
299        // The single-character value starts after the 33-bit prefix above.
300        for bit in 33..39 {
301            bytes[bit / 8] |= 1 << (7 - bit % 8);
302        }
303        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
304    }
305
306    #[test]
307    fn kanji_segment_round_trips() {
308        let bytes = sa_bytes(1, 2, 0x00, |b| {
309            b.push_kanji_data(b"\x93\x5f\xe4\xaa").unwrap();
310        });
311        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
312        assert_eq!(parsed.data, b"\x93\x5f\xe4\xaa");
313    }
314
315    #[test]
316    fn non_structured_append_stream_is_rejected() {
317        // A plain byte-mode symbol — first mode is 0100, not 0011.
318        let mut bits = Bits::new(Version::Normal(1));
319        bits.push_byte_data(b"hello").unwrap();
320        bits.push_terminator(EcLevel::M).unwrap();
321        let bytes = bits.into_bytes();
322        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::NotStructuredAppend));
323    }
324
325    #[test]
326    fn truncated_stream_is_malformed() {
327        // Starts with the SA mode `0011`, but only 4 bits remain — not enough
328        // for the 8-bit symbol-sequence indicator.
329        assert_eq!(parse_sa_datastream(&[0b0011_0000], Version::Normal(1)), Err(SaParseError::MalformedStream));
330    }
331}