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 #include <limits.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include "qrcodegen.h"
28
29 #ifndef QRCODEGEN_TEST
30 #define testable static // Keep functions private
31 #else
32 #define testable // Expose private functions
33 #endif
34
35 /*---- Forward declarations for private functions ----*/
36
37 // Regarding all public and private functions defined in this source file:
38 // - They require all pointer/array arguments to be not null unless the array length is zero.
39 // - They only read input scalar/array arguments, write to output pointer/array
40 // arguments, and return scalar values; they are "pure" functions.
41 // - They don't read mutable global variables or write to any global variables.
42 // - They don't perform I/O, read the clock, print to console, etc.
43 // - They allocate a small and constant amount of stack memory.
44 // - They don't allocate or free any memory on the heap.
45 // - They don't recurse or mutually recurse. All the code
46 // could be inlined into the top-level public functions.
47 // - They run in at most quadratic time with respect to input arguments.
48 // Most functions run in linear time, and some in constant time.
49 // There are no unbounded loops or non-obvious termination conditions.
50 // - They are completely thread-safe if the caller does not give the
51 // same writable buffer to concurrent calls to these functions.
52
53 testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int *bitLen);
54
55 testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]);
56 testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl);
57 testable int getNumRawDataModules(int ver);
58
59 testable void reedSolomonComputeDivisor(int degree, uint8_t result[]);
60 testable void reedSolomonComputeRemainder(const uint8_t data[], int dataLen,
61 const uint8_t generator[], int degree, uint8_t result[]);
62 testable uint8_t reedSolomonMultiply(uint8_t x, uint8_t y);
63
64 testable void initializeFunctionModules(int version, uint8_t qrcode[]);
65 static void drawLightFunctionModules(uint8_t qrcode[], int version);
66 static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[]);
67 testable int getAlignmentPatternPositions(int version, uint8_t result[7]);
68 static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[]);
69
70 static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[]);
71 static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask);
72 static long getPenaltyScore(const uint8_t qrcode[]);
73 static int finderPenaltyCountPatterns(const int runHistory[7], int qrsize);
74 static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, int runHistory[7], int qrsize);
75 static void finderPenaltyAddHistory(int currentRunLength, int runHistory[7], int qrsize);
76
77 testable bool getModuleBounded(const uint8_t qrcode[], int x, int y);
78 testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isDark);
79 testable void setModuleUnbounded(uint8_t qrcode[], int x, int y, bool isDark);
80 static bool getBit(int x, int i);
81
82 testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars);
83 testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version);
84 static int numCharCountBits(enum qrcodegen_Mode mode, int version);
85
86 /*---- Private tables of constants ----*/
87
88 // The set of all legal characters in alphanumeric mode, where each character
89 // value maps to the index in the string. For checking text and encoding segments.
90 static const char *ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
abs(int n)91 static int abs(int n)
92 {
93 if (n < 0) {
94 return -n;
95 }
96 return n;
97 }
98
labs(long n)99 static long labs(long n)
100 {
101 if (n < 0) {
102 return -n;
103 }
104 return n;
105 }
106 // For generating error correction codes.
107 testable const int8_t ECC_CODEWORDS_PER_BLOCK[4][41] = {
108 // Version: (note that index 0 is for padding, and is set to an illegal value)
109 //0, 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 Error correction level
110 {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low
111 {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium
112 {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile
113 {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High
114 };
115
116 #define qrcodegen_REED_SOLOMON_DEGREE_MAX 30 // Based on the table above
117
118 // For generating error correction codes.
119 testable const int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41] = {
120 // Version: (note that index 0 is for padding, and is set to an illegal value)
121 //0, 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 Error correction level
122 {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low
123 {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium
124 {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile
125 {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High
126 };
127
128 // For automatic mask pattern selection.
129 static const int PENALTY_N1 = 3;
130 static const int PENALTY_N2 = 3;
131 static const int PENALTY_N3 = 40;
132 static const int PENALTY_N4 = 10;
133
134 #ifdef INT16_MAX
135 #undef INT16_MAX
136 #endif
137 #ifdef SIZE_MAX
138 #undef SIZE_MAX
139 #endif
140 #define INT16_MAX 0x7fff
141 #define SIZE_MAX 65535
142 /*---- High-level QR Code encoding functions ----*/
143
144 // Public function - see documentation comment in header file.
qrcodegen_encodeText(const char * text,uint8_t tempBuffer[],uint8_t qrcode[],enum qrcodegen_Ecc ecl,int minVersion,int maxVersion,enum qrcodegen_Mask mask,bool boostEcl)145 bool qrcodegen_encodeText(const char *text, uint8_t tempBuffer[], uint8_t qrcode[],
146 enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl) {
147
148 size_t textLen = strlen(text);
149 if (textLen == 0)
150 return qrcodegen_encodeSegmentsAdvanced(NULL, 0, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode);
151 size_t bufLen = (size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion);
152
153 struct qrcodegen_Segment seg;
154 if (qrcodegen_isNumeric(text)) {
155 if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_NUMERIC, textLen) > bufLen)
156 goto fail;
157 seg = qrcodegen_makeNumeric(text, tempBuffer);
158 } else if (qrcodegen_isAlphanumeric(text)) {
159 if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_ALPHANUMERIC, textLen) > bufLen)
160 goto fail;
161 seg = qrcodegen_makeAlphanumeric(text, tempBuffer);
162 } else {
163 if (textLen > bufLen)
164 goto fail;
165 size_t i;
166 for (i = 0; i < textLen; i++)
167 tempBuffer[i] = (uint8_t)text[i];
168 seg.mode = qrcodegen_Mode_BYTE;
169 seg.bitLength = calcSegmentBitLength(seg.mode, textLen);
170 if (seg.bitLength == -1)
171 goto fail;
172 seg.numChars = (int)textLen;
173 seg.data = tempBuffer;
174 }
175 return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode);
176
177 fail:
178 qrcode[0] = 0; // Set size to invalid value for safety
179 return false;
180 }
181
182 // Public function - see documentation comment in header file.
qrcodegen_encodeBinary(uint8_t dataAndTemp[],size_t dataLen,uint8_t qrcode[],enum qrcodegen_Ecc ecl,int minVersion,int maxVersion,enum qrcodegen_Mask mask,bool boostEcl)183 bool qrcodegen_encodeBinary(uint8_t dataAndTemp[], size_t dataLen, uint8_t qrcode[],
184 enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl) {
185
186 struct qrcodegen_Segment seg;
187 seg.mode = qrcodegen_Mode_BYTE;
188 seg.bitLength = calcSegmentBitLength(seg.mode, dataLen);
189 if (seg.bitLength == -1) {
190 qrcode[0] = 0; // Set size to invalid value for safety
191 return false;
192 }
193 seg.numChars = (int)dataLen;
194 seg.data = dataAndTemp;
195 return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, dataAndTemp, qrcode);
196 }
197
198 // Appends the given number of low-order bits of the given value to the given byte-based
199 // bit buffer, increasing the bit length. Requires 0 <= numBits <= 16 and val < 2^numBits.
appendBitsToBuffer(unsigned int val,int numBits,uint8_t buffer[],int * bitLen)200 testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int *bitLen) {
201 if(!(0 <= numBits && numBits <= 16 && (unsigned long)val >> numBits == 0))
202 return;
203 int i;
204 for (i = numBits - 1; i >= 0; i--, (*bitLen)++)
205 buffer[*bitLen >> 3] |= ((val >> i) & 1) << (7 - (*bitLen & 7));
206 }
207
208 /*---- Low-level QR Code encoding functions ----*/
209
210 // Public function - see documentation comment in header file.
qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[],size_t len,enum qrcodegen_Ecc ecl,uint8_t tempBuffer[],uint8_t qrcode[])211 bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len,
212 enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[]) {
213 return qrcodegen_encodeSegmentsAdvanced(segs, len, ecl,
214 qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true, tempBuffer, qrcode);
215 }
216
217 // Public function - see documentation comment in header file.
qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[],size_t len,enum qrcodegen_Ecc ecl,int minVersion,int maxVersion,enum qrcodegen_Mask mask,bool boostEcl,uint8_t tempBuffer[],uint8_t qrcode[])218 bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl,
219 int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl, uint8_t tempBuffer[], uint8_t qrcode[]) {
220 if (!(segs != NULL || len == 0))
221 return false;
222 if (!(qrcodegen_VERSION_MIN <= minVersion && minVersion <= maxVersion && maxVersion <= qrcodegen_VERSION_MAX))
223 return false;
224 if (!(0 <= (int)ecl && (int)ecl <= 3 && -1 <= (int)mask && (int)mask <= 7))
225 return false;
226 // Find the minimal version number to use
227 int version, dataUsedBits;
228 for (version = minVersion; ; version++) {
229 int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available
230 dataUsedBits = getTotalBits(segs, len, version);
231 if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
232 break; // This version number is found to be suitable
233 if (version >= maxVersion) { // All versions in the range could not fit the given data
234 qrcode[0] = 0; // Set size to invalid value for safety
235 return false;
236 }
237 }
238 if (dataUsedBits == -1) {
239 return false;
240 }
241 // Increase the error correction level while the data still fits in the current version number
242 int i, j;
243 for (i = (int)qrcodegen_Ecc_MEDIUM; i <= (int)qrcodegen_Ecc_HIGH; i++) { // From low to high
244 if (boostEcl && dataUsedBits <= getNumDataCodewords(version, (enum qrcodegen_Ecc)i) * 8)
245 ecl = (enum qrcodegen_Ecc)i;
246 }
247
248 // Concatenate all segments to create the data bit string
249 memset(qrcode, 0, (size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(version) * sizeof(qrcode[0]));
250 int bitLen = 0;
251 size_t k;
252 for (k = 0; k < len; k++) {
253 const struct qrcodegen_Segment *seg = &segs[k];
254 appendBitsToBuffer((unsigned int)seg->mode, 4, qrcode, &bitLen);
255 appendBitsToBuffer((unsigned int)seg->numChars, numCharCountBits(seg->mode, version), qrcode, &bitLen);
256 for (j = 0; j < seg->bitLength; j++) {
257 int bit = (seg->data[j >> 3] >> (7 - (j & 7))) & 1;
258 appendBitsToBuffer((unsigned int)bit, 1, qrcode, &bitLen);
259 }
260 }
261 if (bitLen != dataUsedBits) {
262 return false;
263 }
264 // Add terminator and pad up to a byte if applicable
265 int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;
266 if (bitLen > dataCapacityBits) {
267 return false;
268 }
269 int terminatorBits = dataCapacityBits - bitLen;
270 if (terminatorBits > 4)
271 terminatorBits = 4;
272 appendBitsToBuffer(0, terminatorBits, qrcode, &bitLen);
273 appendBitsToBuffer(0, (8 - bitLen % 8) % 8, qrcode, &bitLen);
274 if (bitLen % 8 != 0) {
275 return false;
276 }
277 // Pad with alternating bytes until data capacity is reached
278 uint8_t padByte;
279 for (padByte = 0xEC; bitLen < dataCapacityBits; padByte ^= 0xEC ^ 0x11) {
280 appendBitsToBuffer(padByte, 8, qrcode, &bitLen);
281 }
282 // Compute ECC, draw modules
283 addEccAndInterleave(qrcode, version, ecl, tempBuffer);
284 initializeFunctionModules(version, qrcode);
285 drawCodewords(tempBuffer, getNumRawDataModules(version) / 8, qrcode);
286 drawLightFunctionModules(qrcode, version);
287 initializeFunctionModules(version, tempBuffer);
288
289 // Do masking
290 if (mask == qrcodegen_Mask_AUTO) { // Automatically choose best mask
291 long minPenalty = LONG_MAX;
292 for (i = 0; i < 8; i++) {
293 enum qrcodegen_Mask msk = (enum qrcodegen_Mask)i;
294 applyMask(tempBuffer, qrcode, msk);
295 drawFormatBits(ecl, msk, qrcode);
296 long penalty = getPenaltyScore(qrcode);
297 if (penalty < minPenalty) {
298 mask = msk;
299 minPenalty = penalty;
300 }
301 applyMask(tempBuffer, qrcode, msk); // Undoes the mask due to XOR
302 }
303 }
304 if (!(0 <= (int)mask && (int)mask <= 7))
305 return false;
306 applyMask(tempBuffer, qrcode, mask); // Apply the final choice of mask
307 drawFormatBits(ecl, mask, qrcode); // Overwrite old format bits
308 return true;
309 }
310
311 /*---- Error correction code generation functions ----*/
312
313 // Appends error correction bytes to each block of the given data array, then interleaves
314 // bytes from the blocks and stores them in the result array. data[0 : dataLen] contains
315 // the input data. data[dataLen : rawCodewords] is used as a temporary work area and will
316 // be clobbered by this function. The final answer is stored in result[0 : rawCodewords].
addEccAndInterleave(uint8_t data[],int version,enum qrcodegen_Ecc ecl,uint8_t result[])317 testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]) {
318 // Calculate parameter numbers
319 if (!(0 <= (int)ecl && (int)ecl < 4 && qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX)) {
320 return;
321 }
322 int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[(int)ecl][version];
323 int blockEccLen = ECC_CODEWORDS_PER_BLOCK [(int)ecl][version];
324 int rawCodewords = getNumRawDataModules(version) / 8;
325 int dataLen = getNumDataCodewords(version, ecl);
326 int numShortBlocks = numBlocks - rawCodewords % numBlocks;
327 int shortBlockDataLen = rawCodewords / numBlocks - blockEccLen;
328
329 // Split data into blocks, calculate ECC, and interleave
330 // (not concatenate) the bytes into a single sequence
331 uint8_t rsdiv[qrcodegen_REED_SOLOMON_DEGREE_MAX];
332 reedSolomonComputeDivisor(blockEccLen, rsdiv);
333 const uint8_t *dat = data;
334 int i, j, k;
335 for (i = 0; i < numBlocks; i++) {
336 int datLen = shortBlockDataLen + (i < numShortBlocks ? 0 : 1);
337 uint8_t *ecc = &data[dataLen]; // Temporary storage
338 reedSolomonComputeRemainder(dat, datLen, rsdiv, blockEccLen, ecc);
339 for (j = 0, k = i; j < datLen; j++, k += numBlocks) { // Copy data
340 if (j == shortBlockDataLen)
341 k -= numShortBlocks;
342 result[k] = dat[j];
343 }
344 for (j = 0, k = dataLen + i; j < blockEccLen; j++, k += numBlocks) // Copy ECC
345 result[k] = ecc[j];
346 dat += datLen;
347 }
348 }
349
350 // Returns the number of 8-bit codewords that can be used for storing data (not ECC),
351 // for the given version number and error correction level. The result is in the range [9, 2956].
getNumDataCodewords(int version,enum qrcodegen_Ecc ecl)352 testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl) {
353 int v = version, e = (int)ecl;
354 if (!(0 <= e && e < 4)) {
355 return 0;
356 }
357 return getNumRawDataModules(v) / 8
358 - ECC_CODEWORDS_PER_BLOCK [e][v]
359 * NUM_ERROR_CORRECTION_BLOCKS[e][v];
360 }
361
362
363 // Returns the number of data bits that can be stored in a QR Code of the given version number, after
364 // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
365 // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
getNumRawDataModules(int ver)366 testable int getNumRawDataModules(int ver) {
367 if (!(qrcodegen_VERSION_MIN <= ver && ver <= qrcodegen_VERSION_MAX)) {
368 return 0;
369 }
370 int result = (16 * ver + 128) * ver + 64;
371 if (ver >= 2) {
372 int numAlign = ver / 7 + 2;
373 result -= (25 * numAlign - 10) * numAlign - 55;
374 if (ver >= 7)
375 result -= 36;
376 }
377 if (!(208 <= result && result <= 29648)) {
378 return 0;
379 }
380 return result;
381 }
382
383 /*---- Reed-Solomon ECC generator functions ----*/
384
385 // Computes a Reed-Solomon ECC generator polynomial for the given degree, storing in result[0 : degree].
386 // This could be implemented as a lookup table over all possible parameter values, instead of as an algorithm.
reedSolomonComputeDivisor(int degree,uint8_t result[])387 testable void reedSolomonComputeDivisor(int degree, uint8_t result[]) {
388 if (!(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX)) {
389 return;
390 }
391 // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
392 // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
393 memset(result, 0, (size_t)degree * sizeof(result[0]));
394 result[degree - 1] = 1; // Start off with the monomial x^0
395 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
396 // drop the highest monomial term which is always 1x^degree.
397 // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
398 uint8_t root = 1;
399 int i, j;
400 for (i = 0; i < degree; i++) {
401 // Multiply the current product by (x - r^i)
402 for (j = 0; j < degree; j++) {
403 result[j] = reedSolomonMultiply(result[j], root);
404 if (j + 1 < degree)
405 result[j] ^= result[j + 1];
406 }
407 root = reedSolomonMultiply(root, 0x02);
408 }
409 }
410
411 // Computes the Reed-Solomon error correction codeword for the given data and divisor polynomials.
412 // The remainder when data[0 : dataLen] is divided by divisor[0 : degree] is stored in result[0 : degree].
413 // All polynomials are in big endian, and the generator has an implicit leading 1 term.
reedSolomonComputeRemainder(const uint8_t data[],int dataLen,const uint8_t generator[],int degree,uint8_t result[])414 testable void reedSolomonComputeRemainder(const uint8_t data[], int dataLen,
415 const uint8_t generator[], int degree, uint8_t result[]) {
416 if (!(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX)) {
417 return;
418 }
419 memset(result, 0, (size_t)degree * sizeof(result[0]));
420 int i, j;
421 for (i = 0; i < dataLen; i++) { // Polynomial division
422 uint8_t factor = data[i] ^ result[0];
423 memmove(&result[0], &result[1], (size_t)(degree - 1) * sizeof(result[0]));
424 result[degree - 1] = 0;
425 for (j = 0; j < degree; j++)
426 result[j] ^= reedSolomonMultiply(generator[j], factor);
427 }
428 }
429
430 #undef qrcodegen_REED_SOLOMON_DEGREE_MAX
431
432 // Returns the product of the two given field elements modulo GF(2^8/0x11D).
433 // All inputs are valid. This could be implemented as a 256*256 lookup table.
reedSolomonMultiply(uint8_t x,uint8_t y)434 testable uint8_t reedSolomonMultiply(uint8_t x, uint8_t y) {
435 // Russian peasant multiplication
436 uint8_t z = 0;
437 int i;
438 for (i = 7; i >= 0; i--) {
439 z = (uint8_t)((z << 1) ^ ((z >> 7) * 0x11D));
440 z ^= ((y >> i) & 1) * x;
441 }
442 return z;
443 }
444
445 /*---- Drawing function modules ----*/
446
447 // Clears the given QR Code grid with light modules for the given
448 // version's size, then marks every function module as dark.
initializeFunctionModules(int version,uint8_t qrcode[])449 testable void initializeFunctionModules(int version, uint8_t qrcode[]) {
450 // Initialize QR Code
451 int qrsize = version * 4 + 17;
452 memset(qrcode, 0, (size_t)((qrsize * qrsize + 7) / 8 + 1) * sizeof(qrcode[0]));
453 qrcode[0] = (uint8_t)qrsize;
454
455 // Fill horizontal and vertical timing patterns
456 fillRectangle(6, 0, 1, qrsize, qrcode);
457 fillRectangle(0, 6, qrsize, 1, qrcode);
458
459 // Fill 3 finder patterns (all corners except bottom right) and format bits
460 fillRectangle(0, 0, 9, 9, qrcode);
461 fillRectangle(qrsize - 8, 0, 8, 9, qrcode);
462 fillRectangle(0, qrsize - 8, 9, 8, qrcode);
463
464 // Fill numerous alignment patterns
465 uint8_t alignPatPos[7];
466 int numAlign = getAlignmentPatternPositions(version, alignPatPos);
467 int i, j;
468 for (i = 0; i < numAlign; i++) {
469 for (j = 0; j < numAlign; j++) {
470 // Don't draw on the three finder corners
471 if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))
472 fillRectangle(alignPatPos[i] - 2, alignPatPos[j] - 2, 5, 5, qrcode);
473 }
474 }
475
476 // Fill version blocks
477 if (version >= 7) {
478 fillRectangle(qrsize - 11, 0, 3, 6, qrcode);
479 fillRectangle(0, qrsize - 11, 6, 3, qrcode);
480 }
481 }
482
483
484 // Draws light function modules and possibly some dark modules onto the given QR Code, without changing
485 // non-function modules. This does not draw the format bits. This requires all function modules to be previously
486 // marked dark (namely by initializeFunctionModules()), because this may skip redrawing dark function modules.
drawLightFunctionModules(uint8_t qrcode[],int version)487 static void drawLightFunctionModules(uint8_t qrcode[], int version) {
488 // Draw horizontal and vertical timing patterns
489 int qrsize = qrcodegen_getSize(qrcode);
490 int i, j, dx, dy;
491 for (i = 7; i < qrsize - 7; i += 2) {
492 setModuleBounded(qrcode, 6, i, false);
493 setModuleBounded(qrcode, i, 6, false);
494 }
495
496 // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
497 for (dy = -4; dy <= 4; dy++) {
498 for (dx = -4; dx <= 4; dx++) {
499 int dist = abs(dx);
500 if (abs(dy) > dist) {
501 dist = abs(dy);
502 }
503 if (dist == 2 || dist == 4) {
504 setModuleUnbounded(qrcode, 3 + dx, 3 + dy, false);
505 setModuleUnbounded(qrcode, qrsize - 4 + dx, 3 + dy, false);
506 setModuleUnbounded(qrcode, 3 + dx, qrsize - 4 + dy, false);
507 }
508 }
509 }
510
511 // Draw numerous alignment patterns
512 uint8_t alignPatPos[7];
513 int numAlign = getAlignmentPatternPositions(version, alignPatPos);
514 for (i = 0; i < numAlign; i++) {
515 for (j = 0; j < numAlign; j++) {
516 if ((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))
517 continue; // Don't draw on the three finder corners
518 for (dy = -1; dy <= 1; dy++) {
519 for (dx = -1; dx <= 1; dx++)
520 setModuleBounded(qrcode, alignPatPos[i] + dx, alignPatPos[j] + dy, dx == 0 && dy == 0);
521 }
522 }
523 }
524
525 // Draw version blocks
526 if (version >= 7) {
527 // Calculate error correction code and pack bits
528 int rem = version; // version is uint6, in the range [7, 40]
529 for (i = 0; i < 12; i++)
530 rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
531 long bits = (long)version << 12 | rem; // uint18
532 if (!(bits >> 18 == 0)) {
533 return;
534 }
535 // Draw two copies
536 for (i = 0; i < 6; i++) {
537 for (j = 0; j < 3; j++) {
538 int k = qrsize - 11 + j;
539 setModuleBounded(qrcode, k, i, (bits & 1) != 0);
540 setModuleBounded(qrcode, i, k, (bits & 1) != 0);
541 bits >>= 1;
542 }
543 }
544 }
545 }
546
547
548 // Draws two copies of the format bits (with its own error correction code) based
549 // on the given mask and error correction level. This always draws all modules of
550 // the format bits, unlike drawLightFunctionModules() which might skip dark modules.
drawFormatBits(enum qrcodegen_Ecc ecl,enum qrcodegen_Mask mask,uint8_t qrcode[])551 static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[]) {
552 // Calculate error correction code and pack bits
553 if (!(0 <= (int)mask && (int)mask <= 7)) {
554 return;
555 }
556 static const int table[] = {1, 0, 3, 2};
557 int data = table[(int)ecl] << 3 | (int)mask; // errCorrLvl is uint2, mask is uint3
558 int rem = data;
559 int i;
560 for (i = 0; i < 10; i++)
561 rem = (rem << 1) ^ ((rem >> 9) * 0x537);
562 int bits = (data << 10 | rem) ^ 0x5412; // uint15
563 if (!(bits >> 15 == 0)) {
564 return;
565 }
566 // Draw first copy
567 for (i = 0; i <= 5; i++)
568 setModuleBounded(qrcode, 8, i, getBit(bits, i));
569 setModuleBounded(qrcode, 8, 7, getBit(bits, 6));
570 setModuleBounded(qrcode, 8, 8, getBit(bits, 7));
571 setModuleBounded(qrcode, 7, 8, getBit(bits, 8));
572 for (i = 9; i < 15; i++)
573 setModuleBounded(qrcode, 14 - i, 8, getBit(bits, i));
574
575 // Draw second copy
576 int qrsize = qrcodegen_getSize(qrcode);
577 for (i = 0; i < 8; i++)
578 setModuleBounded(qrcode, qrsize - 1 - i, 8, getBit(bits, i));
579 for (i = 8; i < 15; i++)
580 setModuleBounded(qrcode, 8, qrsize - 15 + i, getBit(bits, i));
581 setModuleBounded(qrcode, 8, qrsize - 8, true); // Always dark
582 }
583
584 // Calculates and stores an ascending list of positions of alignment patterns
585 // for this version number, returning the length of the list (in the range [0,7]).
586 // Each position is in the range [0,177), and are used on both the x and y axes.
587 // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
getAlignmentPatternPositions(int version,uint8_t result[7])588 testable int getAlignmentPatternPositions(int version, uint8_t result[7]) {
589 if (version == 1)
590 return 0;
591 int numAlign = version / 7 + 2;
592 int step = (version == 32) ? 26 :
593 (version*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2;
594 int i, pos;
595 for (i = numAlign - 1, pos = version * 4 + 10; i >= 1; i--, pos -= step)
596 result[i] = (uint8_t)pos;
597 result[0] = 6;
598 return numAlign;
599 }
600
601
602 // Sets every module in the range [left : left + width] * [top : top + height] to dark.
fillRectangle(int left,int top,int width,int height,uint8_t qrcode[])603 static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[]) {
604 int dy, dx;
605 for (dy = 0; dy < height; dy++) {
606 for (dx = 0; dx < width; dx++)
607 setModuleBounded(qrcode, left + dx, top + dy, true);
608 }
609 }
610
611 /*---- Drawing data modules and masking ----*/
612
613 // Draws the raw codewords (including data and ECC) onto the given QR Code. This requires the initial state of
drawCodewords(const uint8_t data[],int dataLen,uint8_t qrcode[])614 static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[]) {
615 int qrsize = qrcodegen_getSize(qrcode);
616 int i = 0; // Bit index into the data
617 // Do the funny zigzag scan
618 int right, vert, j;
619 for (right = qrsize - 1; right >= 1; right -= 2) { // Index of right column in each column pair
620 if (right == 6)
621 right = 5;
622 for (vert = 0; vert < qrsize; vert++) { // Vertical counter
623 for (j = 0; j < 2; j++) {
624 int x = right - j; // Actual x coordinate
625 bool upward = ((right + 1) & 2) == 0;
626 int y = upward ? qrsize - 1 - vert : vert; // Actual y coordinate
627 if (!getModuleBounded(qrcode, x, y) && i < dataLen * 8) {
628 bool dark = getBit(data[i >> 3], 7 - (i & 7));
629 setModuleBounded(qrcode, x, y, dark);
630 i++;
631 }
632 // If this QR Code has any remainder bits (0 to 7), they were assigned as
633 // 0/false/light by the constructor and are left unchanged by this method
634 }
635 }
636 }
637 if (!(i == dataLen * 8)) {
638 return;
639 }
640 }
641
642
643 // XORs the codeword modules in this QR Code with the given mask pattern
644 // and given pattern of function modules. The codeword bits must be drawn
645 // before masking. Due to the arithmetic of XOR, calling applyMask() with
646 // the same mask value a second time will undo the mask. A final well-formed
647 // QR Code needs exactly one (not zero, two, etc.) mask applied.
applyMask(const uint8_t functionModules[],uint8_t qrcode[],enum qrcodegen_Mask mask)648 static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask) {
649 if (!(0 <= (int)mask && (int)mask <= 7)) { // Disallows qrcodegen_Mask_AUTO
650 return;
651 }
652 int qrsize = qrcodegen_getSize(qrcode);
653 int x, y;
654 for (y = 0; y < qrsize; y++) {
655 for (x = 0; x < qrsize; x++) {
656 if (getModuleBounded(functionModules, x, y))
657 continue;
658 bool invert;
659 switch ((int)mask) {
660 case 0: invert = (x + y) % 2 == 0; break;
661 case 1: invert = y % 2 == 0; break;
662 case 2: invert = x % 3 == 0; break;
663 case 3: invert = (x + y) % 3 == 0; break;
664 case 4: invert = (x / 3 + y / 2) % 2 == 0; break;
665 case 5: invert = x * y % 2 + x * y % 3 == 0; break;
666 case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
667 case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
668 default: return;
669 }
670 bool val = getModuleBounded(qrcode, x, y);
671 setModuleBounded(qrcode, x, y, val ^ invert);
672 }
673 }
674 }
675
676 // Calculates and returns the penalty score based on state of the given QR Code's current modules.
677 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
getPenaltyScore(const uint8_t qrcode[])678 static long getPenaltyScore(const uint8_t qrcode[]) {
679 int qrsize = qrcodegen_getSize(qrcode);
680 long result = 0;
681 // Adjacent modules in row having same color, and finder-like patterns
682 int x, y;
683 for (y = 0; y < qrsize; y++) {
684 bool runColor = false;
685 int runX = 0;
686 int runHistory[7] = {0};
687 for (x = 0; x < qrsize; x++) {
688 if (getModuleBounded(qrcode, x, y) == runColor) {
689 runX++;
690 if (runX == 5)
691 result += PENALTY_N1;
692 else if (runX > 5)
693 result++;
694 } else {
695 finderPenaltyAddHistory(runX, runHistory, qrsize);
696 if (!runColor)
697 result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3;
698 runColor = getModuleBounded(qrcode, x, y);
699 runX = 1;
700 }
701 }
702 result += finderPenaltyTerminateAndCount(runColor, runX, runHistory, qrsize) * PENALTY_N3;
703 }
704 // Adjacent modules in column having same color, and finder-like patterns
705 for (x = 0; x < qrsize; x++) {
706 bool runColor = false;
707 int runY = 0;
708 int runHistory[7] = {0};
709 for (y = 0; y < qrsize; y++) {
710 if (getModuleBounded(qrcode, x, y) == runColor) {
711 runY++;
712 if (runY == 5)
713 result += PENALTY_N1;
714 else if (runY > 5)
715 result++;
716 } else {
717 finderPenaltyAddHistory(runY, runHistory, qrsize);
718 if (!runColor)
719 result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3;
720 runColor = getModuleBounded(qrcode, x, y);
721 runY = 1;
722 }
723 }
724 result += finderPenaltyTerminateAndCount(runColor, runY, runHistory, qrsize) * PENALTY_N3;
725 }
726
727 // 2*2 blocks of modules having same color
728 for (y = 0; y < qrsize - 1; y++) {
729 for (x = 0; x < qrsize - 1; x++) {
730 bool color = getModuleBounded(qrcode, x, y);
731 if ( color == getModuleBounded(qrcode, x + 1, y) &&
732 color == getModuleBounded(qrcode, x, y + 1) &&
733 color == getModuleBounded(qrcode, x + 1, y + 1))
734 result += PENALTY_N2;
735 }
736 }
737
738 // Balance of dark and light modules
739 int dark = 0;
740 for (y = 0; y < qrsize; y++) {
741 for (x = 0; x < qrsize; x++) {
742 if (getModuleBounded(qrcode, x, y))
743 dark++;
744 }
745 }
746 int total = qrsize * qrsize; // Note that size is odd, so dark/total != 1/2
747 // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
748 int k = (int)((labs(dark * 20L - total * 10L) + total - 1) / total) - 1;
749 if (0 <= k && k <= 9) {
750 return 0;
751 }
752 result += k * PENALTY_N4;
753 if (0 <= result && result <= 2568888L) { // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
754 return 0;
755 }
756 return result;
757 }
758
759 // Can only be called immediately after a light run is added, and
760 // returns either 0, 1, or 2. A helper function for getPenaltyScore().
finderPenaltyCountPatterns(const int runHistory[7],int qrsize)761 static int finderPenaltyCountPatterns(const int runHistory[7], int qrsize) {
762 int n = runHistory[1];
763 if (!(n <= qrsize * 3)) {
764 return -1;
765 }
766 (void)qrsize;
767 bool core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
768 // The maximum QR Code size is 177, hence the dark run length n <= 177.
769 // Arithmetic is promoted to int, so n*4 will not overflow.
770 return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) +
771 (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
772 }
773
774 // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
finderPenaltyTerminateAndCount(bool currentRunColor,int currentRunLength,int runHistory[7],int qrsize)775 static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, int runHistory[7], int qrsize) {
776 if (currentRunColor) { // Terminate dark run
777 finderPenaltyAddHistory(currentRunLength, runHistory, qrsize);
778 currentRunLength = 0;
779 }
780 currentRunLength += qrsize; // Add light border to final run
781 finderPenaltyAddHistory(currentRunLength, runHistory, qrsize);
782 return finderPenaltyCountPatterns(runHistory, qrsize);
783 }
784
785 // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
finderPenaltyAddHistory(int currentRunLength,int runHistory[7],int qrsize)786 static void finderPenaltyAddHistory(int currentRunLength, int runHistory[7], int qrsize) {
787 if (runHistory[0] == 0)
788 currentRunLength += qrsize; // Add light border to initial run
789 memmove(&runHistory[1], &runHistory[0], 6 * sizeof(runHistory[0]));
790 runHistory[0] = currentRunLength;
791 }
792
793 /*---- Basic QR Code information ----*/
794 // Public function - see documentation comment in header file.
qrcodegen_getSize(const uint8_t qrcode[])795 int qrcodegen_getSize(const uint8_t qrcode[]) {
796 if(!(qrcode != NULL)) {
797 return 0;
798 }
799 int result = qrcode[0];
800 if(!((qrcodegen_VERSION_MIN * 4 + 17) <= result &&
801 result <= (qrcodegen_VERSION_MAX * 4 + 17))) {
802 return 0;
803 }
804 return result;
805 }
806
807 // Public function - see documentation comment in header file.
qrcodegen_getModule(const uint8_t qrcode[],int x,int y)808 bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y) {
809 if(!(qrcode != NULL)) {
810 return false;
811 }
812 int qrsize = qrcode[0];
813 return (0 <= x && x < qrsize && 0 <= y && y < qrsize) && getModuleBounded(qrcode, x, y);
814 }
815
816
817 // Returns the color of the module at the given coordinates, which must be in bounds.
getModuleBounded(const uint8_t qrcode[],int x,int y)818 testable bool getModuleBounded(const uint8_t qrcode[], int x, int y) {
819 int qrsize = qrcode[0];
820 if (!(21 <= qrsize && qrsize <= 177 &&
821 0 <= x && x < qrsize && 0 <= y && y < qrsize)) {
822 return false;
823 }
824 int index = y * qrsize + x;
825 return getBit(qrcode[(index >> 3) + 1], index & 7);
826 }
827
828
829 // Sets the color of the module at the given coordinates, which must be in bounds.
setModuleBounded(uint8_t qrcode[],int x,int y,bool isDark)830 testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isDark) {
831 int qrsize = qrcode[0];
832 if (!(21 <= qrsize && qrsize <= 177 &&
833 0 <= x && x < qrsize && 0 <= y && y < qrsize)) {
834 return;
835 }
836 int index = y * qrsize + x;
837 int bitIndex = index & 7;
838 int byteIndex = (index >> 3) + 1;
839 if (isDark) {
840 qrcode[byteIndex] |= 1 << bitIndex;
841 }
842 else
843 qrcode[byteIndex] &= (1 << bitIndex) ^ 0xFF;
844 }
845
846
847 // Sets the color of the module at the given coordinates, doing nothing if out of bounds.
setModuleUnbounded(uint8_t qrcode[],int x,int y,bool isDark)848 testable void setModuleUnbounded(uint8_t qrcode[], int x, int y, bool isDark) {
849 int qrsize = qrcode[0];
850 if (0 <= x && x < qrsize && 0 <= y && y < qrsize)
851 setModuleBounded(qrcode, x, y, isDark);
852 }
853
854 // Public function - see documentation comment in header file.
qrcodegen_isAlphanumeric(const char * text)855 bool qrcodegen_isAlphanumeric(const char *text) {
856 if (text == NULL) {
857 return false;
858 }
859 for (; *text != '\0'; text++) {
860 if (strchr(ALPHANUMERIC_CHARSET, *text) == NULL)
861 return false;
862 }
863 return true;
864 }
865
866 // Returns true iff the i'th bit of x is set to 1. Requires x >= 0 and 0 <= i <= 14.
getBit(int x,int i)867 static bool getBit(int x, int i) {
868 return ((x >> i) & 1) != 0;
869 }
870
871 /*---- Segment handling ----*/
872
873 // Public function - see documentation comment in header file.
qrcodegen_isNumeric(const char * text)874 bool qrcodegen_isNumeric(const char *text) {
875 if (text == NULL) {
876 return false;
877 }
878 for (; *text != '\0'; text++) {
879 if (*text < '0' || *text > '9')
880 return false;
881 }
882 return true;
883 }
884
885 // Public function - see documentation comment in header file.
qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode,size_t numChars)886 size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars) {
887 int temp = calcSegmentBitLength(mode, numChars);
888 if (temp == -1) {
889 return SIZE_MAX;
890 }
891 if (!(0 <= temp && temp <= INT16_MAX)) {
892 return SIZE_MAX;
893 }
894 return ((size_t)temp + 7) / 8;
895 }
896
897 // Returns the number of data bits needed to represent a segment
898 // containing the given number of characters using the given mode. Notes:
899 // - Returns -1 on failure, i.e. numChars > INT16_MAX or
900 // the number of needed bits exceeds INT16_MAX (i.e. 32767).
901 // - Otherwise, all valid results are in the range [0, INT16_MAX].
902 // - For byte mode, numChars measures the number of bytes, not Unicode code points.
903 // - For ECI mode, numChars must be 0, and the worst-case number of bits is returned.
904 // An actual ECI segment can have shorter data. For non-ECI modes, the result is exact.
calcSegmentBitLength(enum qrcodegen_Mode mode,size_t numChars)905 testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars) {
906 // All calculations are designed to avoid overflow on all platforms
907 if (numChars > (unsigned int)INT16_MAX)
908 return -1;
909 long result = (long)numChars;
910 if (mode == qrcodegen_Mode_NUMERIC)
911 result = (result * 10 + 2) / 3; // ceil(10/3 * n)
912 else if (mode == qrcodegen_Mode_ALPHANUMERIC)
913 result = (result * 11 + 1) / 2; // ceil(11/2 * n)
914 else if (mode == qrcodegen_Mode_BYTE)
915 result *= 8;
916 else if (mode == qrcodegen_Mode_KANJI)
917 result *= 13;
918 else if (mode == qrcodegen_Mode_ECI && numChars == 0)
919 result = 3 * 8;
920 else { // Invalid argument
921 return -1;
922 }
923 if (result < 0) {
924 return -1;
925 }
926 if (result > INT16_MAX)
927 return -1;
928 return (int)result;
929 }
930
931 // Public function - see documentation comment in header file.
qrcodegen_makeBytes(const uint8_t data[],size_t len,uint8_t buf[])932 struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]) {
933 struct qrcodegen_Segment result;
934 result.mode = qrcodegen_Mode_BYTE;
935 result.bitLength = calcSegmentBitLength(result.mode, len);
936 result.numChars = (int)len;
937 if (len > 0)
938 memcpy(buf, data, len * sizeof(buf[0]));
939 result.data = buf;
940 return result;
941 }
942
943 // Public function - see documentation comment in header file.
qrcodegen_makeNumeric(const char * digits,uint8_t buf[])944 struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]) {
945 struct qrcodegen_Segment result;
946 size_t len = strlen(digits);
947 result.mode = qrcodegen_Mode_NUMERIC;
948 int bitLen = calcSegmentBitLength(result.mode, len);
949 result.numChars = (int)len;
950 if (bitLen > 0)
951 memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0]));
952 result.bitLength = 0;
953
954 unsigned int accumData = 0;
955 int accumCount = 0;
956 for (; *digits != '\0'; digits++) {
957 char c = *digits;
958 accumData = accumData * 10 + (unsigned int)(c - '0');
959 accumCount++;
960 if (accumCount == 3) {
961 appendBitsToBuffer(accumData, 10, buf, &result.bitLength);
962 accumData = 0;
963 accumCount = 0;
964 }
965 }
966 if (accumCount > 0) // 1 or 2 digits remaining
967 appendBitsToBuffer(accumData, accumCount * 3 + 1, buf, &result.bitLength);
968 result.data = buf;
969 return result;
970 }
971
972 // Public function - see documentation comment in header file.
qrcodegen_makeAlphanumeric(const char * text,uint8_t buf[])973 struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]) {
974 struct qrcodegen_Segment result;
975 size_t len = strlen(text);
976 result.mode = qrcodegen_Mode_ALPHANUMERIC;
977 int bitLen = calcSegmentBitLength(result.mode, len);
978 result.numChars = (int)len;
979 if (bitLen > 0)
980 memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0]));
981 result.bitLength = 0;
982
983 unsigned int accumData = 0;
984 int accumCount = 0;
985 for (; *text != '\0'; text++) {
986 const char *temp = (char *)strchr(ALPHANUMERIC_CHARSET, *text);
987 accumData = accumData * 45 + (unsigned int)(temp - ALPHANUMERIC_CHARSET);
988 accumCount++;
989 if (accumCount == 2) {
990 appendBitsToBuffer(accumData, 11, buf, &result.bitLength);
991 accumData = 0;
992 accumCount = 0;
993 }
994 }
995 if (accumCount > 0) // 1 character remaining
996 appendBitsToBuffer(accumData, 6, buf, &result.bitLength);
997 result.data = buf;
998 return result;
999 }
1000
1001 // Public function - see documentation comment in header file.
qrcodegen_makeEci(long assignVal,uint8_t buf[])1002 struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]) {
1003 struct qrcodegen_Segment result;
1004 result.mode = qrcodegen_Mode_ECI;
1005 result.numChars = 0;
1006 result.bitLength = 0;
1007 if (assignVal < 0)
1008 return result;
1009 else if (assignVal < (1 << 7)) {
1010 memset(buf, 0, 1 * sizeof(buf[0]));
1011 appendBitsToBuffer((unsigned int)assignVal, 8, buf, &result.bitLength);
1012 } else if (assignVal < (1 << 14)) {
1013 memset(buf, 0, 2 * sizeof(buf[0]));
1014 appendBitsToBuffer(2, 2, buf, &result.bitLength);
1015 appendBitsToBuffer((unsigned int)assignVal, 14, buf, &result.bitLength);
1016 } else if (assignVal < 1000000L) {
1017 memset(buf, 0, 3 * sizeof(buf[0]));
1018 appendBitsToBuffer(6, 3, buf, &result.bitLength);
1019 appendBitsToBuffer((unsigned int)(assignVal >> 10), 11, buf, &result.bitLength);
1020 appendBitsToBuffer((unsigned int)(assignVal & 0x3FF), 10, buf, &result.bitLength);
1021 } else
1022 return result;
1023 result.data = buf;
1024 return result;
1025 }
1026
1027 // Calculates the number of bits needed to encode the given segments at the given version.
1028 // Returns a non-negative number if successful. Otherwise returns -1 if a segment has too
1029 // many characters to fit its length field, or the total bits exceeds INT16_MAX.
getTotalBits(const struct qrcodegen_Segment segs[],size_t len,int version)1030 testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version) {
1031 if (!(segs != NULL || len == 0)) {
1032 return -1;
1033 }
1034 long result = 0;
1035 size_t i;
1036 for (i = 0; i < len; i++) {
1037 int numChars = segs[i].numChars;
1038 int bitLength = segs[i].bitLength;
1039 if (!(0 <= numChars && numChars <= INT16_MAX)) {
1040 return -1;
1041 }
1042 if (!(0 <= bitLength && bitLength <= INT16_MAX)) {
1043 return -1;
1044 }
1045 int ccbits = numCharCountBits(segs[i].mode, version);
1046 if (!(0 <= ccbits && ccbits <= 16)) {
1047 return -1;
1048 }
1049 if (numChars >= (1L << ccbits))
1050 return -1; // The segment's length doesn't fit the field's bit width
1051 result += 4L + ccbits + bitLength;
1052 if (result > INT16_MAX)
1053 return -1; // The sum might overflow an int type
1054 }
1055 if (!(0 <= result && result <= INT16_MAX)) {
1056 return -1;
1057 }
1058 return (int)result;
1059 }
1060
1061 // Returns the bit width of the character count field for a segment in the given mode
1062 // in a QR Code at the given version number. The result is in the range [0, 16].
numCharCountBits(enum qrcodegen_Mode mode,int version)1063 static int numCharCountBits(enum qrcodegen_Mode mode, int version) {
1064 if (!(qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX)) {
1065 return -1;
1066 }
1067 int i = (version + 7) / 17;
1068 switch (mode) {
1069 case qrcodegen_Mode_NUMERIC : { static const int temp[] = {10, 12, 14}; return temp[i]; }
1070 case qrcodegen_Mode_ALPHANUMERIC: { static const int temp[] = { 9, 11, 13}; return temp[i]; }
1071 case qrcodegen_Mode_BYTE : { static const int temp[] = { 8, 16, 16}; return temp[i]; }
1072 case qrcodegen_Mode_KANJI : { static const int temp[] = { 8, 10, 12}; return temp[i]; }
1073 case qrcodegen_Mode_ECI : return 0;
1074 default: return(false); return -1; // Dummy value
1075 }
1076 }
1077