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        out.push(ALPHA_REV[v / 45]);
184        out.push(ALPHA_REV[v % 45]);
185        remaining -= 2;
186    }
187    if remaining == 1 {
188        let v = r.read_bits(6).ok_or(SaParseError::MalformedStream)? as usize;
189        out.push(ALPHA_REV[v]);
190    }
191    Ok(())
192}
193
194fn decode_kanji(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
195    let count = r.read_bits(Mode::Kanji.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
196    for _ in 0..count {
197        let n = r.read_bits(13).ok_or(SaParseError::MalformedStream)?;
198        let high = n / 0xc0;
199        let low = n % 0xc0;
200        let bytes = (high << 8) | low;
201        let cp = if bytes < 0x1f00 { bytes + 0x8140 } else { bytes + 0xc140 };
202        out.push((cp >> 8) as u8);
203        out.push((cp & 0xff) as u8);
204    }
205    Ok(())
206}
207
208#[cfg(test)]
209mod tests {
210    use super::{SaParseError, parse_sa_datastream};
211    use alloc::vec::Vec;
212    use qrcode_core::bits::Bits;
213    use qrcode_core::{EcLevel, Version};
214
215    /// Builds a single symbol's data stream (SA header + `data` via `push`) and
216    /// returns the bytes, mirroring what a decoder would recover.
217    fn sa_bytes<F>(position: u8, total: u8, parity: u8, push: F) -> Vec<u8>
218    where
219        F: FnOnce(&mut Bits),
220    {
221        let mut bits = Bits::new(Version::Normal(1));
222        bits.push_structured_append_header(position, total, parity).unwrap();
223        push(&mut bits);
224        bits.push_terminator(EcLevel::M).unwrap();
225        bits.into_bytes()
226    }
227
228    #[test]
229    fn header_only_parses_back() {
230        // v1.5.0 header vector: position 1, total 3, parity 0x5a, no data.
231        let bytes = sa_bytes(1, 3, 0x5a, |_| {});
232        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
233        assert_eq!(parsed.position, 1);
234        assert_eq!(parsed.total, 3);
235        assert_eq!(parsed.parity, 0x5a);
236        assert!(parsed.data.is_empty());
237    }
238
239    #[test]
240    fn value_16_decodes_from_zero_nibble() {
241        let bytes = sa_bytes(16, 16, 0x00, |_| {});
242        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
243        assert_eq!(parsed.position, 16);
244        assert_eq!(parsed.total, 16);
245    }
246
247    #[test]
248    fn byte_segment_round_trips() {
249        let bytes = sa_bytes(1, 2, 0x03, |b| {
250            b.push_byte_data(b"ab").unwrap();
251        });
252        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
253        assert_eq!(parsed.data, b"ab");
254    }
255
256    #[test]
257    fn numeric_segment_round_trips() {
258        let bytes = sa_bytes(1, 2, 0x00, |b| {
259            b.push_numeric_data(b"01234567").unwrap();
260        });
261        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
262        assert_eq!(parsed.data, b"01234567");
263    }
264
265    #[test]
266    fn alphanumeric_segment_round_trips() {
267        let bytes = sa_bytes(1, 2, 0x00, |b| {
268            b.push_alphanumeric_data(b"AC-42").unwrap();
269        });
270        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
271        assert_eq!(parsed.data, b"AC-42");
272    }
273
274    #[test]
275    fn kanji_segment_round_trips() {
276        let bytes = sa_bytes(1, 2, 0x00, |b| {
277            b.push_kanji_data(b"\x93\x5f\xe4\xaa").unwrap();
278        });
279        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
280        assert_eq!(parsed.data, b"\x93\x5f\xe4\xaa");
281    }
282
283    #[test]
284    fn non_structured_append_stream_is_rejected() {
285        // A plain byte-mode symbol — first mode is 0100, not 0011.
286        let mut bits = Bits::new(Version::Normal(1));
287        bits.push_byte_data(b"hello").unwrap();
288        bits.push_terminator(EcLevel::M).unwrap();
289        let bytes = bits.into_bytes();
290        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::NotStructuredAppend));
291    }
292
293    #[test]
294    fn truncated_stream_is_malformed() {
295        // Starts with the SA mode `0011`, but only 4 bits remain — not enough
296        // for the 8-bit symbol-sequence indicator.
297        assert_eq!(parse_sa_datastream(&[0b0011_0000], Version::Normal(1)), Err(SaParseError::MalformedStream));
298    }
299}