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::{EncodingMode, KanjiMode, 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 version is not a normal QR version
113/// in `1..=40`, the bits run out mid-field, a value is invalid for its mode, or
114/// a segment uses an unsupported mode (including ECI and FNC1), or a shortened
115/// terminator at the end of the stream contains non-zero bits.
116pub fn parse_sa_datastream(bits: &[u8], version: Version) -> Result<SaSymbolData, SaParseError> {
117    if !matches!(version, Version::Normal(1..=40)) {
118        return Err(SaParseError::MalformedStream);
119    }
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 = ((sequence >> 4) + 1) as u8;
128    let total = ((sequence & 0x0f) + 1) as u8;
129    if total < 2 || position > total {
130        return Err(SaParseError::MalformedStream);
131    }
132    let parity = r.read_bits(8).ok_or(SaParseError::MalformedStream)? as u8;
133
134    let mut data = Vec::new();
135    while r.remaining() >= 4 {
136        let segment_mode = r.read_bits(4).ok_or(SaParseError::MalformedStream)?;
137        match segment_mode {
138            // A full terminator ends the payload; retain the existing tolerance
139            // for any remaining alignment and pad bytes.
140            0b0000 => return Ok(SaSymbolData { position, total, parity, data }),
141            0b0001 => decode_numeric(&mut r, version, &mut data)?,
142            0b0010 => decode_alpha(&mut r, version, &mut data)?,
143            0b0100 => decode_byte(&mut r, version, &mut data)?,
144            0b1000 => decode_kanji(&mut r, version, &mut data)?,
145            // Unsupported modes must not make a partial payload look complete.
146            _ => return Err(SaParseError::MalformedStream),
147        }
148    }
149
150    // A normal QR terminator may be shortened when fewer than four bits remain.
151    // Non-zero residual bits instead indicate a truncated next mode indicator.
152    let remaining = r.remaining();
153    if r.read_bits(remaining) != Some(0) {
154        return Err(SaParseError::MalformedStream);
155    }
156
157    Ok(SaSymbolData { position, total, parity, data })
158}
159
160fn decode_byte(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
161    let count = r.read_bits(Mode::Byte.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
162    for _ in 0..count {
163        let byte = r.read_bits(8).ok_or(SaParseError::MalformedStream)? as u8;
164        out.push(byte);
165    }
166    Ok(())
167}
168
169fn decode_numeric(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
170    let mut remaining =
171        r.read_bits(Mode::Numeric.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
172    while remaining >= 3 {
173        let v = r.read_bits(10).ok_or(SaParseError::MalformedStream)?;
174        if v >= 1000 {
175            return Err(SaParseError::MalformedStream);
176        }
177        out.push(b'0' + (v / 100) as u8);
178        out.push(b'0' + ((v / 10) % 10) as u8);
179        out.push(b'0' + (v % 10) as u8);
180        remaining -= 3;
181    }
182    if remaining == 2 {
183        let v = r.read_bits(7).ok_or(SaParseError::MalformedStream)?;
184        if v >= 100 {
185            return Err(SaParseError::MalformedStream);
186        }
187        out.push(b'0' + (v / 10) as u8);
188        out.push(b'0' + (v % 10) as u8);
189    } else if remaining == 1 {
190        let v = r.read_bits(4).ok_or(SaParseError::MalformedStream)?;
191        if v >= 10 {
192            return Err(SaParseError::MalformedStream);
193        }
194        out.push(b'0' + v as u8);
195    }
196    Ok(())
197}
198
199fn decode_alpha(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
200    let mut remaining =
201        r.read_bits(Mode::Alphanumeric.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
202    while remaining >= 2 {
203        let v = r.read_bits(11).ok_or(SaParseError::MalformedStream)? as usize;
204        let first = ALPHA_REV.get(v / 45).ok_or(SaParseError::MalformedStream)?;
205        let second = ALPHA_REV.get(v % 45).ok_or(SaParseError::MalformedStream)?;
206        out.push(*first);
207        out.push(*second);
208        remaining -= 2;
209    }
210    if remaining == 1 {
211        let v = r.read_bits(6).ok_or(SaParseError::MalformedStream)? as usize;
212        out.push(*ALPHA_REV.get(v).ok_or(SaParseError::MalformedStream)?);
213    }
214    Ok(())
215}
216
217fn decode_kanji(r: &mut BitReader<'_>, version: Version, out: &mut Vec<u8>) -> Result<(), SaParseError> {
218    let count = r.read_bits(Mode::Kanji.length_bits_count(version)).ok_or(SaParseError::MalformedStream)? as usize;
219    for _ in 0..count {
220        let n = r.read_bits(13).ok_or(SaParseError::MalformedStream)?;
221        let high = n / 0xc0;
222        let low = n % 0xc0;
223        let bytes = (high << 8) | low;
224        let cp = if bytes < 0x1f00 { bytes + 0x8140 } else { bytes + 0xc140 };
225        let pair = [(cp >> 8) as u8, (cp & 0xff) as u8];
226        if !KanjiMode::validate(&pair) {
227            return Err(SaParseError::MalformedStream);
228        }
229        out.extend_from_slice(&pair);
230    }
231    Ok(())
232}
233
234#[cfg(test)]
235mod tests {
236    use super::{SaParseError, parse_sa_datastream};
237    use alloc::vec::Vec;
238    use qrcode_core::bits::Bits;
239    use qrcode_core::{EcLevel, EncodingMode, KanjiMode, Version};
240
241    /// Builds a single symbol's data stream (SA header + `data` via `push`) and
242    /// returns the bytes, mirroring what a decoder would recover.
243    fn sa_bytes<F>(position: u8, total: u8, parity: u8, push: F) -> Vec<u8>
244    where
245        F: FnOnce(&mut Bits),
246    {
247        let mut bits = Bits::new(Version::Normal(1));
248        bits.push_structured_append_header(position, total, parity).unwrap();
249        push(&mut bits);
250        bits.push_terminator(EcLevel::M).unwrap();
251        bits.into_bytes()
252    }
253
254    #[test]
255    fn header_only_parses_back() {
256        // v1.5.0 header vector: position 1, total 3, parity 0x5a, no data.
257        let bytes = sa_bytes(1, 3, 0x5a, |_| {});
258        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
259        assert_eq!(parsed.position, 1);
260        assert_eq!(parsed.total, 3);
261        assert_eq!(parsed.parity, 0x5a);
262        assert!(parsed.data.is_empty());
263    }
264
265    #[test]
266    fn value_16_decodes_from_max_nibble() {
267        let bytes = sa_bytes(16, 16, 0x00, |_| {});
268        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
269        assert_eq!(parsed.position, 16);
270        assert_eq!(parsed.total, 16);
271    }
272
273    #[test]
274    fn invalid_header_range_is_rejected() {
275        // Position nibble 1 means position 2, total nibble 0 means total 1.
276        let bytes = [0x31, 0x00, 0x00];
277        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
278    }
279
280    #[test]
281    fn byte_segment_round_trips() {
282        let bytes = sa_bytes(1, 2, 0x03, |b| {
283            b.push_byte_data(b"ab").unwrap();
284        });
285        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
286        assert_eq!(parsed.data, b"ab");
287    }
288
289    #[test]
290    fn numeric_segment_round_trips() {
291        let bytes = sa_bytes(1, 2, 0x00, |b| {
292            b.push_numeric_data(b"01234567").unwrap();
293        });
294        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
295        assert_eq!(parsed.data, b"01234567");
296    }
297
298    #[test]
299    fn alphanumeric_segment_round_trips() {
300        let bytes = sa_bytes(1, 2, 0x00, |b| {
301            b.push_alphanumeric_data(b"AC-42").unwrap();
302        });
303        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
304        assert_eq!(parsed.data, b"AC-42");
305    }
306
307    #[test]
308    fn invalid_alphanumeric_pair_is_rejected_without_panicking() {
309        let mut bytes = sa_bytes(1, 2, 0x00, |b| {
310            b.push_alphanumeric_data(b"AA").unwrap();
311        });
312        // The pair value starts after the 20-bit SA header, 4-bit mode, and
313        // 9-bit v1 character count. Set all 11 value bits to an invalid
314        // base-45 pair (2047 > 44 * 45 + 44).
315        for bit in 33..44 {
316            bytes[bit / 8] |= 1 << (7 - bit % 8);
317        }
318        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
319    }
320
321    #[test]
322    fn invalid_alphanumeric_single_is_rejected_without_panicking() {
323        let mut bytes = sa_bytes(1, 2, 0x00, |b| {
324            b.push_alphanumeric_data(b"A").unwrap();
325        });
326        // The single-character value starts after the 33-bit prefix above.
327        for bit in 33..39 {
328            bytes[bit / 8] |= 1 << (7 - bit % 8);
329        }
330        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
331    }
332
333    #[test]
334    fn kanji_segment_round_trips() {
335        let bytes = sa_bytes(1, 2, 0x00, |b| {
336            b.push_kanji_data(b"\x93\x5f\xe4\xaa").unwrap();
337        });
338        let parsed = parse_sa_datastream(&bytes, Version::Normal(1)).unwrap();
339        assert_eq!(parsed.data, b"\x93\x5f\xe4\xaa");
340    }
341
342    #[test]
343    fn non_structured_append_stream_is_rejected() {
344        // A plain byte-mode symbol — first mode is 0100, not 0011.
345        let mut bits = Bits::new(Version::Normal(1));
346        bits.push_byte_data(b"hello").unwrap();
347        bits.push_terminator(EcLevel::M).unwrap();
348        let bytes = bits.into_bytes();
349        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::NotStructuredAppend));
350    }
351
352    #[test]
353    fn truncated_stream_is_malformed() {
354        // Starts with the SA mode `0011`, but only 4 bits remain — not enough
355        // for the 8-bit symbol-sequence indicator.
356        assert_eq!(parse_sa_datastream(&[0b0011_0000], Version::Normal(1)), Err(SaParseError::MalformedStream));
357    }
358
359    #[test]
360    fn numeric_values_outside_their_decimal_width_are_rejected() {
361        // SA header (position 1 of 2), Numeric mode, count 3 / 2 / 1,
362        // then the largest 10 / 7 / 4-bit value instead of decimal digits.
363        for bytes in [
364            &[0x30, 0x10, 0x01, 0x00, 0xff, 0xf0][..],
365            &[0x30, 0x10, 0x01, 0x00, 0xbf, 0x80][..],
366            &[0x30, 0x10, 0x01, 0x00, 0x7c, 0x00][..],
367        ] {
368            assert_eq!(parse_sa_datastream(bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
369        }
370    }
371
372    #[test]
373    fn largest_valid_numeric_values_round_trip() {
374        for data in [b"999".as_slice(), b"99", b"9"] {
375            let bytes = sa_bytes(1, 2, 0x00, |bits| {
376                bits.push_numeric_data(data).unwrap();
377            });
378            assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)).unwrap().data, data);
379        }
380    }
381
382    #[test]
383    fn unsupported_modes_do_not_return_a_partial_payload() {
384        for mode in [0b0011, 0b0101, 0b0110, 0b0111, 0b1001, 0b1111] {
385            let mut bytes = sa_bytes(1, 2, 0x00, |bits| {
386                bits.push_byte_data(b"a").unwrap();
387            });
388            // Replace the terminator immediately after the byte payload with
389            // an unsupported mode, leaving a valid decoded prefix before it.
390            bytes[5] = mode << 4;
391            assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
392        }
393    }
394
395    #[test]
396    fn invalid_or_micro_versions_are_rejected_before_reading_counts() {
397        let bytes = sa_bytes(1, 2, 0x00, |bits| {
398            bits.push_numeric_data(b"123").unwrap();
399        });
400        for version in [
401            Version::Normal(0),
402            Version::Normal(41),
403            Version::Normal(i16::MIN),
404            Version::Normal(i16::MAX),
405            Version::Micro(-1),
406            Version::Micro(1),
407            Version::Micro(4),
408        ] {
409            assert_eq!(parse_sa_datastream(&bytes, version), Err(SaParseError::MalformedStream));
410        }
411    }
412
413    #[test]
414    fn all_data_modes_round_trip_across_normal_version_count_tiers() {
415        let expected = b"0123AC-\xff\x93\x5f\xe4\xaa";
416        for number in [1, 9, 10, 26, 27, 40] {
417            let version = Version::Normal(number);
418            let mut bits = Bits::new(version);
419            bits.push_structured_append_header(2, 3, 0x5a).unwrap();
420            bits.push_numeric_data(b"0123").unwrap();
421            bits.push_alphanumeric_data(b"AC-").unwrap();
422            bits.push_byte_data(b"\xff").unwrap();
423            bits.push_kanji_data(b"\x93\x5f\xe4\xaa").unwrap();
424            bits.push_terminator(EcLevel::L).unwrap();
425
426            let parsed = parse_sa_datastream(&bits.into_bytes(), version).unwrap();
427            assert_eq!(parsed.position, 2, "version {number}");
428            assert_eq!(parsed.total, 3, "version {number}");
429            assert_eq!(parsed.parity, 0x5a, "version {number}");
430            assert_eq!(parsed.data, expected, "version {number}");
431        }
432    }
433
434    #[test]
435    fn a_truncated_next_mode_does_not_return_an_incomplete_payload() {
436        // SA header, Numeric "1", Byte "b", terminator. The Numeric payload
437        // ends at bit 38, so taking five bytes leaves the next mode's "01".
438        let complete = [0x30, 0x10, 0x01, 0x00, 0x45, 0x00, 0x58, 0x80];
439        assert_eq!(parse_sa_datastream(&complete, Version::Normal(1)).unwrap().data, b"1b");
440        let truncated = [0x30, 0x10, 0x01, 0x00, 0x45];
441        assert_eq!(truncated.as_slice(), &complete[..5]);
442        assert_eq!(parse_sa_datastream(&truncated, Version::Normal(1)), Err(SaParseError::MalformedStream));
443    }
444
445    #[test]
446    fn shortened_terminators_accept_only_zero_bits() {
447        let cases = [
448            (sa_bytes(1, 2, 0, |bits| bits.push_alphanumeric_data(b"A").unwrap()), 5, b"A".as_slice()),
449            (sa_bytes(1, 2, 0, |bits| bits.push_numeric_data(b"1").unwrap()), 5, b"1".as_slice()),
450            (sa_bytes(1, 2, 0, |bits| bits.push_kanji_data(b"\x93\x5f").unwrap()), 6, b"\x93\x5f".as_slice()),
451        ];
452        // These data segments leave respectively one, two, and three bits at
453        // the end of their last byte. Preserve each all-zero shortened ending.
454        for (mut bytes, length, expected) in cases {
455            bytes.truncate(length);
456            assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)).unwrap().data, expected);
457            *bytes.last_mut().unwrap() |= 1;
458            assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
459        }
460    }
461
462    #[test]
463    fn a_full_terminator_preserves_tolerance_for_trailing_padding() {
464        let mut bytes = sa_bytes(1, 2, 0, |bits| bits.push_byte_data(b"a").unwrap());
465        // The four-bit terminator starts at bit 40. Leave it intact and replace
466        // every following alignment/pad bit with one.
467        bytes[5] |= 0x0f;
468        bytes[6..].fill(0xff);
469        assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)).unwrap().data, b"a");
470    }
471
472    #[test]
473    fn reserved_kanji_values_outside_encoder_ranges_are_malformed() {
474        for bytes in [
475            [0x30, 0x10, 0x08, 0x01, 0xb9, 0xe8, 0x00],
476            [0x30, 0x10, 0x08, 0x01, 0xb9, 0xf0, 0x00],
477            [0x30, 0x10, 0x08, 0x01, 0xb9, 0xf8, 0x00],
478        ] {
479            // Values 5949 / 5950 / 5951 would produce 9FFD / 9FFE / 9FFF.
480            assert_eq!(parse_sa_datastream(&bytes, Version::Normal(1)), Err(SaParseError::MalformedStream));
481        }
482    }
483
484    #[test]
485    fn every_kanji_value_matches_the_existing_core_encoder_contract() {
486        for value in 0_u16..=8191 {
487            let bytes = [0x30, 0x10, 0x08, 0x01, (value >> 5) as u8, (value << 3) as u8, 0x00];
488            let parsed = parse_sa_datastream(&bytes, Version::Normal(1));
489            if (5949..=5951).contains(&value) {
490                assert_eq!(parsed, Err(SaParseError::MalformedStream));
491                continue;
492            }
493            let parsed = parsed.unwrap();
494            assert!(KanjiMode::validate(&parsed.data), "Kanji value {value}");
495            let mut encoded = Bits::new(Version::Normal(1));
496            encoded.push_structured_append_header(1, 2, 0).unwrap();
497            encoded.push_kanji_data(&parsed.data).unwrap();
498            assert_eq!(encoded.into_bytes(), &bytes[..6], "Kanji value {value}");
499        }
500    }
501}