Debian Codegraph @

src/qr.rs

raw symbols SCIP
1 //! Module `qr` is the entrypoint to start making `QRCodes`
2
3 use crate::module::Module;
4 use core::fmt::{Debug, Formatter};
5 use core::ops::{Index, IndexMut};
6
7 use crate::datamasking::Mask;
8 use crate::encode::Mode;
9 #[cfg(not(feature = "wasm-bindgen"))]
10 use crate::helpers;
11 use crate::{encode, Version, ECL};
12
13 const QR_MAX_WIDTH: usize = 177;
14 const QR_MAX_MODULES: usize = QR_MAX_WIDTH * QR_MAX_WIDTH;
15
16 /// A `QRCode` can be created using [`QRBuilder`]. Simple API for simple usage.
17 /// If you need to use `QRCode` directly, please file an [issue on
18 /// github](https://github.com/erwanvivien/fast_qr) explaining your use case.
19 ///
20 /// Contains all needed information about the `QRCode`.
21 /// This is the main struct of the crate.
22 ///
23 /// It contains the matrix of the `QRCode`, stored as a one-dimensional array.
24 #[derive(Clone)]
25 pub struct QRCode {
26 /// This array length is of size `177 x 177`. It is using a fixed size
27 /// array simply because of performance.
28 ///
29 /// # Other data type possible:
30 /// - Templated Matrix was faster but crate size was huge.
31 /// - Vector using `with_capacity`, really bad.
32 pub data: [Module; QR_MAX_MODULES],
33 /// Width & Height of QRCode. If manually set, should be `version * 4 + 17`, `version` going
34 /// from 1 to 40 both included.
35 pub size: usize,
36
37 /// Version of the `QRCode`, impacts the size.
38 ///
39 /// `None` will optimize Version according to ECL and Mode
40 pub version: Option<Version>,
41 /// Defines how powerful `QRCode` redundancy should be or how much percent of a QRCode can be
42 /// recovered.
43 ///
44 /// - `ECL::L`: 7%
45 /// - `ECL::M`: 15%
46 /// - `ECL::Q`: 25%
47 /// - `ELC::H`: 30%
48 ///
49 /// `None` will set ECL to Quartile (`ELC::Q`)
50 pub ecl: Option<ECL>,
51
52 /// Changes the final pattern used.
53 ///
54 /// None will find the best suited mask.
55 pub mask: Option<Mask>,
56 /// Mode defines which data is being parsed, between Numeric, AlphaNumeric & Byte.
57 ///
58 /// `None` will optimize Mode according to user input.
59 ///
60 /// ## Note
61 /// Kanji mode is not supported (yet).
62 pub mode: Option<Mode>,
63 }
64
65 impl Debug for QRCode {
66 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
67 f.debug_struct("QRCode")
68 .field("size", &self.size)
69 .field("version", &self.version)
70 .field("ecl", &self.ecl)
71 .field("mask", &self.mask)
72 .field("mode", &self.mode)
73 .finish_non_exhaustive()
74 }
75 }
76
77 impl QRCode {
78 /// A default `QRCode` will have all it's fields as `None` and a default Matrix filled with `Module::LIGHT`.
79 #[must_use]
80 pub const fn default(size: usize) -> Self {
81 QRCode {
82 data: [Module::data(Module::LIGHT); QR_MAX_MODULES],
83 size,
84 version: None,
85 ecl: None,
86 mask: None,
87 mode: None,
88 }
89 }
90 }
91
92 impl Index<usize> for QRCode {
93 type Output = [Module];
94
95 fn index(&self, index: usize) -> &Self::Output {
96 &self.data[index * self.size..(index + 1) * self.size]
97 }
98 }
99
100 impl IndexMut<usize> for QRCode {
101 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
102 &mut self.data[index * self.size..(index + 1) * self.size]
103 }
104 }
105
106 /// Contains different error when [`QRCode`] could not be created
107 pub enum QRCodeError {
108 /// If data if too large to be encoded (refer to Table 7-11 of the spec or [an online table](https://fast-qr.com/blog/tables/ecl))
109 EncodedData,
110 /// Specified version too small to contain data
111 SpecifiedVersion,
112 }
113
114 // We don't want to use `std::error::Error` on wasm32
115 impl std::error::Error for QRCodeError {}
116
117 impl std::fmt::Display for QRCodeError {
118 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
119 match self {
120 QRCodeError::EncodedData => f.write_str("Data too big to be encoded"),
121 QRCodeError::SpecifiedVersion => {
122 f.write_str("Specified version too low to contain data")
123 }
124 }
125 }
126 }
127
128 impl Debug for QRCodeError {
129 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
130 match self {
131 QRCodeError::EncodedData => f.write_str("Data too big to be encoded"),
132 QRCodeError::SpecifiedVersion => {
133 f.write_str("Specified version too low to contain data")
134 }
135 }
136 }
137 }
138
139 impl QRCode {
140 /// Creates a new `QRCode` from a ECL / version
141 ///
142 /// # Errors
143 /// - `QRCodeError::EncodedData` if `input` is too large to be encoded
144 /// - `QRCodeError::SpecifiedVersion` if specified `version` is too small to contain data
145 pub(crate) fn new(
146 input: &[u8],
147 ecl: Option<ECL>,
148 v: Option<Version>,
149 mode: Option<Mode>,
150 mut mask: Option<Mask>,
151 ) -> Result<Self, QRCodeError> {
152 use crate::placement::create_matrix;
153
154 let mode = mode.unwrap_or_else(|| encode::best_encoding(input));
155 let level = ecl.unwrap_or(ECL::Q);
156
157 let version = match Version::get(mode, level, input.len()) {
158 Some(version) => version,
159 None => return Err(QRCodeError::EncodedData),
160 };
161 let version = match v {
162 Some(user_version) if user_version as usize >= version as usize => user_version,
163 None => version,
164 Some(_) => return Err(QRCodeError::SpecifiedVersion),
165 };
166
167 let out = create_matrix(input, level, mode, version, &mut mask);
168 Ok(out)
169 }
170
171 /// Prints the `QRCode` to the terminal
172 #[must_use]
173 #[cfg(not(feature = "wasm-bindgen"))]
174 pub fn to_str(&self) -> String {
175 helpers::print_matrix_with_margin(self)
176 }
177
178 /// Prints the `QRCode` to the terminal
179 #[cfg(not(feature = "wasm-bindgen"))]
180 pub fn print(&self) {
181 println!("{}", helpers::print_matrix_with_margin(self));
182 }
183 }
184
185 /// Builder struct, makes it easier to create a [`QRCode`].
186 ///
187 /// # Example
188 /// ```rust
189 /// use fast_qr::QRBuilder;
190 /// use fast_qr::{Mask, ECL, Version};
191 ///
192 /// // Creates a `QRCode` with a forced `version`, `ecl` and/or `mask`
193 /// let input = String::from("Hello World!");
194 /// let qr = QRBuilder::new(input)
195 /// // .version(Version::V05)
196 /// // .ecl(ECL::H)
197 /// // .mask(Mask::Checkerboard)
198 /// .build();
199 /// ```
200 pub struct QRBuilder {
201 input: Vec<u8>,
202 ecl: Option<ECL>,
203 mode: Option<Mode>,
204 version: Option<Version>,
205 mask: Option<Mask>,
206 }
207
208 impl QRBuilder {
209 /// Creates an instance of `QRBuilder` with default parameters
210 #[must_use]
211 pub fn new<I: Into<Vec<u8>>>(input: I) -> QRBuilder {
212 QRBuilder {
213 input: input.into(),
214 mask: None,
215 mode: None,
216 version: None,
217 ecl: None,
218 }
219 }
220
221 /// Forces the Mode
222 pub fn mode(&mut self, mode: Mode) -> &mut Self {
223 self.mode = Some(mode);
224 self
225 }
226
227 /// Forces the Encoding Level
228 pub fn ecl(&mut self, ecl: ECL) -> &mut Self {
229 self.ecl = Some(ecl);
230 self
231 }
232
233 /// Forces the version
234 pub fn version(&mut self, version: Version) -> &mut Self {
235 self.version = Some(version);
236 self
237 }
238
239 /// Forces the mask, should very rarely be used
240 pub fn mask(&mut self, mask: Mask) -> &mut Self {
241 self.mask = Some(mask);
242 self
243 }
244
245 /// Computes a [`QRCode`] with given parameters
246 ///
247 /// # Errors
248 /// - `QRCodeError::EncodedData` if `input` is too large to be encoded. See [an online table](https://fast-qr.com/blog/tables/ecl) for more info.
249 /// - `QRCodeError::SpecifiedVersion` if specified `version` is too small to contain data
250 pub fn build(&self) -> Result<QRCode, QRCodeError> {
251 QRCode::new(&self.input, self.ecl, self.version, self.mode, self.mask)
252 }
253 }