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