qrcodegen.c 40 KB

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