1#![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#[non_exhaustive]
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum GrayPixelsError {
39 DimensionsOverflow,
41 BufferLengthMismatch {
43 expected: usize,
45 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#[non_exhaustive]
69#[derive(Debug, Clone, Copy)]
70pub struct GrayPixels<'a> {
71 width: u32,
73 height: u32,
75 data: &'a [u8],
77}
78
79impl<'a> GrayPixels<'a> {
80 #[must_use]
82 pub fn new(width: u32, height: u32, data: &'a [u8]) -> Self {
83 Self { width, height, data }
84 }
85
86 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 #[must_use]
111 pub const fn width(&self) -> u32 {
112 self.width
113 }
114
115 #[must_use]
117 pub const fn height(&self) -> u32 {
118 self.height
119 }
120
121 #[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 #[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 let logical_len = width as usize * height as usize;
156 Self::new(width, height, &img.as_raw()[..logical_len])
157 }
158}
159
160#[non_exhaustive]
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct DecodedQrCode {
168 data: Vec<u8>,
170 version: Version,
172 ec_level: EcLevel,
174}
175
176impl DecodedQrCode {
177 #[must_use]
179 pub fn new(data: Vec<u8>, version: Version, ec_level: EcLevel) -> Self {
180 Self { data, version, ec_level }
181 }
182
183 #[must_use]
185 pub fn data(&self) -> &[u8] {
186 &self.data
187 }
188
189 #[must_use]
193 pub fn into_data(self) -> Vec<u8> {
194 self.data
195 }
196
197 #[must_use]
199 pub fn version(&self) -> Version {
200 self.version
201 }
202
203 #[must_use]
205 pub fn ec_level(&self) -> EcLevel {
206 self.ec_level
207 }
208}
209
210pub trait QrDecoder {
219 type Error;
221
222 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}