qrcodegen.c 41 KB

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