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/// Decodes a 4-bit Structured Append nibble: `0` means 16, anything else is the
101/// value itself (the only encoding of 16 in four bits).
102fn nibble_to_value(nibble: u32) -> u8 {
103    if nibble == 0 { 16 } else { nibble as u8 }
104}
105
106/// Parses a Structured Append data bit stream into its header and payload.
107///
108/// `bits` is one symbol's data region (as recovered by a decoder); `version`
109/// sets the character-count bit widths used by each data segment. The function
110/// reads the 20-bit Structured Append header, then decodes Numeric /
111/// Alphanumeric / Byte / Kanji segments until the terminator, returning the
112/// recovered bytes.
113///
114/// # Errors
115///
116/// Returns [`SaParseError::NotStructuredAppend`] if the stream does not begin
117/// with the Structured Append mode indicator (`0011`), or
118/// [`SaParseError::MalformedStream`] if the bits run out mid-field.
119pub fn parse_sa_datastream(bits: &[u8], version: Version) -> Result<SaSymbolData, SaParseError> {
120    let mut r = BitReader::new(bits);
121
122    let mode = r.read_bits(4).ok_or(SaParseError::MalformedStream)?;
123    if mode != 0b0011 {
124        return Err(SaParseError::NotStructuredAppend);
125    }
126    let sequence = r.read_bits(8).ok_or(SaParseError::MalformedStream)?;
127    let position = nibble_to_value(sequence >> 4);
128    let total = nibble_to_value(sequence & 0x0f);
129    let parity = r.read_bits(8).ok_or(SaParseError::MalformedStream)? as u8;
130
131    let mut data = Vec::new();
132    while r.remaining() >= 4 {
133        let segment_mode = r.read_bits(4).ok_or(SaParseError::MalformedStream)?;
134        match segment_mode {
135            0b0000 => break, // terminator
136            0b0001 => decode_numeric(&mut r, version, &mut data)?,
137            0b0010 => decode_alpha(&mut r, version, &mut data)?,
138            0b0100 => decode_byte(&mut r, version, &mut data)?,
139            0b1000 => decode_kanji(&mut r, version, &mut data)?,
140            // FNC1 / ECI / unknown — stop with the payload parsed so far.
141            _ => break,
142        }
143    }
144
145    Ok(SaSymbolData { position, total, parity, data })
146}
147
148fn decode_byte(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
149    let count = r.read_bits(Mode::Byte.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
150    for _ in 0..count {
151        let byte = r.read_bits(8).ok_or(SaParseError::MalformedStream)? as u8;
152        out.push(byte);
153    }
154    Ok(())
155}
156
157fn decode_numeric(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
158    let mut remaining =
159        r.read_bits(Mode::Numeric.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
160    while remaining >= 3 {
161        let v = r.read_bits(10).ok_or(SaParseError::MalformedStream)?;
162        out.push(b'0' + (v / 100) as u8);
163        out.push(b'0' + ((v / 10) % 10) as u8);
164        out.push(b'0' + (v % 10) as u8);
165        remaining -= 3;
166    }
167    if remaining == 2 {
168        let v = r.read_bits(7).ok_or(SaParseError::MalformedStream)?;
169        out.push(b'0' + (v / 10) as u8);
170        out.push(b'0' + (v % 10) as u8);
171    } else if remaining == 1 {
172        let v = r.read_bits(4).ok_or(SaParseError::MalformedStream)?;
173        out.push(b'0' + v as u8);
174    }
175    Ok(())
176}
177
178fn decode_alpha(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
179    let mut remaining =
180        r.read_bits(Mode::Alphanumeric.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
181    while remaining >= 2 {
182        let v = r.read_bits(11).ok_or(SaParseError::MalformedStream)? as usize;
183        let first = ALPHA_REV.get(v / 45).ok_or(SaParseError::MalformedStream)?;
184        let second = ALPHA_REV.get(v % 45).ok_or(SaParseError::MalformedStream)?;
185        out.push(*first);
186        out.push(*second);
187        remaining -= 2;
188    }
189    if remaining == 1 {
190        let v = r.read_bits(6).ok_or(SaParseError::MalformedStream)? as usize;
191        out.push(*ALPHA_REV.get(v).ok_or(SaParseError::MalformedStream)?);
192    }
193    Ok(())
194}
195
196fn decode_kanji(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
197    let count = r.read_bits(Mode::Kanji.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
198    for _ in 0..count {
199        let n = r.read_bits(13).ok_or(SaParseError::MalformedStream)?;
200        let high = n / 0xc0;
201        let low = n % 0xc0;
202        let bytes = (high << 8) | low;
203        let cp = if bytes < 0x1f00 { bytes + 0x8140 } else { bytes + 0xc140 };
204        out.push((cp >> 8) as u8);
205        out.push((cp & 0xff) as u8);
206    }
207    Ok(())
208}
209
210#[cfg(test)]
211mod tests {
212    use super::{SaParseError, parse_sa_datastream};
213    use alloc::vec::Vec;
214    use qrcode_core::bits::Bits;
215    use qrcode_core::{EcLevel, Version};
216
217    /// Builds a single symbol's data stream (SA header + `data` via `push`) and
218    /// returns the bytes, mirroring what a decoder would recover.
219    fn sa_bytes<F>(position: u8, total: u8, parity: u8, push: F) -> Vec<u8>
220    where
221        F: FnOnce(&mut Bits),
222    {
223        let mut bits = Bits::new(Version::Normal(1));
224        bits.push_structured_append_header(position, total, parity).unwrap();
225        push(&mut bits);
226        bits.push_terminator(EcLevel::M).unwrap();
227        bits.into_bytes()
228    }
229
230    #[test]
231    fn header_only_parses_back() {
232        // v1.5.0 header vector: position 1, total 3, parity 0x5a, no data.
233        let bytes = sa_bytes(1, 3, 0x5a, |_| {});
234        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
235        assert_eq!(parsed.position, 1);
236        assert_eq!(parsed.total, 3);
237        assert_eq!(parsed.parity, 0x5a);
238        assert!(parsed.data.is_empty());
239    }
240
241    #[test]
242    fn value_16_decodes_from_zero_nibble() {
243        let bytes = sa_bytes(16, 16, 0x00, |_| {});
244        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
245        assert_eq!(parsed.position, 16);
246        assert_eq!(parsed.total, 16);
247    }
248
249    #[test]
250    fn byte_segment_round_trips() {
251        let bytes = sa_bytes(1, 2, 0x03, |b| {
252            b.push_byte_data(b"ab").unwrap();
253        });
254        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
255        assert_eq!(parsed.data, b"ab");
256    }
257
258    #[test]
259    fn numeric_segment_round_trips() {
260        let bytes = sa_bytes(1, 2, 0x00, |b| {
261            b.push_numeric_data(b"01234567").unwrap();
262        });
263        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
264        assert_eq!(parsed.data, b"01234567");
265    }
266
267    #[test]
268    fn alphanumeric_segment_round_trips() {
269        let bytes = sa_bytes(1, 2, 0x00, |b| {
270            b.push_alphanumeric_data(b"AC-42").unwrap();
271        });
272        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
273        assert_eq!(parsed.data, b"AC-42");
274    }
275
276    #[test]
277    fn invalid_alphanumeric_pair_is_rejected_without_panicking() {
278        let mut bytes = sa_bytes(1, 2, 0x00, |b| {
279            b.push_alphanumeric_data(b"AA").unwrap();
280        });
281        // The pair value starts after the 20-bit SA header, 4-bit mode, and
282        // 9-bit v1 character count. Set all 11 value bits to an invalid
283        // base-45 pair (2047 > 44 * 45 + 44).
284        for bit in 33..44 {
285            bytes[bit / 8] |= 1 << (7 - bit % 8);
286        }
287        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
288    }
289
290    #[test]
291    fn invalid_alphanumeric_single_is_rejected_without_panicking() {
292        let mut bytes = sa_bytes(1, 2, 0x00, |b| {
293            b.push_alphanumeric_data(b"A").unwrap();
294        });
295        // The single-character value starts after the 33-bit prefix above.
296        for bit in 33..39 {
297            bytes[bit / 8] |= 1 << (7 - bit % 8);
298        }
299        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
300    }
301
302    #[test]
303    fn kanji_segment_round_trips() {
304        let bytes = sa_bytes(1, 2, 0x00, |b| {
305            b.push_kanji_data(b"\x93\x5f\xe4\xaa").unwrap();
306        });
307        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
308        assert_eq!(parsed.data, b"\x93\x5f\xe4\xaa");
309    }
310
311    #[test]
312    fn non_structured_append_stream_is_rejected() {
313        // A plain byte-mode symbol — first mode is 0100, not 0011.
314        let mut bits = Bits::new(Version::Normal(1));
315        bits.push_byte_data(b"hello").unwrap();
316        bits.push_terminator(EcLevel::M).unwrap();
317        let bytes = bits.into_bytes();
318        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::NotStructuredAppend));
319    }
320
321    #[test]
322    fn truncated_stream_is_malformed() {
323        // Starts with the SA mode `0011`, but only 4 bits remain — not enough
324        // for the 8-bit symbol-sequence indicator.
325        assert_eq!(parse_sa_datastream(&[0b0011_0000], Version::Normal(1)), Err(SaParseError::MalformedStream));
326    }
327}