/ cpp / QrCode.hpp
QrCode.hpp
  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 <array>
 27  #include <cstdint>
 28  #include <stdexcept>
 29  #include <string>
 30  #include <vector>
 31  
 32  
 33  namespace qrcodegen {
 34  
 35  /* 
 36   * A segment of character/binary/control data in a QR Code symbol.
 37   * Instances of this class are immutable.
 38   * The mid-level way to create a segment is to take the payload data
 39   * and call a static factory function such as QrSegment::makeNumeric().
 40   * The low-level way to create a segment is to custom-make the bit buffer
 41   * and call the QrSegment() constructor with appropriate values.
 42   * This segment class imposes no length restrictions, but QR Codes have restrictions.
 43   * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
 44   * Any segment longer than this is meaningless for the purpose of generating QR Codes.
 45   */
 46  class QrSegment final {
 47  	
 48  	/*---- Public helper enumeration ----*/
 49  	
 50  	/* 
 51  	 * Describes how a segment's data bits are interpreted. Immutable.
 52  	 */
 53  	public: class Mode final {
 54  		
 55  		/*-- Constants --*/
 56  		
 57  		public: static const Mode NUMERIC;
 58  		public: static const Mode ALPHANUMERIC;
 59  		public: static const Mode BYTE;
 60  		public: static const Mode KANJI;
 61  		public: static const Mode ECI;
 62  		
 63  		
 64  		/*-- Fields --*/
 65  		
 66  		// The mode indicator bits, which is a uint4 value (range 0 to 15).
 67  		private: int modeBits;
 68  		
 69  		// Number of character count bits for three different version ranges.
 70  		private: int numBitsCharCount[3];
 71  		
 72  		
 73  		/*-- Constructor --*/
 74  		
 75  		private: Mode(int mode, int cc0, int cc1, int cc2);
 76  		
 77  		
 78  		/*-- Methods --*/
 79  		
 80  		/* 
 81  		 * (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15).
 82  		 */
 83  		public: int getModeBits() const;
 84  		
 85  		/* 
 86  		 * (Package-private) Returns the bit width of the character count field for a segment in
 87  		 * this mode in a QR Code at the given version number. The result is in the range [0, 16].
 88  		 */
 89  		public: int numCharCountBits(int ver) const;
 90  		
 91  	};
 92  	
 93  	
 94  	
 95  	/*---- Static factory functions (mid level) ----*/
 96  	
 97  	/* 
 98  	 * Returns a segment representing the given binary data encoded in
 99  	 * byte mode. All input byte vectors are acceptable. Any text string
100  	 * can be converted to UTF-8 bytes and encoded as a byte mode segment.
101  	 */
102  	public: static QrSegment makeBytes(const std::vector<std::uint8_t> &data);
103  	
104  	
105  	/* 
106  	 * Returns a segment representing the given string of decimal digits encoded in numeric mode.
107  	 */
108  	public: static QrSegment makeNumeric(const char *digits);
109  	
110  	
111  	/* 
112  	 * Returns a segment representing the given text string encoded in alphanumeric mode.
113  	 * The characters allowed are: 0 to 9, A to Z (uppercase only), space,
114  	 * dollar, percent, asterisk, plus, hyphen, period, slash, colon.
115  	 */
116  	public: static QrSegment makeAlphanumeric(const char *text);
117  	
118  	
119  	/* 
120  	 * Returns a list of zero or more segments to represent the given text string. The result
121  	 * may use various segment modes and switch modes to optimize the length of the bit stream.
122  	 */
123  	public: static std::vector<QrSegment> makeSegments(const char *text);
124  	
125  	
126  	/* 
127  	 * Returns a segment representing an Extended Channel Interpretation
128  	 * (ECI) designator with the given assignment value.
129  	 */
130  	public: static QrSegment makeEci(long assignVal);
131  	
132  	
133  	/*---- Public static helper functions ----*/
134  	
135  	/* 
136  	 * Tests whether the given string can be encoded as a segment in alphanumeric mode.
137  	 * A string is encodable iff each character is in the following set: 0 to 9, A to Z
138  	 * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
139  	 */
140  	public: static bool isAlphanumeric(const char *text);
141  	
142  	
143  	/* 
144  	 * Tests whether the given string can be encoded as a segment in numeric mode.
145  	 * A string is encodable iff each character is in the range 0 to 9.
146  	 */
147  	public: static bool isNumeric(const char *text);
148  	
149  	
150  	
151  	/*---- Instance fields ----*/
152  	
153  	/* The mode indicator of this segment. Accessed through getMode(). */
154  	private: Mode mode;
155  	
156  	/* The length of this segment's unencoded data. Measured in characters for
157  	 * numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
158  	 * Always zero or positive. Not the same as the data's bit length.
159  	 * Accessed through getNumChars(). */
160  	private: int numChars;
161  	
162  	/* The data bits of this segment. Accessed through getData(). */
163  	private: std::vector<bool> data;
164  	
165  	
166  	/*---- Constructors (low level) ----*/
167  	
168  	/* 
169  	 * Creates a new QR Code segment with the given attributes and data.
170  	 * The character count (numCh) must agree with the mode and the bit buffer length,
171  	 * but the constraint isn't checked. The given bit buffer is copied and stored.
172  	 */
173  	public: QrSegment(Mode md, int numCh, const std::vector<bool> &dt);
174  	
175  	
176  	/* 
177  	 * Creates a new QR Code segment with the given parameters and data.
178  	 * The character count (numCh) must agree with the mode and the bit buffer length,
179  	 * but the constraint isn't checked. The given bit buffer is moved and stored.
180  	 */
181  	public: QrSegment(Mode md, int numCh, std::vector<bool> &&dt);
182  	
183  	
184  	/*---- Methods ----*/
185  	
186  	/* 
187  	 * Returns the mode field of this segment.
188  	 */
189  	public: Mode getMode() const;
190  	
191  	
192  	/* 
193  	 * Returns the character count field of this segment.
194  	 */
195  	public: int getNumChars() const;
196  	
197  	
198  	/* 
199  	 * Returns the data bits of this segment.
200  	 */
201  	public: const std::vector<bool> &getData() const;
202  	
203  	
204  	// (Package-private) Calculates the number of bits needed to encode the given segments at
205  	// the given version. Returns a non-negative number if successful. Otherwise returns -1 if a
206  	// segment has too many characters to fit its length field, or the total bits exceeds INT_MAX.
207  	public: static int getTotalBits(const std::vector<QrSegment> &segs, int version);
208  	
209  	
210  	/*---- Private constant ----*/
211  	
212  	/* The set of all legal characters in alphanumeric mode, where
213  	 * each character value maps to the index in the string. */
214  	private: static const char *ALPHANUMERIC_CHARSET;
215  	
216  };
217  
218  
219  
220  /* 
221   * A QR Code symbol, which is a type of two-dimension barcode.
222   * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
223   * Instances of this class represent an immutable square grid of black and white cells.
224   * The class provides static factory functions to create a QR Code from text or binary data.
225   * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
226   * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
227   * 
228   * Ways to create a QR Code object:
229   * - High level: Take the payload data and call QrCode::encodeText() or QrCode::encodeBinary().
230   * - Mid level: Custom-make the list of segments and call QrCode::encodeSegments().
231   * - Low level: Custom-make the array of data codeword bytes (including
232   *   segment headers and final padding, excluding error correction codewords),
233   *   supply the appropriate version number, and call the QrCode() constructor.
234   * (Note that all ways require supplying the desired error correction level.)
235   */
236  class QrCode final {
237  	
238  	/*---- Public helper enumeration ----*/
239  	
240  	/* 
241  	 * The error correction level in a QR Code symbol.
242  	 */
243  	public: enum class Ecc {
244  		LOW = 0 ,  // The QR Code can tolerate about  7% erroneous codewords
245  		MEDIUM  ,  // The QR Code can tolerate about 15% erroneous codewords
246  		QUARTILE,  // The QR Code can tolerate about 25% erroneous codewords
247  		HIGH    ,  // The QR Code can tolerate about 30% erroneous codewords
248  	};
249  	
250  	
251  	// Returns a value in the range 0 to 3 (unsigned 2-bit integer).
252  	private: static int getFormatBits(Ecc ecl);
253  	
254  	
255  	
256  	/*---- Static factory functions (high level) ----*/
257  	
258  	/* 
259  	 * Returns a QR Code representing the given Unicode text string at the given error correction level.
260  	 * As a conservative upper bound, this function is guaranteed to succeed for strings that have 2953 or fewer
261  	 * UTF-8 code units (not Unicode code points) if the low error correction level is used. The smallest possible
262  	 * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than
263  	 * the ecl argument if it can be done without increasing the version.
264  	 */
265  	public: static QrCode encodeText(const char *text, Ecc ecl);
266  	
267  	
268  	/* 
269  	 * Returns a QR Code representing the given binary data at the given error correction level.
270  	 * This function always encodes using the binary segment mode, not any text mode. The maximum number of
271  	 * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
272  	 * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
273  	 */
274  	public: static QrCode encodeBinary(const std::vector<std::uint8_t> &data, Ecc ecl);
275  	
276  	
277  	/*---- Static factory functions (mid level) ----*/
278  	
279  	/* 
280  	 * Returns a QR Code representing the given segments with the given encoding parameters.
281  	 * The smallest possible QR Code version within the given range is automatically
282  	 * chosen for the output. Iff boostEcl is true, then the ECC level of the result
283  	 * may be higher than the ecl argument if it can be done without increasing the
284  	 * version. The mask number is either between 0 to 7 (inclusive) to force that
285  	 * mask, or -1 to automatically choose an appropriate mask (which may be slow).
286  	 * This function allows the user to create a custom sequence of segments that switches
287  	 * between modes (such as alphanumeric and byte) to encode text in less space.
288  	 * This is a mid-level API; the high-level API is encodeText() and encodeBinary().
289  	 */
290  	public: static QrCode encodeSegments(const std::vector<QrSegment> &segs, Ecc ecl,
291  		int minVersion=1, int maxVersion=40, int mask=-1, bool boostEcl=true);  // All optional parameters
292  	
293  	
294  	
295  	/*---- Instance fields ----*/
296  	
297  	// Immutable scalar parameters:
298  	
299  	/* The version number of this QR Code, which is between 1 and 40 (inclusive).
300  	 * This determines the size of this barcode. */
301  	private: int version;
302  	
303  	/* The width and height of this QR Code, measured in modules, between
304  	 * 21 and 177 (inclusive). This is equal to version * 4 + 17. */
305  	private: int size;
306  	
307  	/* The error correction level used in this QR Code. */
308  	private: Ecc errorCorrectionLevel;
309  	
310  	/* The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
311  	 * Even if a QR Code is created with automatic masking requested (mask = -1),
312  	 * the resulting object still has a mask value between 0 and 7. */
313  	private: int mask;
314  	
315  	// Private grids of modules/pixels, with dimensions of size*size:
316  	
317  	// The modules of this QR Code (false = white, true = black).
318  	// Immutable after constructor finishes. Accessed through getModule().
319  	private: std::vector<std::vector<bool> > modules;
320  	
321  	// Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
322  	private: std::vector<std::vector<bool> > isFunction;
323  	
324  	
325  	
326  	/*---- Constructor (low level) ----*/
327  	
328  	/* 
329  	 * Creates a new QR Code with the given version number,
330  	 * error correction level, data codeword bytes, and mask number.
331  	 * This is a low-level API that most users should not use directly.
332  	 * A mid-level API is the encodeSegments() function.
333  	 */
334  	public: QrCode(int ver, Ecc ecl, const std::vector<std::uint8_t> &dataCodewords, int msk);
335  	
336  	
337  	
338  	/*---- Public instance methods ----*/
339  	
340  	/* 
341  	 * Returns this QR Code's version, in the range [1, 40].
342  	 */
343  	public: int getVersion() const;
344  	
345  	
346  	/* 
347  	 * Returns this QR Code's size, in the range [21, 177].
348  	 */
349  	public: int getSize() const;
350  	
351  	
352  	/* 
353  	 * Returns this QR Code's error correction level.
354  	 */
355  	public: Ecc getErrorCorrectionLevel() const;
356  	
357  	
358  	/* 
359  	 * Returns this QR Code's mask, in the range [0, 7].
360  	 */
361  	public: int getMask() const;
362  	
363  	
364  	/* 
365  	 * Returns the color of the module (pixel) at the given coordinates, which is false
366  	 * for white or true for black. The top left corner has the coordinates (x=0, y=0).
367  	 * If the given coordinates are out of bounds, then false (white) is returned.
368  	 */
369  	public: bool getModule(int x, int y) const;
370  	
371  	
372  	/* 
373  	 * Returns a string of SVG code for an image depicting this QR Code, with the given number
374  	 * of border modules. The string always uses Unix newlines (\n), regardless of the platform.
375  	 */
376  	public: std::string toSvgString(int border) const;
377  	
378  	
379  	
380  	/*---- Private helper methods for constructor: Drawing function modules ----*/
381  	
382  	// Reads this object's version field, and draws and marks all function modules.
383  	private: void drawFunctionPatterns();
384  	
385  	
386  	// Draws two copies of the format bits (with its own error correction code)
387  	// based on the given mask and this object's error correction level field.
388  	private: void drawFormatBits(int msk);
389  	
390  	
391  	// Draws two copies of the version bits (with its own error correction code),
392  	// based on this object's version field, iff 7 <= version <= 40.
393  	private: void drawVersion();
394  	
395  	
396  	// Draws a 9*9 finder pattern including the border separator,
397  	// with the center module at (x, y). Modules can be out of bounds.
398  	private: void drawFinderPattern(int x, int y);
399  	
400  	
401  	// Draws a 5*5 alignment pattern, with the center module
402  	// at (x, y). All modules must be in bounds.
403  	private: void drawAlignmentPattern(int x, int y);
404  	
405  	
406  	// Sets the color of a module and marks it as a function module.
407  	// Only used by the constructor. Coordinates must be in bounds.
408  	private: void setFunctionModule(int x, int y, bool isBlack);
409  	
410  	
411  	// Returns the color of the module at the given coordinates, which must be in range.
412  	private: bool module(int x, int y) const;
413  	
414  	
415  	/*---- Private helper methods for constructor: Codewords and masking ----*/
416  	
417  	// Returns a new byte string representing the given data with the appropriate error correction
418  	// codewords appended to it, based on this object's version and error correction level.
419  	private: std::vector<std::uint8_t> addEccAndInterleave(const std::vector<std::uint8_t> &data) const;
420  	
421  	
422  	// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
423  	// data area of this QR Code. Function modules need to be marked off before this is called.
424  	private: void drawCodewords(const std::vector<std::uint8_t> &data);
425  	
426  	
427  	// XORs the codeword modules in this QR Code with the given mask pattern.
428  	// The function modules must be marked and the codeword bits must be drawn
429  	// before masking. Due to the arithmetic of XOR, calling applyMask() with
430  	// the same mask value a second time will undo the mask. A final well-formed
431  	// QR Code needs exactly one (not zero, two, etc.) mask applied.
432  	private: void applyMask(int msk);
433  	
434  	
435  	// Calculates and returns the penalty score based on state of this QR Code's current modules.
436  	// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
437  	private: long getPenaltyScore() const;
438  	
439  	
440  	
441  	/*---- Private helper functions ----*/
442  	
443  	// Returns an ascending list of positions of alignment patterns for this version number.
444  	// Each position is in the range [0,177), and are used on both the x and y axes.
445  	// This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
446  	private: std::vector<int> getAlignmentPatternPositions() const;
447  	
448  	
449  	// Returns the number of data bits that can be stored in a QR Code of the given version number, after
450  	// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
451  	// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
452  	private: static int getNumRawDataModules(int ver);
453  	
454  	
455  	// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
456  	// QR Code of the given version number and error correction level, with remainder bits discarded.
457  	// This stateless pure function could be implemented as a (40*4)-cell lookup table.
458  	private: static int getNumDataCodewords(int ver, Ecc ecl);
459  	
460  	
461  	// Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
462  	// implemented as a lookup table over all possible parameter values, instead of as an algorithm.
463  	private: static std::vector<std::uint8_t> reedSolomonComputeDivisor(int degree);
464  	
465  	
466  	// Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
467  	private: static std::vector<std::uint8_t> reedSolomonComputeRemainder(const std::vector<std::uint8_t> &data, const std::vector<std::uint8_t> &divisor);
468  	
469  	
470  	// Returns the product of the two given field elements modulo GF(2^8/0x11D).
471  	// All inputs are valid. This could be implemented as a 256*256 lookup table.
472  	private: static std::uint8_t reedSolomonMultiply(std::uint8_t x, std::uint8_t y);
473  	
474  	
475  	// Can only be called immediately after a white run is added, and
476  	// returns either 0, 1, or 2. A helper function for getPenaltyScore().
477  	private: int finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const;
478  	
479  	
480  	// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
481  	private: int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const;
482  	
483  	
484  	// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
485  	private: void finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) const;
486  	
487  	
488  	// Returns true iff the i'th bit of x is set to 1.
489  	private: static bool getBit(long x, int i);
490  	
491  	
492  	/*---- Constants and tables ----*/
493  	
494  	// The minimum version number supported in the QR Code Model 2 standard.
495  	public: static constexpr int MIN_VERSION =  1;
496  	
497  	// The maximum version number supported in the QR Code Model 2 standard.
498  	public: static constexpr int MAX_VERSION = 40;
499  	
500  	
501  	// For use in getPenaltyScore(), when evaluating which mask is best.
502  	private: static const int PENALTY_N1;
503  	private: static const int PENALTY_N2;
504  	private: static const int PENALTY_N3;
505  	private: static const int PENALTY_N4;
506  	
507  	
508  	private: static const std::int8_t ECC_CODEWORDS_PER_BLOCK[4][41];
509  	private: static const std::int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41];
510  	
511  };
512  
513  
514  
515  /*---- Public exception class ----*/
516  
517  /* 
518   * Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include:
519   * - Decrease the error correction level if it was greater than Ecc::LOW.
520   * - If the encodeSegments() function was called with a maxVersion argument, then increase
521   *   it if it was less than QrCode::MAX_VERSION. (This advice does not apply to the other
522   *   factory functions because they search all versions up to QrCode::MAX_VERSION.)
523   * - Split the text data into better or optimal segments in order to reduce the number of bits required.
524   * - Change the text or binary data to be shorter.
525   * - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).
526   * - Propagate the error upward to the caller/user.
527   */
528  class data_too_long : public std::length_error {
529  	
530  	public: explicit data_too_long(const std::string &msg);
531  	
532  };
533  
534  
535  
536  /* 
537   * An appendable sequence of bits (0s and 1s). Mainly used by QrSegment.
538   */
539  class BitBuffer final : public std::vector<bool> {
540  	
541  	/*---- Constructor ----*/
542  	
543  	// Creates an empty bit buffer (length 0).
544  	public: BitBuffer();
545  	
546  	
547  	
548  	/*---- Method ----*/
549  	
550  	// Appends the given number of low-order bits of the given value
551  	// to this buffer. Requires 0 <= len <= 31 and val < 2^len.
552  	public: void appendBits(std::uint32_t val, int len);
553  	
554  };
555  
556  }