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