1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//! Module `qr` is the entrypoint to start making `QRCodes`

use crate::module::Module;
use core::fmt::{Debug, Formatter};
use core::ops::{Index, IndexMut};

use crate::datamasking::Mask;
use crate::encode::Mode;
#[cfg(not(feature = "wasm-bindgen"))]
use crate::helpers;
use crate::{encode, Version, ECL};

const QR_MAX_WIDTH: usize = 177;
const QR_MAX_MODULES: usize = QR_MAX_WIDTH * QR_MAX_WIDTH;

/// A `QRCode` can be created using [`QRBuilder`]. Simple API for simple usage.
/// If you need to use `QRCode` directly, please file an [issue on
/// github](https://github.com/erwanvivien/fast_qr) explaining your use case.
///
/// Contains all needed information about the `QRCode`.
/// This is the main struct of the crate.
///
/// It contains the matrix of the `QRCode`, stored as a one-dimensional array.
#[derive(Clone)]
pub struct QRCode {
    /// This array length is of size `177 x 177`. It is using a fixed size
    /// array simply because of performance.
    ///
    /// # Other data type possible:
    /// - Templated Matrix was faster but crate size was huge.
    /// - Vector using `with_capacity`, really bad.
    pub data: [Module; QR_MAX_MODULES],
    /// Width & Height of QRCode. If manually set, should be `version * 4 + 17`, `version` going
    /// from 1 to 40 both included.
    pub size: usize,

    /// Version of the `QRCode`, impacts the size.
    ///
    /// `None` will optimize Version according to ECL and Mode
    pub version: Option<Version>,
    /// Defines how powerful `QRCode` redundancy should be or how much percent of a QRCode can be
    /// recovered.
    ///
    /// - `ECL::L`: 7%
    /// - `ECL::M`: 15%
    /// - `ECL::Q`: 25%
    /// - `ELC::H`: 30%
    ///
    /// `None` will set ECL to Quartile (`ELC::Q`)
    pub ecl: Option<ECL>,

    /// Changes the final pattern used.
    ///
    /// None will find the best suited mask.
    pub mask: Option<Mask>,
    /// Mode defines which data is being parsed, between Numeric, AlphaNumeric & Byte.
    ///
    /// `None` will optimize Mode according to user input.
    ///
    /// ## Note
    /// Kanji mode is not supported (yet).
    pub mode: Option<Mode>,
}

impl Debug for QRCode {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("QRCode")
            .field("size", &self.size)
            .field("version", &self.version)
            .field("ecl", &self.ecl)
            .field("mask", &self.mask)
            .field("mode", &self.mode)
            .finish_non_exhaustive()
    }
}

impl QRCode {
    /// A default `QRCode` will have all it's fields as `None` and a default Matrix filled with `Module::LIGHT`.
    #[must_use]
    pub const fn default(size: usize) -> Self {
        QRCode {
            data: [Module::data(Module::LIGHT); QR_MAX_MODULES],
            size,
            version: None,
            ecl: None,
            mask: None,
            mode: None,
        }
    }
}

impl Index<usize> for QRCode {
    type Output = [Module];

    fn index(&self, index: usize) -> &Self::Output {
        &self.data[index * self.size..(index + 1) * self.size]
    }
}

impl IndexMut<usize> for QRCode {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.data[index * self.size..(index + 1) * self.size]
    }
}

/// Contains different error when [`QRCode`] could not be created
pub enum QRCodeError {
    /// 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))
    EncodedData,
    /// Specified version too small to contain data
    SpecifiedVersion,
}

// We don't want to use `std::error::Error` on wasm32
impl std::error::Error for QRCodeError {}

impl std::fmt::Display for QRCodeError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            QRCodeError::EncodedData => f.write_str("Data too big to be encoded"),
            QRCodeError::SpecifiedVersion => {
                f.write_str("Specified version too low to contain data")
            }
        }
    }
}

impl Debug for QRCodeError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            QRCodeError::EncodedData => f.write_str("Data too big to be encoded"),
            QRCodeError::SpecifiedVersion => {
                f.write_str("Specified version too low to contain data")
            }
        }
    }
}

impl QRCode {
    /// Creates a new `QRCode` from a ECL / version
    ///
    /// # Errors
    /// - `QRCodeError::EncodedData` if `input` is too large to be encoded
    /// - `QRCodeError::SpecifiedVersion` if specified `version` is too small to contain data
    pub(crate) fn new(
        input: &[u8],
        ecl: Option<ECL>,
        v: Option<Version>,
        mode: Option<Mode>,
        mut mask: Option<Mask>,
    ) -> Result<Self, QRCodeError> {
        use crate::placement::create_matrix;

        let mode = mode.unwrap_or_else(|| encode::best_encoding(input));
        let level = ecl.unwrap_or(ECL::Q);

        let version = match Version::get(mode, level, input.len()) {
            Some(version) => version,
            None => return Err(QRCodeError::EncodedData),
        };
        let version = match v {
            Some(user_version) if user_version as usize >= version as usize => user_version,
            None => version,
            Some(_) => return Err(QRCodeError::SpecifiedVersion),
        };

        let out = create_matrix(input, level, mode, version, &mut mask);
        Ok(out)
    }

    /// Prints the `QRCode` to the terminal
    #[must_use]
    #[cfg(not(feature = "wasm-bindgen"))]
    pub fn to_str(&self) -> String {
        helpers::print_matrix_with_margin(self)
    }

    /// Prints the `QRCode` to the terminal
    #[cfg(not(feature = "wasm-bindgen"))]
    pub fn print(&self) {
        println!("{}", helpers::print_matrix_with_margin(self));
    }
}

/// Builder struct, makes it easier to create a [`QRCode`].
///
/// # Example
/// ```rust
/// use fast_qr::QRBuilder;
/// use fast_qr::{Mask, ECL, Version};
///
/// // Creates a `QRCode` with a forced `version`, `ecl` and/or `mask`
/// let input = String::from("Hello World!");
/// let qr = QRBuilder::new(input)
///     // .version(Version::V05)
///     // .ecl(ECL::H)
///     // .mask(Mask::Checkerboard)
///     .build();
/// ```
pub struct QRBuilder {
    input: Vec<u8>,
    ecl: Option<ECL>,
    mode: Option<Mode>,
    version: Option<Version>,
    mask: Option<Mask>,
}

impl QRBuilder {
    /// Creates an instance of `QRBuilder` with default parameters
    #[must_use]
    pub fn new<I: Into<Vec<u8>>>(input: I) -> QRBuilder {
        QRBuilder {
            input: input.into(),
            mask: None,
            mode: None,
            version: None,
            ecl: None,
        }
    }

    /// Forces the Mode
    pub fn mode(&mut self, mode: Mode) -> &mut Self {
        self.mode = Some(mode);
        self
    }

    /// Forces the Encoding Level
    pub fn ecl(&mut self, ecl: ECL) -> &mut Self {
        self.ecl = Some(ecl);
        self
    }

    /// Forces the version
    pub fn version(&mut self, version: Version) -> &mut Self {
        self.version = Some(version);
        self
    }

    /// Forces the mask, should very rarely be used
    pub fn mask(&mut self, mask: Mask) -> &mut Self {
        self.mask = Some(mask);
        self
    }

    /// Computes a [`QRCode`] with given parameters
    ///
    /// # Errors
    /// - `QRCodeError::EncodedData` if `input` is too large to be encoded. See [an online table](https://fast-qr.com/blog/tables/ecl) for more info.
    /// - `QRCodeError::SpecifiedVersion` if specified `version` is too small to contain data
    pub fn build(&self) -> Result<QRCode, QRCodeError> {
        QRCode::new(&self.input, self.ecl, self.version, self.mode, self.mask)
    }
}