Skip to main content

qrcode_decode/
lib.rs

1//! QR code decoding (scan-to-data).
2//!
3//! This module defines the [`QrDecoder`] trait and the value types a decoder
4//! returns ([`DecodedQrCode`]). The trait takes a borrowed grayscale view
5//! ([`GrayPixels`]) so it stays decoupled from the `image` crate: a decoder
6//! working from a camera frame or an embedded framebuffer can implement
7//! [`QrDecoder`] without pulling in `image`.
8//!
9//! Encoding is the primary mission of this crate; decoding is bridged via an
10//! opt-in adapter (see the `rqrr` feature). Implementing [`QrDecoder`]
11//! for your own decoder is always available.
12
13#![cfg_attr(not(feature = "std"), no_std)]
14#![deny(missing_docs)]
15
16extern crate alloc;
17
18#[cfg(not(feature = "std"))]
19#[allow(unused_imports)]
20use alloc::vec::Vec;
21
22use core::fmt;
23use qrcode_core::{EcLevel, Version};
24
25#[cfg(feature = "rxing")]
26mod engine;
27#[cfg(feature = "rqrr")]
28pub mod rqrr;
29#[cfg(feature = "rxing")]
30pub mod rxing;
31#[cfg(feature = "rxing")]
32pub use rxing::{ScanSymbol, StructuredAppendHeader};
33pub mod sa_parse;
34
35/// Errors returned when validating a [`GrayPixels`] buffer.
36#[non_exhaustive]
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum GrayPixelsError {
39    /// The image dimensions exceed the byte-slice size supported by this target.
40    DimensionsOverflow,
41    /// The buffer does not contain exactly one byte per pixel.
42    BufferLengthMismatch {
43        /// Required byte count for the supplied dimensions.
44        expected: usize,
45        /// Actual byte count in the supplied buffer.
46        actual: usize,
47    },
48}
49
50impl fmt::Display for GrayPixelsError {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::DimensionsOverflow => f.write_str("grayscale image dimensions exceed the supported buffer size"),
54            Self::BufferLengthMismatch { expected, actual } => {
55                write!(f, "grayscale buffer length mismatch: expected {expected} bytes, got {actual}")
56            }
57        }
58    }
59}
60
61impl ::core::error::Error for GrayPixelsError {}
62
63/// A borrowed grayscale (luma) pixel view: the universal input to a
64/// [`QrDecoder`].
65///
66/// One byte per pixel, row-major, `0` = black / `255` = white. Decoupled from
67/// the `image` crate so custom decoders need no image dependency.
68#[non_exhaustive]
69#[derive(Debug, Clone, Copy)]
70pub struct GrayPixels<'a> {
71    /// Image width in pixels.
72    width: u32,
73    /// Image height in pixels.
74    height: u32,
75    /// Row-major luma bytes (`len == width * height`).
76    data: &'a [u8],
77}
78
79impl<'a> GrayPixels<'a> {
80    /// Creates a view over `data` (which must hold `width * height` bytes).
81    #[must_use]
82    pub fn new(width: u32, height: u32, data: &'a [u8]) -> Self {
83        Self { width, height, data }
84    }
85
86    /// Creates a view after validating its dimensions and buffer length.
87    ///
88    /// Zero-area dimensions are accepted when the buffer is empty. A decoder
89    /// may require a non-empty image even when this view is valid.
90    ///
91    /// # Errors
92    ///
93    /// Returns [`GrayPixelsError::DimensionsOverflow`] if the pixel count cannot
94    /// be represented by a byte slice on this target, or
95    /// [`GrayPixelsError::BufferLengthMismatch`] if `data.len()` differs from
96    /// `width * height`.
97    pub fn try_new(width: u32, height: u32, data: &'a [u8]) -> Result<Self, GrayPixelsError> {
98        let expected = u64::from(width)
99            .checked_mul(u64::from(height))
100            .and_then(|length| usize::try_from(length).ok())
101            .filter(|&length| length <= isize::MAX as usize)
102            .ok_or(GrayPixelsError::DimensionsOverflow)?;
103        if data.len() != expected {
104            return Err(GrayPixelsError::BufferLengthMismatch { expected, actual: data.len() });
105        }
106        Ok(Self::new(width, height, data))
107    }
108
109    /// The image width in pixels.
110    #[must_use]
111    pub const fn width(&self) -> u32 {
112        self.width
113    }
114
115    /// The image height in pixels.
116    #[must_use]
117    pub const fn height(&self) -> u32 {
118        self.height
119    }
120
121    /// The luma byte at `(x, y)` (`0` = black, `255` = white).
122    ///
123    /// # Panics
124    ///
125    /// Panics if `(x, y)` is out of bounds.
126    #[must_use]
127    pub fn get(&self, x: u32, y: u32) -> u8 {
128        assert!(x < self.width && y < self.height, "grayscale pixel coordinates are out of bounds");
129        self.data[(y as usize) * (self.width as usize) + (x as usize)]
130    }
131
132    /// Returns the luma byte at `(x, y)` without panicking.
133    ///
134    /// Returns `None` when the coordinates are out of bounds, their index cannot
135    /// be represented, or a view constructed with [`Self::new`] has no byte for
136    /// that pixel.
137    #[must_use]
138    pub fn try_get(&self, x: u32, y: u32) -> Option<u8> {
139        if x >= self.width || y >= self.height {
140            return None;
141        }
142        let width = usize::try_from(self.width).ok()?;
143        let x = usize::try_from(x).ok()?;
144        let y = usize::try_from(y).ok()?;
145        let index = y.checked_mul(width)?.checked_add(x)?;
146        self.data.get(index).copied()
147    }
148}
149
150#[cfg(feature = "image")]
151impl<'a> From<&'a image::GrayImage> for GrayPixels<'a> {
152    fn from(img: &'a image::GrayImage) -> Self {
153        let (width, height) = (img.width(), img.height());
154        // ImageBuffer validates the logical area but permits excess backing bytes.
155        let logical_len = width as usize * height as usize;
156        Self::new(width, height, &img.as_raw()[..logical_len])
157    }
158}
159
160/// A QR code recovered from an image by a [`QrDecoder`].
161///
162/// `#[non_exhaustive]`: fields may grow in 1.x (e.g. encoding mode, mask,
163/// position) without a breaking change; construct via [`DecodedQrCode::new`]
164/// and read via the accessors.
165#[non_exhaustive]
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct DecodedQrCode {
168    /// The decoded payload bytes.
169    data: Vec<u8>,
170    /// The QR version.
171    version: Version,
172    /// The error-correction level.
173    ec_level: EcLevel,
174}
175
176impl DecodedQrCode {
177    /// Creates a decoded QR code from its recovered fields.
178    #[must_use]
179    pub fn new(data: Vec<u8>, version: Version, ec_level: EcLevel) -> Self {
180        Self { data, version, ec_level }
181    }
182
183    /// The decoded payload bytes.
184    #[must_use]
185    pub fn data(&self) -> &[u8] {
186        &self.data
187    }
188
189    /// Consumes the decoded QR code and transfers its payload buffer without
190    /// copying or allocating. The returned bytes may contain arbitrary binary
191    /// data, including non-UTF-8 values.
192    #[must_use]
193    pub fn into_data(self) -> Vec<u8> {
194        self.data
195    }
196
197    /// The QR version.
198    #[must_use]
199    pub fn version(&self) -> Version {
200        self.version
201    }
202
203    /// The error-correction level.
204    #[must_use]
205    pub fn ec_level(&self) -> EcLevel {
206        self.ec_level
207    }
208}
209
210/// A QR code decoder: turns a grayscale image back into data.
211///
212/// Implement this for your own decoder (e.g. wrapping a native binding); use
213/// the bundled `RqrrDecoder` (behind the `rqrr` feature) for the
214/// `rqrr` crate.
215///
216/// `decode` returns a [`Vec`] because an image may contain more than one QR
217/// code; the order is decoder-defined.
218pub trait QrDecoder {
219    /// The error type returned on failure.
220    type Error;
221
222    /// Decodes all QR codes found in `image`.
223    ///
224    /// # Errors
225    ///
226    /// Returns `Self::Error` if decoding fails.
227    fn decode(&self, image: GrayPixels<'_>) -> Result<Vec<DecodedQrCode>, Self::Error>;
228}
229
230#[cfg(test)]
231mod tests {
232    use super::{DecodedQrCode, GrayPixels, GrayPixelsError};
233    use alloc::vec::Vec;
234    use qrcode_core::{EcLevel, Version};
235
236    #[test]
237    fn consuming_decoded_payload_transfers_the_binary_buffer_and_capacity() {
238        let mut payload = Vec::with_capacity(32);
239        payload.extend_from_slice(&[0x00, 0xff, 0x80, 0x11, 0x00]);
240        let pointer = payload.as_ptr();
241        let capacity = payload.capacity();
242        let decoded = DecodedQrCode::new(payload, Version::Normal(7), EcLevel::Q);
243
244        let bytes = decoded.into_data();
245        assert_eq!(bytes, [0x00, 0xff, 0x80, 0x11, 0x00]);
246        assert_eq!(bytes.as_ptr(), pointer);
247        assert_eq!(bytes.capacity(), capacity);
248    }
249
250    #[cfg(feature = "image")]
251    #[test]
252    fn gray_image_conversion_borrows_only_logical_pixels_from_padded_storage() {
253        let image = image::GrayImage::from_raw(2, 2, Vec::from([1, 2, 3, 4, 99, 100, 101])).unwrap();
254        let pixels = GrayPixels::from(&image);
255
256        assert_eq!((pixels.width(), pixels.height()), (2, 2));
257        assert_eq!(pixels.data, [1, 2, 3, 4]);
258        assert_eq!(pixels.data.as_ptr(), image.as_raw().as_ptr());
259        assert!(GrayPixels::try_new(pixels.width(), pixels.height(), pixels.data).is_ok());
260        assert_eq!(pixels.try_get(1, 1), Some(4));
261    }
262
263    #[cfg(feature = "image")]
264    #[test]
265    fn gray_image_conversion_borrows_an_empty_prefix_for_zero_area_padded_storage() {
266        for (width, height) in [(0, 0), (0, 7), (7, 0), (0, u32::MAX), (u32::MAX, 0)] {
267            let image = image::GrayImage::from_raw(width, height, Vec::from([99, 100, 101])).unwrap();
268            let pixels = GrayPixels::from(&image);
269
270            assert_eq!((pixels.width(), pixels.height()), (width, height));
271            assert!(pixels.data.is_empty());
272            assert_eq!(pixels.data.as_ptr(), image.as_raw().as_ptr());
273            assert!(GrayPixels::try_new(width, height, pixels.data).is_ok());
274        }
275    }
276
277    #[test]
278    fn grayscale_pixels_use_row_major_coordinates() {
279        let pixels = GrayPixels::new(2, 2, &[1, 2, 3, 4]);
280        assert_eq!(pixels.get(0, 0), 1);
281        assert_eq!(pixels.get(1, 0), 2);
282        assert_eq!(pixels.get(0, 1), 3);
283        assert_eq!(pixels.get(1, 1), 4);
284    }
285
286    #[test]
287    #[should_panic(expected = "grayscale pixel coordinates are out of bounds")]
288    fn grayscale_x_coordinate_cannot_alias_the_next_row() {
289        let _ = GrayPixels::new(2, 2, &[1, 2, 3, 4]).get(2, 0);
290    }
291
292    #[test]
293    #[should_panic(expected = "grayscale pixel coordinates are out of bounds")]
294    fn grayscale_y_coordinate_cannot_read_outside_the_image() {
295        let _ = GrayPixels::new(2, 2, &[1, 2, 3, 4]).get(0, 2);
296    }
297
298    #[test]
299    #[should_panic(expected = "grayscale pixel coordinates are out of bounds")]
300    fn empty_grayscale_image_has_no_valid_coordinates() {
301        let _ = GrayPixels::new(0, 0, &[]).get(0, 0);
302    }
303
304    #[test]
305    fn checked_grayscale_view_and_pixel_access_use_the_same_coordinates() {
306        let pixels = GrayPixels::try_new(2, 2, &[1, 2, 3, 4]).unwrap();
307        for y in 0..2 {
308            for x in 0..2 {
309                assert_eq!(pixels.try_get(x, y), Some(pixels.get(x, y)));
310            }
311        }
312        assert_eq!(pixels.try_get(2, 0), None);
313        assert_eq!(pixels.try_get(0, 2), None);
314        assert_eq!(pixels.try_get(u32::MAX, u32::MAX), None);
315    }
316
317    #[test]
318    fn checked_grayscale_view_rejects_short_and_long_buffers() {
319        for (data, actual) in [(&[1, 2, 3][..], 3), (&[1, 2, 3, 4, 5][..], 5)] {
320            assert!(matches!(
321                GrayPixels::try_new(2, 2, data),
322                Err(GrayPixelsError::BufferLengthMismatch { expected: 4, actual: length }) if length == actual
323            ));
324        }
325    }
326
327    #[test]
328    fn checked_grayscale_view_accepts_empty_buffers_for_zero_area() {
329        for (width, height) in [(0, 0), (0, u32::MAX), (u32::MAX, 0)] {
330            let pixels = GrayPixels::try_new(width, height, &[]).unwrap();
331            assert_eq!(pixels.try_get(0, 0), None);
332        }
333    }
334
335    #[test]
336    fn checked_grayscale_view_rejects_unrepresentable_dimensions() {
337        assert!(matches!(GrayPixels::try_new(u32::MAX, u32::MAX, &[]), Err(GrayPixelsError::DimensionsOverflow)));
338    }
339
340    #[test]
341    fn checked_access_is_safe_for_an_unchecked_short_buffer() {
342        let pixels = GrayPixels::new(2, 2, &[7]);
343        assert_eq!(pixels.try_get(0, 0), Some(7));
344        assert_eq!(pixels.try_get(1, 0), None);
345        assert_eq!(pixels.try_get(0, 1), None);
346        assert_eq!(GrayPixels::new(u32::MAX, u32::MAX, &[]).try_get(u32::MAX - 1, u32::MAX - 1), None);
347    }
348}