SWE-350 TOTP Generator Milestone 5
The DE-10 board has six 7-segment displays, this can be used to display and generate a time based one-time pin (TOTP).
Loading...
Searching...
No Matches
QrCode.hpp
Go to the documentation of this file.
1/*
2 * QR Code generator library (C++)
3 *
4 * Copyright (c) Project Nayuki
5 * https://www.nayuki.io/page/qr-code-generator-library
6 *
7 * (MIT License)
8 * Permission is hereby granted, free of charge, to any person obtaining a copy of
9 * this software and associated documentation files (the "Software"), to deal in
10 * the Software without restriction, including without limitation the rights to
11 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
12 * the Software, and to permit persons to whom the Software is furnished to do so,
13 * subject to the following conditions:
14 * - The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 * - The Software is provided "as is", without warranty of any kind, express or
17 * implied, including but not limited to the warranties of merchantability,
18 * fitness for a particular purpose and noninfringement. In no event shall the
19 * authors or copyright holders be liable for any claim, damages or other
20 * liability, whether in an action of contract, tort or otherwise, arising from,
21 * out of or in connection with the Software or the use or other dealings in the
22 * Software.
23 */
24
25#pragma once
26
27#include <cstdint>
28#include <string>
29#include <vector>
30#include "QrSegment.hpp"
31
32
33namespace qrcodegen {
34
35/*
36 * Represents an immutable square grid of black and white cells for a QR Code symbol, and
37 * provides static functions to create a QR Code from user-supplied textual or binary data.
38 * This class covers the QR Code model 2 specification, supporting all versions (sizes)
39 * from 1 to 40, all 4 error correction levels, and only 3 character encoding modes.
40 */
41class QrCode {
42
43 /*---- Public helper enumeration ----*/
44public:
45
46 /*
47 * Represents the error correction level used in a QR Code symbol.
48 */
49 class Ecc {
50 // Constants declared in ascending order of error protection.
51 public:
52 const static Ecc LOW, MEDIUM, QUARTILE, HIGH;
53
54 // Fields.
55 public:
56 const int ordinal; // (Public) In the range 0 to 3 (unsigned 2-bit integer).
57 const int formatBits; // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
58
59 // Constructor.
60 private:
61 Ecc(int ord, int fb);
62 };
63
64
65
66 /*---- Public static factory functions ----*/
67public:
68
69 /*
70 * Returns a QR Code symbol representing the given Unicode text string at the given error correction level.
71 * As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer Unicode
72 * code points (not UTF-16 code units). The smallest possible QR Code version is automatically chosen for the output.
73 * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
74 */
75 static QrCode encodeText(const char *text, int version, const Ecc &ecl);
76
77
78 /*
79 * Returns a QR Code symbol representing the given binary data string at the given error correction level.
80 * This function always encodes using the binary segment mode, not any text mode. The maximum number of
81 * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
82 * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
83 */
84 static QrCode encodeBinary(const std::vector<uint8_t> &data, const Ecc &ecl);
85
86
87 /*
88 * Returns a QR Code symbol representing the given data segments with the given encoding parameters.
89 * The smallest possible QR Code version within the given range is automatically chosen for the output.
90 * This function allows the user to create a custom sequence of segments that switches
91 * between modes (such as alphanumeric and binary) to encode text more efficiently.
92 * This function is considered to be lower level than simply encoding text or binary data.
93 */
94 static QrCode encodeSegments(const std::vector<QrSegment> &segs, const Ecc &ecl,
95 int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true); // All optional parameters
96
97
98
99 /*---- Instance fields ----*/
100
101 // Public immutable scalar parameters
102public:
103
104 /* This QR Code symbol's version number, which is always between 1 and 40 (inclusive). */
105 const int version;
106
107 /* The width and height of this QR Code symbol, measured in modules.
108 * Always equal to version &times; 4 + 17, in the range 21 to 177. */
109 const int size;
110
111 /* The error correction level used in this QR Code symbol. */
113
114 /* The mask pattern used in this QR Code symbol, in the range 0 to 7 (i.e. unsigned 3-bit integer).
115 * Note that even if a constructor was called with automatic masking requested
116 * (mask = -1), the resulting object will still have a mask value between 0 and 7. */
117private:
118 int mask;
119
120 // Private grids of modules/pixels (conceptually immutable)
121private:
122 std::vector<std::vector<bool> > modules; // The modules of this QR Code symbol (false = white, true = black)
123 std::vector<std::vector<bool> > isFunction; // Indicates function modules that are not subjected to masking
124
125
126
127 /*---- Constructors ----*/
128public:
129
130 /*
131 * Creates a new QR Code symbol with the given version number, error correction level, binary data array,
132 * and mask number. This is a cumbersome low-level constructor that should not be invoked directly by the user.
133 * To go one level up, see the encodeSegments() function.
134 */
135 QrCode(int ver, const Ecc &ecl, const std::vector<uint8_t> &dataCodewords, int mask);
136
137
138 /*
139 * Creates a new QR Code symbol based on the given existing object, but with a potentially
140 * different mask pattern. The version, error correction level, codewords, etc. of the newly
141 * created object are all identical to the argument object; only the mask may differ.
142 */
143 QrCode(const QrCode &qr, int mask);
144
145
146
147 /*---- Public instance methods ----*/
148public:
149
150 int getMask() const;
151
152
153 /*
154 * Returns the color of the module (pixel) at the given coordinates, which is either 0 for white or 1 for black. The top
155 * left corner has the coordinates (x=0, y=0). If the given coordinates are out of bounds, then 0 (white) is returned.
156 */
157 int getModule(int x, int y) const;
158
159
160 /*
161 * Based on the given number of border modules to add as padding, this returns a
162 * string whose contents represents an SVG XML file that depicts this QR Code symbol.
163 * Note that Unix newlines (\n) are always used, regardless of the platform.
164 */
165 std::string toSvgString(int border) const;
166
167
168
169 /*---- Private helper methods for constructor: Drawing function modules ----*/
170private:
171
172 void drawFunctionPatterns();
173
174
175 // Draws two copies of the format bits (with its own error correction code)
176 // based on the given mask and this object's error correction level field.
177 void drawFormatBits(int mask);
178
179
180 // Draws two copies of the version bits (with its own error correction code),
181 // based on this object's version field (which only has an effect for 7 <= version <= 40).
182 void drawVersion();
183
184
185 // Draws a 9*9 finder pattern including the border separator, with the center module at (x, y).
186 void drawFinderPattern(int x, int y);
187
188
189 // Draws a 5*5 alignment pattern, with the center module at (x, y).
190 void drawAlignmentPattern(int x, int y);
191
192
193 // Sets the color of a module and marks it as a function module.
194 // Only used by the constructor. Coordinates must be in range.
195 void setFunctionModule(int x, int y, bool isBlack);
196
197
198 /*---- Private helper methods for constructor: Codewords and masking ----*/
199private:
200
201 // Returns a new byte string representing the given data with the appropriate error correction
202 // codewords appended to it, based on this object's version and error correction level.
203 std::vector<uint8_t> appendErrorCorrection(const std::vector<uint8_t> &data) const;
204
205
206 // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
207 // data area of this QR Code symbol. Function modules need to be marked off before this is called.
208 void drawCodewords(const std::vector<uint8_t> &data);
209
210
211 // XORs the data modules in this QR Code with the given mask pattern. Due to XOR's mathematical
212 // properties, calling applyMask(m) twice with the same value is equivalent to no change at all.
213 // This means it is possible to apply a mask, undo it, and try another mask. Note that a final
214 // well-formed QR Code symbol needs exactly one mask applied (not zero, not two, etc.).
215 void applyMask(int mask);
216
217
218 // A messy helper function for the constructors. This QR Code must be in an unmasked state when this
219 // method is called. The given argument is the requested mask, which is -1 for auto or 0 to 7 for fixed.
220 // This method applies and returns the actual mask chosen, from 0 to 7.
221 int handleConstructorMasking(int mask);
222
223
224 // Calculates and returns the penalty score based on state of this QR Code's current modules.
225 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
226 int getPenaltyScore() const;
227
228
229
230 /*---- Private static helper functions ----*/
231private:
232
233 // Returns a set of positions of the alignment patterns in ascending order. These positions are
234 // used on both the x and y axes. Each value in the resulting array is in the range [0, 177).
235 // This stateless pure function could be implemented as table of 40 variable-length lists of unsigned bytes.
236 static std::vector<int> getAlignmentPatternPositions(int ver);
237
238
239 // Returns the number of raw data modules (bits) available at the given version number.
240 // These data modules are used for both user data codewords and error correction codewords.
241 // This stateless pure function could be implemented as a 40-entry lookup table.
242 static int getNumRawDataModules(int ver);
243
244
245 // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
246 // QR Code of the given version number and error correction level, with remainder bits discarded.
247 // This stateless pure function could be implemented as a (40*4)-cell lookup table.
248 static int getNumDataCodewords(int ver, const Ecc &ecl);
249
250
251 /*---- Private tables of constants ----*/
252private:
253
254 // For use in getPenaltyScore(), when evaluating which mask is best.
255 static const int PENALTY_N1;
256 static const int PENALTY_N2;
257 static const int PENALTY_N3;
258 static const int PENALTY_N4;
259
260 static const int16_t NUM_ERROR_CORRECTION_CODEWORDS[4][41];
261 static const int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41];
262
263
264
265 /*---- Private helper class ----*/
266private:
267
268 /*
269 * Computes the Reed-Solomon error correction codewords for a sequence of data codewords
270 * at a given degree. Objects are immutable, and the state only depends on the degree.
271 * This class exists because the divisor polynomial does not need to be recalculated for every input.
272 */
273 class ReedSolomonGenerator {
274
275 /*-- Immutable field --*/
276 private:
277
278 // Coefficients of the divisor polynomial, stored from highest to lowest power, excluding the leading term which
279 // is always 1. For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
280 std::vector<uint8_t> coefficients;
281
282
283 /*-- Constructor --*/
284 public:
285
286 /*
287 * Creates a Reed-Solomon ECC generator for the given degree. This could be implemented
288 * as a lookup table over all possible parameter values, instead of as an algorithm.
289 */
290 ReedSolomonGenerator(int degree);
291
292
293 /*-- Method --*/
294 public:
295
296 /*
297 * Computes and returns the Reed-Solomon error correction codewords for the given sequence of data codewords.
298 * The returned object is always a new byte array. This method does not alter this object's state (because it is immutable).
299 */
300 std::vector<uint8_t> getRemainder(const std::vector<uint8_t> &data) const;
301
302
303 /*-- Static function --*/
304 private:
305
306 // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
307 // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
308 static uint8_t multiply(uint8_t x, uint8_t y);
309
310 };
311
312};
313
314}
static const Ecc LOW
Definition QrCode.hpp:52
static const Ecc QUARTILE
Definition QrCode.hpp:52
static const Ecc HIGH
Definition QrCode.hpp:52
static const Ecc MEDIUM
Definition QrCode.hpp:52
QrCode(int ver, const Ecc &ecl, const std::vector< uint8_t > &dataCodewords, int mask)
Definition QrCode.cpp:109
static QrCode encodeText(const char *text, int version, const Ecc &ecl)
Definition QrCode.cpp:45
int getMask() const
Definition QrCode.cpp:153
const Ecc & errorCorrectionLevel
Definition QrCode.hpp:112
const int size
Definition QrCode.hpp:109
const int version
Definition QrCode.hpp:105
static QrCode encodeBinary(const std::vector< uint8_t > &data, const Ecc &ecl)
Definition QrCode.cpp:51
int getModule(int x, int y) const
Definition QrCode.cpp:158
std::string toSvgString(int border) const
Definition QrCode.cpp:166
static QrCode encodeSegments(const std::vector< QrSegment > &segs, const Ecc &ecl, int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true)
Definition QrCode.cpp:58