1 /++ 2 This is a port of the C code from https://www.nayuki.io/page/qr-code-generator-library 3 4 History: 5 Originally written in C by Project Nayuki. 6 7 Ported to D by me on July 26, 2021 8 +/ 9 /* 10 * QR Code generator library (C) 11 * 12 * Copyright (c) Project Nayuki. (MIT License) 13 * https://www.nayuki.io/page/qr-code-generator-library 14 * 15 * Permission is hereby granted, free of charge, to any person obtaining a copy of 16 * this software and associated documentation files (the "Software"), to deal in 17 * the Software without restriction, including without limitation the rights to 18 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 19 * the Software, and to permit persons to whom the Software is furnished to do so, 20 * subject to the following conditions: 21 * - The above copyright notice and this permission notice shall be included in 22 * all copies or substantial portions of the Software. 23 * - The Software is provided "as is", without warranty of any kind, express or 24 * implied, including but not limited to the warranties of merchantability, 25 * fitness for a particular purpose and noninfringement. In no event shall the 26 * authors or copyright holders be liable for any claim, damages or other 27 * liability, whether in an action of contract, tort or otherwise, arising from, 28 * out of or in connection with the Software or the use or other dealings in the 29 * Software. 30 */ 31 module arsd.qrcode; 32 33 /// 34 unittest { 35 import arsd.qrcode; 36 37 void main() { 38 import arsd.simpledisplay; 39 40 QrCode code = QrCode("http://arsdnet.net/"); 41 42 enum drawsize = 4; 43 // you have to have some border around it 44 auto window = new SimpleWindow(code.size * drawsize + 80, code.size * drawsize + 80); 45 46 { 47 auto painter = window.draw; 48 painter.clear(Color.white); 49 50 foreach(y; 0 .. code.size) 51 foreach(x; 0 .. code.size) { 52 if(code[x, y]) { 53 painter.outlineColor = Color.black; 54 painter.fillColor = Color.black; 55 } else { 56 painter.outlineColor = Color.white; 57 painter.fillColor = Color.white; 58 } 59 painter.drawRectangle(Point(x * drawsize + 40, y * drawsize + 40), Size(drawsize, drawsize)); 60 } 61 } 62 63 window.eventLoop(0); 64 } 65 66 main; // exclude from docs 67 } 68 69 import core.stdc.stddef; 70 import core.stdc.stdint; 71 import core.stdc.string; 72 import core.stdc.config; 73 import core.stdc.stdlib; 74 import core.stdc.math; 75 76 /* 77 * This library creates QR Code symbols, which is a type of two-dimension barcode. 78 * Invented by Denso Wave and described in the ISO/IEC 18004 standard. 79 * A QR Code structure is an immutable square grid of black and white cells. 80 * The library provides functions to create a QR Code from text or binary data. 81 * The library covers the QR Code Model 2 specification, supporting all versions (sizes) 82 * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. 83 * 84 * Ways to create a QR Code object: 85 * - High level: Take the payload data and call qrcodegen_encodeText() or qrcodegen_encodeBinary(). 86 * - Low level: Custom-make the list of segments and call 87 * qrcodegen_encodeSegments() or qrcodegen_encodeSegmentsAdvanced(). 88 * (Note that all ways require supplying the desired error correction level and various byte buffers.) 89 */ 90 91 92 /*---- Enum and struct types----*/ 93 94 /* 95 * The error correction level in a QR Code symbol. 96 */ 97 98 alias qrcodegen_Ecc = int; 99 100 enum /*qrcodegen_Ecc*/ { 101 // Must be declared in ascending order of error protection 102 // so that an internal qrcodegen function works properly 103 qrcodegen_Ecc_LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords 104 qrcodegen_Ecc_MEDIUM , // The QR Code can tolerate about 15% erroneous codewords 105 qrcodegen_Ecc_QUARTILE, // The QR Code can tolerate about 25% erroneous codewords 106 qrcodegen_Ecc_HIGH , // The QR Code can tolerate about 30% erroneous codewords 107 } 108 109 110 /* 111 * The mask pattern used in a QR Code symbol. 112 */ 113 alias qrcodegen_Mask = int; 114 enum /* qrcodegen_Mask */ { 115 // A special value to tell the QR Code encoder to 116 // automatically select an appropriate mask pattern 117 qrcodegen_Mask_AUTO = -1, 118 // The eight actual mask patterns 119 qrcodegen_Mask_0 = 0, 120 qrcodegen_Mask_1, 121 qrcodegen_Mask_2, 122 qrcodegen_Mask_3, 123 qrcodegen_Mask_4, 124 qrcodegen_Mask_5, 125 qrcodegen_Mask_6, 126 qrcodegen_Mask_7, 127 } 128 129 130 /* 131 * Describes how a segment's data bits are interpreted. 132 */ 133 alias qrcodegen_Mode = int; 134 enum /*qrcodegen_Mode*/ { 135 qrcodegen_Mode_NUMERIC = 0x1, 136 qrcodegen_Mode_ALPHANUMERIC = 0x2, 137 qrcodegen_Mode_BYTE = 0x4, 138 qrcodegen_Mode_KANJI = 0x8, 139 qrcodegen_Mode_ECI = 0x7, 140 } 141 142 143 /* 144 * A segment of character/binary/control data in a QR Code symbol. 145 * The mid-level way to create a segment is to take the payload data 146 * and call a factory function such as qrcodegen_makeNumeric(). 147 * The low-level way to create a segment is to custom-make the bit buffer 148 * and initialize a qrcodegen_Segment struct with appropriate values. 149 * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. 150 * Any segment longer than this is meaningless for the purpose of generating QR Codes. 151 * Moreover, the maximum allowed bit length is 32767 because 152 * the largest QR Code (version 40) has 31329 modules. 153 */ 154 struct qrcodegen_Segment { 155 // The mode indicator of this segment. 156 qrcodegen_Mode mode; 157 158 // The length of this segment's unencoded data. Measured in characters for 159 // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. 160 // Always zero or positive. Not the same as the data's bit length. 161 int numChars; 162 163 // The data bits of this segment, packed in bitwise big endian. 164 // Can be null if the bit length is zero. 165 uint8_t *data; 166 167 // The number of valid data bits used in the buffer. Requires 168 // 0 <= bitLength <= 32767, and bitLength <= (capacity of data array) * 8. 169 // The character count (numChars) must agree with the mode and the bit buffer length. 170 int bitLength; 171 }; 172 173 174 175 /*---- Macro constants and functions ----*/ 176 177 enum qrcodegen_VERSION_MIN = 1; // The minimum version number supported in the QR Code Model 2 standard 178 enum qrcodegen_VERSION_MAX = 40; // The maximum version number supported in the QR Code Model 2 standard 179 180 // Calculates the number of bytes needed to store any QR Code up to and including the given version number, 181 // as a compile-time constant. For example, 'uint8_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(25)];' 182 // can store any single QR Code from version 1 to 25 (inclusive). The result fits in an int (or int16). 183 // Requires qrcodegen_VERSION_MIN <= n <= qrcodegen_VERSION_MAX. 184 auto qrcodegen_BUFFER_LEN_FOR_VERSION(int n) { return ((((n) * 4 + 17) * ((n) * 4 + 17) + 7) / 8 + 1); } 185 186 // The worst-case number of bytes needed to store one QR Code, up to and including 187 // version 40. This value equals 3918, which is just under 4 kilobytes. 188 // Use this more convenient value to avoid calculating tighter memory bounds for buffers. 189 auto qrcodegen_BUFFER_LEN_MAX() { return qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX); } 190 191 192 193 /*---- Functions (high level) to generate QR Codes ----*/ 194 195 /* 196 * Encodes the given text string to a QR Code, returning true if encoding succeeded. 197 * If the data is too long to fit in any version in the given range 198 * at the given ECC level, then false is returned. 199 * - The input text must be encoded in UTF-8 and contain no NULs. 200 * - The variables ecl and mask must correspond to enum constant values. 201 * - Requires 1 <= minVersion <= maxVersion <= 40. 202 * - The arrays tempBuffer and qrcode must each have a length 203 * of at least qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion). 204 * - After the function returns, tempBuffer contains no useful data. 205 * - If successful, the resulting QR Code may use numeric, 206 * alphanumeric, or byte mode to encode the text. 207 * - In the most optimistic case, a QR Code at version 40 with low ECC 208 * can hold any UTF-8 string up to 2953 bytes, or any alphanumeric string 209 * up to 4296 characters, or any digit string up to 7089 characters. 210 * These numbers represent the hard upper limit of the QR Code standard. 211 * - Please consult the QR Code specification for information on 212 * data capacities per version, ECC level, and text encoding mode. 213 */ 214 bool qrcodegen_encodeText(const char *text, uint8_t* tempBuffer, uint8_t* qrcode, 215 qrcodegen_Ecc ecl, int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl); 216 217 218 /* 219 * Encodes the given binary data to a QR Code, returning true if encoding succeeded. 220 * If the data is too long to fit in any version in the given range 221 * at the given ECC level, then false is returned. 222 * - The input array range dataAndTemp[0 : dataLen] should normally be 223 * valid UTF-8 text, but is not required by the QR Code standard. 224 * - The variables ecl and mask must correspond to enum constant values. 225 * - Requires 1 <= minVersion <= maxVersion <= 40. 226 * - The arrays dataAndTemp and qrcode must each have a length 227 * of at least qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion). 228 * - After the function returns, the contents of dataAndTemp may have changed, 229 * and does not represent useful data anymore. 230 * - If successful, the resulting QR Code will use byte mode to encode the data. 231 * - In the most optimistic case, a QR Code at version 40 with low ECC can hold any byte 232 * sequence up to length 2953. This is the hard upper limit of the QR Code standard. 233 * - Please consult the QR Code specification for information on 234 * data capacities per version, ECC level, and text encoding mode. 235 */ 236 bool qrcodegen_encodeBinary(uint8_t* dataAndTemp, size_t dataLen, uint8_t* qrcode, 237 qrcodegen_Ecc ecl, int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl); 238 239 240 241 /*---- Functions to extract raw data from QR Codes ----*/ 242 243 244 /* 245 * QR Code generator library (C) 246 * 247 * Copyright (c) Project Nayuki. (MIT License) 248 * https://www.nayuki.io/page/qr-code-generator-library 249 * 250 * Permission is hereby granted, free of charge, to any person obtaining a copy of 251 * this software and associated documentation files (the "Software"), to deal in 252 * the Software without restriction, including without limitation the rights to 253 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 254 * the Software, and to permit persons to whom the Software is furnished to do so, 255 * subject to the following conditions: 256 * - The above copyright notice and this permission notice shall be included in 257 * all copies or substantial portions of the Software. 258 * - The Software is provided "as is", without warranty of any kind, express or 259 * implied, including but not limited to the warranties of merchantability, 260 * fitness for a particular purpose and noninfringement. In no event shall the 261 * authors or copyright holders be liable for any claim, damages or other 262 * liability, whether in an action of contract, tort or otherwise, arising from, 263 * out of or in connection with the Software or the use or other dealings in the 264 * Software. 265 */ 266 267 /*---- Forward declarations for private functions ----*/ 268 269 // Regarding all public and private functions defined in this source file: 270 // - They require all pointer/array arguments to be not null unless the array length is zero. 271 // - They only read input scalar/array arguments, write to output pointer/array 272 // arguments, and return scalar values; they are "pure" functions. 273 // - They don't read mutable global variables or write to any global variables. 274 // - They don't perform I/O, read the clock, print to console, etc. 275 // - They allocate a small and constant amount of stack memory. 276 // - They don't allocate or free any memory on the heap. 277 // - They don't recurse or mutually recurse. All the code 278 // could be inlined into the top-level public functions. 279 // - They run in at most quadratic time with respect to input arguments. 280 // Most functions run in linear time, and some in constant time. 281 // There are no unbounded loops or non-obvious termination conditions. 282 // - They are completely thread-safe if the caller does not give the 283 // same writable buffer to concurrent calls to these functions. 284 285 /*---- Private tables of constants ----*/ 286 287 // The set of all legal characters in alphanumeric mode, where each character 288 // value maps to the index in the string. For checking text and encoding segments. 289 static const char *ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; 290 291 // For generating error correction codes. 292 private const int8_t[41][4] ECC_CODEWORDS_PER_BLOCK = [ 293 // Version: (note that index 0 is for padding, and is set to an illegal value) 294 //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 295 [-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 296 [-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 297 [-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 298 [-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 299 ]; 300 301 enum qrcodegen_REED_SOLOMON_DEGREE_MAX = 30; // Based on the table above 302 303 // For generating error correction codes. 304 private const int8_t[41][4] NUM_ERROR_CORRECTION_BLOCKS = [ 305 // Version: (note that index 0 is for padding, and is set to an illegal value) 306 //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 307 [-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 308 [-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 309 [-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 310 [-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 311 ]; 312 313 // For automatic mask pattern selection. 314 static const int PENALTY_N1 = 3; 315 static const int PENALTY_N2 = 3; 316 static const int PENALTY_N3 = 40; 317 static const int PENALTY_N4 = 10; 318 319 320 321 /*---- High-level QR Code encoding functions ----*/ 322 323 // Public function - see documentation comment in header file. 324 bool qrcodegen_encodeText(const char *text, uint8_t* tempBuffer, uint8_t* qrcode, 325 qrcodegen_Ecc ecl, int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl) { 326 327 size_t textLen = strlen(text); 328 if (textLen == 0) 329 return qrcodegen_encodeSegmentsAdvanced(null, 0, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); 330 size_t bufLen = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion); 331 332 qrcodegen_Segment seg; 333 if (qrcodegen_isNumeric(text)) { 334 if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_NUMERIC, textLen) > bufLen) 335 goto fail; 336 seg = qrcodegen_makeNumeric(text, tempBuffer); 337 } else if (qrcodegen_isAlphanumeric(text)) { 338 if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_ALPHANUMERIC, textLen) > bufLen) 339 goto fail; 340 seg = qrcodegen_makeAlphanumeric(text, tempBuffer); 341 } else { 342 if (textLen > bufLen) 343 goto fail; 344 for (size_t i = 0; i < textLen; i++) 345 tempBuffer[i] = cast(uint8_t)text[i]; 346 seg.mode = qrcodegen_Mode_BYTE; 347 seg.bitLength = calcSegmentBitLength(seg.mode, textLen); 348 if (seg.bitLength == -1) 349 goto fail; 350 seg.numChars = cast(int)textLen; 351 seg.data = tempBuffer; 352 } 353 return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); 354 355 fail: 356 qrcode[0] = 0; // Set size to invalid value for safety 357 return false; 358 } 359 360 361 // Public function - see documentation comment in header file. 362 bool qrcodegen_encodeBinary(uint8_t* dataAndTemp, size_t dataLen, uint8_t* qrcode, 363 qrcodegen_Ecc ecl, int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl) { 364 365 qrcodegen_Segment seg; 366 seg.mode = qrcodegen_Mode_BYTE; 367 seg.bitLength = calcSegmentBitLength(seg.mode, dataLen); 368 if (seg.bitLength == -1) { 369 qrcode[0] = 0; // Set size to invalid value for safety 370 return false; 371 } 372 seg.numChars = cast(int)dataLen; 373 seg.data = dataAndTemp; 374 return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, dataAndTemp, qrcode); 375 } 376 377 378 // Appends the given number of low-order bits of the given value to the given byte-based 379 // bit buffer, increasing the bit length. Requires 0 <= numBits <= 16 and val < 2^numBits. 380 private void appendBitsToBuffer(uint val, int numBits, uint8_t* buffer, int *bitLen) { 381 assert(0 <= numBits && numBits <= 16 && cast(c_ulong)val >> numBits == 0); 382 for (int i = numBits - 1; i >= 0; i--, (*bitLen)++) 383 buffer[*bitLen >> 3] |= ((val >> i) & 1) << (7 - (*bitLen & 7)); 384 } 385 386 387 388 /*---- Low-level QR Code encoding functions ----*/ 389 390 // Public function - see documentation comment in header file. 391 392 /* 393 * Renders a QR Code representing the given segments at the given error correction level. 394 * The smallest possible QR Code version is automatically chosen for the output. Returns true if 395 * QR Code creation succeeded, or false if the data is too long to fit in any version. The ECC level 396 * of the result may be higher than the ecl argument if it can be done without increasing the version. 397 * This function allows the user to create a custom sequence of segments that switches 398 * between modes (such as alphanumeric and byte) to encode text in less space. 399 * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). 400 * To save memory, the segments' data buffers can alias/overlap tempBuffer, and will 401 * result in them being clobbered, but the QR Code output will still be correct. 402 * But the qrcode array must not overlap tempBuffer or any segment's data buffer. 403 */ 404 405 bool qrcodegen_encodeSegments(const qrcodegen_Segment* segs, size_t len, 406 qrcodegen_Ecc ecl, uint8_t* tempBuffer, uint8_t* qrcode) { 407 return qrcodegen_encodeSegmentsAdvanced(segs, len, ecl, 408 qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true, tempBuffer, qrcode); 409 } 410 411 412 // Public function - see documentation comment in header file. 413 414 415 /* 416 * Renders a QR Code representing the given segments with the given encoding parameters. 417 * Returns true if QR Code creation succeeded, or false if the data is too long to fit in the range of versions. 418 * The smallest possible QR Code version within the given range is automatically 419 * chosen for the output. Iff boostEcl is true, then the ECC level of the result 420 * may be higher than the ecl argument if it can be done without increasing the 421 * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or 422 * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). 423 * This function allows the user to create a custom sequence of segments that switches 424 * between modes (such as alphanumeric and byte) to encode text in less space. 425 * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). 426 * To save memory, the segments' data buffers can alias/overlap tempBuffer, and will 427 * result in them being clobbered, but the QR Code output will still be correct. 428 * But the qrcode array must not overlap tempBuffer or any segment's data buffer. 429 */ 430 431 bool qrcodegen_encodeSegmentsAdvanced(const qrcodegen_Segment* segs, size_t len, qrcodegen_Ecc ecl, 432 int minVersion, int maxVersion, qrcodegen_Mask mask, bool boostEcl, uint8_t* tempBuffer, uint8_t* qrcode) { 433 assert(segs != null || len == 0); 434 assert(qrcodegen_VERSION_MIN <= minVersion && minVersion <= maxVersion && maxVersion <= qrcodegen_VERSION_MAX); 435 assert(0 <= cast(int)ecl && cast(int)ecl <= 3 && -1 <= cast(int)mask && cast(int)mask <= 7); 436 437 // Find the minimal version_ number to use 438 int version_, dataUsedBits; 439 for (version_ = minVersion; ; version_++) { 440 int dataCapacityBits = getNumDataCodewords(version_, ecl) * 8; // Number of data bits available 441 dataUsedBits = getTotalBits(segs, len, version_); 442 if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) 443 break; // This version_ number is found to be suitable 444 if (version_ >= maxVersion) { // All version_s in the range could not fit the given data 445 qrcode[0] = 0; // Set size to invalid value for safety 446 return false; 447 } 448 } 449 assert(dataUsedBits != -1); 450 451 // Increase the error correction level while the data still fits in the current version_ number 452 for (int i = cast(int)qrcodegen_Ecc_MEDIUM; i <= cast(int)qrcodegen_Ecc_HIGH; i++) { // From low to high 453 if (boostEcl && dataUsedBits <= getNumDataCodewords(version_, cast(qrcodegen_Ecc)i) * 8) 454 ecl = cast(qrcodegen_Ecc)i; 455 } 456 457 // Concatenate all segments to create the data bit string 458 memset(qrcode, 0, cast(size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(version_) * (qrcode[0]).sizeof); 459 int bitLen = 0; 460 for (size_t i = 0; i < len; i++) { 461 const qrcodegen_Segment *seg = &segs[i]; 462 appendBitsToBuffer(cast(uint)seg.mode, 4, qrcode, &bitLen); 463 appendBitsToBuffer(cast(uint)seg.numChars, numCharCountBits(seg.mode, version_), qrcode, &bitLen); 464 for (int j = 0; j < seg.bitLength; j++) { 465 int bit = (seg.data[j >> 3] >> (7 - (j & 7))) & 1; 466 appendBitsToBuffer(cast(uint)bit, 1, qrcode, &bitLen); 467 } 468 } 469 assert(bitLen == dataUsedBits); 470 471 // Add terminator and pad up to a byte if applicable 472 int dataCapacityBits = getNumDataCodewords(version_, ecl) * 8; 473 assert(bitLen <= dataCapacityBits); 474 int terminatorBits = dataCapacityBits - bitLen; 475 if (terminatorBits > 4) 476 terminatorBits = 4; 477 appendBitsToBuffer(0, terminatorBits, qrcode, &bitLen); 478 appendBitsToBuffer(0, (8 - bitLen % 8) % 8, qrcode, &bitLen); 479 assert(bitLen % 8 == 0); 480 481 // Pad with alternating bytes until data capacity is reached 482 for (uint8_t padByte = 0xEC; bitLen < dataCapacityBits; padByte ^= 0xEC ^ 0x11) 483 appendBitsToBuffer(padByte, 8, qrcode, &bitLen); 484 485 // Draw function and data codeword modules 486 addEccAndInterleave(qrcode, version_, ecl, tempBuffer); 487 initializeFunctionModules(version_, qrcode); 488 drawCodewords(tempBuffer, getNumRawDataModules(version_) / 8, qrcode); 489 drawWhiteFunctionModules(qrcode, version_); 490 initializeFunctionModules(version_, tempBuffer); 491 492 // Handle masking 493 if (mask == qrcodegen_Mask_AUTO) { // Automatically choose best mask 494 long minPenalty = long.max; 495 for (int i = 0; i < 8; i++) { 496 qrcodegen_Mask msk = cast(qrcodegen_Mask)i; 497 applyMask(tempBuffer, qrcode, msk); 498 drawFormatBits(ecl, msk, qrcode); 499 long penalty = getPenaltyScore(qrcode); 500 if (penalty < minPenalty) { 501 mask = msk; 502 minPenalty = penalty; 503 } 504 applyMask(tempBuffer, qrcode, msk); // Undoes the mask due to XOR 505 } 506 } 507 assert(0 <= cast(int)mask && cast(int)mask <= 7); 508 applyMask(tempBuffer, qrcode, mask); 509 drawFormatBits(ecl, mask, qrcode); 510 return true; 511 } 512 513 514 515 /*---- Error correction code generation functions ----*/ 516 517 // Appends error correction bytes to each block of the given data array, then interleaves 518 // bytes from the blocks and stores them in the result array. data[0 : dataLen] contains 519 // the input data. data[dataLen : rawCodewords] is used as a temporary work area and will 520 // be clobbered by this function. The final answer is stored in result[0 : rawCodewords]. 521 private void addEccAndInterleave(uint8_t* data, int version_, qrcodegen_Ecc ecl, uint8_t* result) { 522 // Calculate parameter numbers 523 assert(0 <= cast(int)ecl && cast(int)ecl < 4 && qrcodegen_VERSION_MIN <= version_ && version_ <= qrcodegen_VERSION_MAX); 524 int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[cast(int)ecl][version_]; 525 int blockEccLen = ECC_CODEWORDS_PER_BLOCK [cast(int)ecl][version_]; 526 int rawCodewords = getNumRawDataModules(version_) / 8; 527 int dataLen = getNumDataCodewords(version_, ecl); 528 int numShortBlocks = numBlocks - rawCodewords % numBlocks; 529 int shortBlockDataLen = rawCodewords / numBlocks - blockEccLen; 530 531 // Split data into blocks, calculate ECC, and interleave 532 // (not concatenate) the bytes into a single sequence 533 uint8_t[qrcodegen_REED_SOLOMON_DEGREE_MAX] rsdiv; 534 reedSolomonComputeDivisor(blockEccLen, rsdiv.ptr); 535 const(uint8_t)* dat = data; 536 for (int i = 0; i < numBlocks; i++) { 537 int datLen = shortBlockDataLen + (i < numShortBlocks ? 0 : 1); 538 uint8_t *ecc = &data[dataLen]; // Temporary storage 539 reedSolomonComputeRemainder(dat, datLen, rsdiv.ptr, blockEccLen, ecc); 540 for (int j = 0, k = i; j < datLen; j++, k += numBlocks) { // Copy data 541 if (j == shortBlockDataLen) 542 k -= numShortBlocks; 543 result[k] = dat[j]; 544 } 545 for (int j = 0, k = dataLen + i; j < blockEccLen; j++, k += numBlocks) // Copy ECC 546 result[k] = ecc[j]; 547 dat += datLen; 548 } 549 } 550 551 552 // Returns the number of 8-bit codewords that can be used for storing data (not ECC), 553 // for the given version_ number and error correction level. The result is in the range [9, 2956]. 554 private int getNumDataCodewords(int version_, qrcodegen_Ecc ecl) { 555 int v = version_, e = cast(int)ecl; 556 assert(0 <= e && e < 4); 557 return getNumRawDataModules(v) / 8 558 - ECC_CODEWORDS_PER_BLOCK [e][v] 559 * NUM_ERROR_CORRECTION_BLOCKS[e][v]; 560 } 561 562 563 // Returns the number of data bits that can be stored in a QR Code of the given version_ number, after 564 // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. 565 // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. 566 private int getNumRawDataModules(int ver) { 567 assert(qrcodegen_VERSION_MIN <= ver && ver <= qrcodegen_VERSION_MAX); 568 int result = (16 * ver + 128) * ver + 64; 569 if (ver >= 2) { 570 int numAlign = ver / 7 + 2; 571 result -= (25 * numAlign - 10) * numAlign - 55; 572 if (ver >= 7) 573 result -= 36; 574 } 575 assert(208 <= result && result <= 29648); 576 return result; 577 } 578 579 580 581 /*---- Reed-Solomon ECC generator functions ----*/ 582 583 // Computes a Reed-Solomon ECC generator polynomial for the given degree, storing in result[0 : degree]. 584 // This could be implemented as a lookup table over all possible parameter values, instead of as an algorithm. 585 private void reedSolomonComputeDivisor(int degree, uint8_t* result) { 586 assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); 587 // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. 588 // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. 589 memset(result, 0, cast(size_t)degree * (result[0]).sizeof); 590 result[degree - 1] = 1; // Start off with the monomial x^0 591 592 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), 593 // drop the highest monomial term which is always 1x^degree. 594 // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). 595 uint8_t root = 1; 596 for (int i = 0; i < degree; i++) { 597 // Multiply the current product by (x - r^i) 598 for (int j = 0; j < degree; j++) { 599 result[j] = reedSolomonMultiply(result[j], root); 600 if (j + 1 < degree) 601 result[j] ^= result[j + 1]; 602 } 603 root = reedSolomonMultiply(root, 0x02); 604 } 605 } 606 607 608 // Computes the Reed-Solomon error correction codeword for the given data and divisor polynomials. 609 // The remainder when data[0 : dataLen] is divided by divisor[0 : degree] is stored in result[0 : degree]. 610 // All polynomials are in big endian, and the generator has an implicit leading 1 term. 611 private void reedSolomonComputeRemainder(const uint8_t* data, int dataLen, 612 const uint8_t* generator, int degree, uint8_t* result) { 613 assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); 614 memset(result, 0, cast(size_t)degree * (result[0]).sizeof); 615 for (int i = 0; i < dataLen; i++) { // Polynomial division 616 uint8_t factor = data[i] ^ result[0]; 617 memmove(&result[0], &result[1], cast(size_t)(degree - 1) * (result[0]).sizeof); 618 result[degree - 1] = 0; 619 for (int j = 0; j < degree; j++) 620 result[j] ^= reedSolomonMultiply(generator[j], factor); 621 } 622 } 623 624 // Returns the product of the two given field elements modulo GF(2^8/0x11D). 625 // All inputs are valid. This could be implemented as a 256*256 lookup table. 626 private uint8_t reedSolomonMultiply(uint8_t x, uint8_t y) { 627 // Russian peasant multiplication 628 uint8_t z = 0; 629 for (int i = 7; i >= 0; i--) { 630 z = cast(uint8_t)((z << 1) ^ ((z >> 7) * 0x11D)); 631 z ^= ((y >> i) & 1) * x; 632 } 633 return z; 634 } 635 636 637 638 /*---- Drawing function modules ----*/ 639 640 // Clears the given QR Code grid with white modules for the given 641 // version_'s size, then marks every function module as black. 642 private void initializeFunctionModules(int version_, uint8_t* qrcode) { 643 // Initialize QR Code 644 int qrsize = version_ * 4 + 17; 645 memset(qrcode, 0, cast(size_t)((qrsize * qrsize + 7) / 8 + 1) * (qrcode[0]).sizeof); 646 qrcode[0] = cast(uint8_t)qrsize; 647 648 // Fill horizontal and vertical timing patterns 649 fillRectangle(6, 0, 1, qrsize, qrcode); 650 fillRectangle(0, 6, qrsize, 1, qrcode); 651 652 // Fill 3 finder patterns (all corners except bottom right) and format bits 653 fillRectangle(0, 0, 9, 9, qrcode); 654 fillRectangle(qrsize - 8, 0, 8, 9, qrcode); 655 fillRectangle(0, qrsize - 8, 9, 8, qrcode); 656 657 // Fill numerous alignment patterns 658 uint8_t[7] alignPatPos; 659 int numAlign = getAlignmentPatternPositions(version_, alignPatPos); 660 for (int i = 0; i < numAlign; i++) { 661 for (int j = 0; j < numAlign; j++) { 662 // Don't draw on the three finder corners 663 if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) 664 fillRectangle(alignPatPos[i] - 2, alignPatPos[j] - 2, 5, 5, qrcode); 665 } 666 } 667 668 // Fill version_ blocks 669 if (version_ >= 7) { 670 fillRectangle(qrsize - 11, 0, 3, 6, qrcode); 671 fillRectangle(0, qrsize - 11, 6, 3, qrcode); 672 } 673 } 674 675 676 // Draws white function modules and possibly some black modules onto the given QR Code, without changing 677 // non-function modules. This does not draw the format bits. This requires all function modules to be previously 678 // marked black (namely by initializeFunctionModules()), because this may skip redrawing black function modules. 679 static void drawWhiteFunctionModules(uint8_t* qrcode, int version_) { 680 // Draw horizontal and vertical timing patterns 681 int qrsize = qrcodegen_getSize(qrcode); 682 for (int i = 7; i < qrsize - 7; i += 2) { 683 setModule(qrcode, 6, i, false); 684 setModule(qrcode, i, 6, false); 685 } 686 687 // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) 688 for (int dy = -4; dy <= 4; dy++) { 689 for (int dx = -4; dx <= 4; dx++) { 690 int dist = abs(dx); 691 if (abs(dy) > dist) 692 dist = abs(dy); 693 if (dist == 2 || dist == 4) { 694 setModuleBounded(qrcode, 3 + dx, 3 + dy, false); 695 setModuleBounded(qrcode, qrsize - 4 + dx, 3 + dy, false); 696 setModuleBounded(qrcode, 3 + dx, qrsize - 4 + dy, false); 697 } 698 } 699 } 700 701 // Draw numerous alignment patterns 702 uint8_t[7] alignPatPos; 703 int numAlign = getAlignmentPatternPositions(version_, alignPatPos); 704 for (int i = 0; i < numAlign; i++) { 705 for (int j = 0; j < numAlign; j++) { 706 if ((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)) 707 continue; // Don't draw on the three finder corners 708 for (int dy = -1; dy <= 1; dy++) { 709 for (int dx = -1; dx <= 1; dx++) 710 setModule(qrcode, alignPatPos[i] + dx, alignPatPos[j] + dy, dx == 0 && dy == 0); 711 } 712 } 713 } 714 715 // Draw version_ blocks 716 if (version_ >= 7) { 717 // Calculate error correction code and pack bits 718 int rem = version_; // version_ is uint6, in the range [7, 40] 719 for (int i = 0; i < 12; i++) 720 rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); 721 c_long bits = cast(c_long)version_ << 12 | rem; // uint18 722 assert(bits >> 18 == 0); 723 724 // Draw two copies 725 for (int i = 0; i < 6; i++) { 726 for (int j = 0; j < 3; j++) { 727 int k = qrsize - 11 + j; 728 setModule(qrcode, k, i, (bits & 1) != 0); 729 setModule(qrcode, i, k, (bits & 1) != 0); 730 bits >>= 1; 731 } 732 } 733 } 734 } 735 736 737 // Draws two copies of the format bits (with its own error correction code) based 738 // on the given mask and error correction level. This always draws all modules of 739 // the format bits, unlike drawWhiteFunctionModules() which might skip black modules. 740 static void drawFormatBits(qrcodegen_Ecc ecl, qrcodegen_Mask mask, uint8_t* qrcode) { 741 // Calculate error correction code and pack bits 742 assert(0 <= cast(int)mask && cast(int)mask <= 7); 743 static const int[] table = [1, 0, 3, 2]; 744 int data = table[cast(int)ecl] << 3 | cast(int)mask; // errCorrLvl is uint2, mask is uint3 745 int rem = data; 746 for (int i = 0; i < 10; i++) 747 rem = (rem << 1) ^ ((rem >> 9) * 0x537); 748 int bits = (data << 10 | rem) ^ 0x5412; // uint15 749 assert(bits >> 15 == 0); 750 751 // Draw first copy 752 for (int i = 0; i <= 5; i++) 753 setModule(qrcode, 8, i, getBit(bits, i)); 754 setModule(qrcode, 8, 7, getBit(bits, 6)); 755 setModule(qrcode, 8, 8, getBit(bits, 7)); 756 setModule(qrcode, 7, 8, getBit(bits, 8)); 757 for (int i = 9; i < 15; i++) 758 setModule(qrcode, 14 - i, 8, getBit(bits, i)); 759 760 // Draw second copy 761 int qrsize = qrcodegen_getSize(qrcode); 762 for (int i = 0; i < 8; i++) 763 setModule(qrcode, qrsize - 1 - i, 8, getBit(bits, i)); 764 for (int i = 8; i < 15; i++) 765 setModule(qrcode, 8, qrsize - 15 + i, getBit(bits, i)); 766 setModule(qrcode, 8, qrsize - 8, true); // Always black 767 } 768 769 770 // Calculates and stores an ascending list of positions of alignment patterns 771 // for this version_ number, returning the length of the list (in the range [0,7]). 772 // Each position is in the range [0,177), and are used on both the x and y axes. 773 // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. 774 private int getAlignmentPatternPositions(int version_, ref uint8_t[7] result) { 775 if (version_ == 1) 776 return 0; 777 int numAlign = version_ / 7 + 2; 778 int step = (version_ == 32) ? 26 : 779 (version_*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2; 780 for (int i = numAlign - 1, pos = version_ * 4 + 10; i >= 1; i--, pos -= step) 781 result[i] = cast(uint8_t)pos; 782 result[0] = 6; 783 return numAlign; 784 } 785 786 787 // Sets every pixel in the range [left : left + width] * [top : top + height] to black. 788 static void fillRectangle(int left, int top, int width, int height, uint8_t* qrcode) { 789 for (int dy = 0; dy < height; dy++) { 790 for (int dx = 0; dx < width; dx++) 791 setModule(qrcode, left + dx, top + dy, true); 792 } 793 } 794 795 796 797 /*---- Drawing data modules and masking ----*/ 798 799 // Draws the raw codewords (including data and ECC) onto the given QR Code. This requires the initial state of 800 // the QR Code to be black at function modules and white at codeword modules (including unused remainder bits). 801 static void drawCodewords(const uint8_t* data, int dataLen, uint8_t* qrcode) { 802 int qrsize = qrcodegen_getSize(qrcode); 803 int i = 0; // Bit index into the data 804 // Do the funny zigzag scan 805 for (int right = qrsize - 1; right >= 1; right -= 2) { // Index of right column in each column pair 806 if (right == 6) 807 right = 5; 808 for (int vert = 0; vert < qrsize; vert++) { // Vertical counter 809 for (int j = 0; j < 2; j++) { 810 int x = right - j; // Actual x coordinate 811 bool upward = ((right + 1) & 2) == 0; 812 int y = upward ? qrsize - 1 - vert : vert; // Actual y coordinate 813 if (!getModule(qrcode, x, y) && i < dataLen * 8) { 814 bool black = getBit(data[i >> 3], 7 - (i & 7)); 815 setModule(qrcode, x, y, black); 816 i++; 817 } 818 // If this QR Code has any remainder bits (0 to 7), they were assigned as 819 // 0/false/white by the constructor and are left unchanged by this method 820 } 821 } 822 } 823 assert(i == dataLen * 8); 824 } 825 826 827 // XORs the codeword modules in this QR Code with the given mask pattern. 828 // The function modules must be marked and the codeword bits must be drawn 829 // before masking. Due to the arithmetic of XOR, calling applyMask() with 830 // the same mask value a second time will undo the mask. A final well-formed 831 // QR Code needs exactly one (not zero, two, etc.) mask applied. 832 static void applyMask(const uint8_t* functionModules, uint8_t* qrcode, qrcodegen_Mask mask) { 833 assert(0 <= cast(int)mask && cast(int)mask <= 7); // Disallows qrcodegen_Mask_AUTO 834 int qrsize = qrcodegen_getSize(qrcode); 835 for (int y = 0; y < qrsize; y++) { 836 for (int x = 0; x < qrsize; x++) { 837 if (getModule(functionModules, x, y)) 838 continue; 839 bool invert; 840 switch (cast(int)mask) { 841 case 0: invert = (x + y) % 2 == 0; break; 842 case 1: invert = y % 2 == 0; break; 843 case 2: invert = x % 3 == 0; break; 844 case 3: invert = (x + y) % 3 == 0; break; 845 case 4: invert = (x / 3 + y / 2) % 2 == 0; break; 846 case 5: invert = x * y % 2 + x * y % 3 == 0; break; 847 case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; 848 case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; 849 default: assert(false); 850 } 851 bool val = getModule(qrcode, x, y); 852 setModule(qrcode, x, y, val ^ invert); 853 } 854 } 855 } 856 857 858 // Calculates and returns the penalty score based on state of the given QR Code's current modules. 859 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. 860 static long getPenaltyScore(const uint8_t* qrcode) { 861 int qrsize = qrcodegen_getSize(qrcode); 862 long result = 0; 863 864 // Adjacent modules in row having same color, and finder-like patterns 865 for (int y = 0; y < qrsize; y++) { 866 bool runColor = false; 867 int runX = 0; 868 int[7] runHistory = 0; 869 for (int x = 0; x < qrsize; x++) { 870 if (getModule(qrcode, x, y) == runColor) { 871 runX++; 872 if (runX == 5) 873 result += PENALTY_N1; 874 else if (runX > 5) 875 result++; 876 } else { 877 finderPenaltyAddHistory(runX, runHistory, qrsize); 878 if (!runColor) 879 result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; 880 runColor = getModule(qrcode, x, y); 881 runX = 1; 882 } 883 } 884 result += finderPenaltyTerminateAndCount(runColor, runX, runHistory, qrsize) * PENALTY_N3; 885 } 886 // Adjacent modules in column having same color, and finder-like patterns 887 for (int x = 0; x < qrsize; x++) { 888 bool runColor = false; 889 int runY = 0; 890 int[7] runHistory = 0; 891 for (int y = 0; y < qrsize; y++) { 892 if (getModule(qrcode, x, y) == runColor) { 893 runY++; 894 if (runY == 5) 895 result += PENALTY_N1; 896 else if (runY > 5) 897 result++; 898 } else { 899 finderPenaltyAddHistory(runY, runHistory, qrsize); 900 if (!runColor) 901 result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; 902 runColor = getModule(qrcode, x, y); 903 runY = 1; 904 } 905 } 906 result += finderPenaltyTerminateAndCount(runColor, runY, runHistory, qrsize) * PENALTY_N3; 907 } 908 909 // 2*2 blocks of modules having same color 910 for (int y = 0; y < qrsize - 1; y++) { 911 for (int x = 0; x < qrsize - 1; x++) { 912 bool color = getModule(qrcode, x, y); 913 if ( color == getModule(qrcode, x + 1, y) && 914 color == getModule(qrcode, x, y + 1) && 915 color == getModule(qrcode, x + 1, y + 1)) 916 result += PENALTY_N2; 917 } 918 } 919 920 // Balance of black and white modules 921 int black = 0; 922 for (int y = 0; y < qrsize; y++) { 923 for (int x = 0; x < qrsize; x++) { 924 if (getModule(qrcode, x, y)) 925 black++; 926 } 927 } 928 int total = qrsize * qrsize; // Note that size is odd, so black/total != 1/2 929 // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)% 930 int k = cast(int)((labs(black * 20 - total * 10) + total - 1) / total) - 1; 931 result += k * PENALTY_N4; 932 return result; 933 } 934 935 936 // Can only be called immediately after a white run is added, and 937 // returns either 0, 1, or 2. A helper function for getPenaltyScore(). 938 static int finderPenaltyCountPatterns(const int[7] runHistory, int qrsize) { 939 int n = runHistory[1]; 940 assert(n <= qrsize * 3); 941 bool core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; 942 // The maximum QR Code size is 177, hence the black run length n <= 177. 943 // Arithmetic is promoted to int, so n*4 will not overflow. 944 return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) 945 + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); 946 } 947 948 949 // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). 950 static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, ref int[7] runHistory, int qrsize) { 951 if (currentRunColor) { // Terminate black run 952 finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); 953 currentRunLength = 0; 954 } 955 currentRunLength += qrsize; // Add white border to final run 956 finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); 957 return finderPenaltyCountPatterns(runHistory, qrsize); 958 } 959 960 961 // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). 962 static void finderPenaltyAddHistory(int currentRunLength, ref int[7] runHistory, int qrsize) { 963 if (runHistory[0] == 0) 964 currentRunLength += qrsize; // Add white border to initial run 965 memmove(&runHistory[1], &runHistory[0], 6 * (runHistory[0]).sizeof); 966 runHistory[0] = currentRunLength; 967 } 968 969 970 971 /*---- Basic QR Code information ----*/ 972 973 // Public function - see documentation comment in header file. 974 975 /* 976 * Returns the side length of the given QR Code, assuming that encoding succeeded. 977 * The result is in the range [21, 177]. Note that the length of the array buffer 978 * is related to the side length - every 'uint8_t qrcode[]' must have length at least 979 * qrcodegen_BUFFER_LEN_FOR_VERSION(version), which equals ceil(size^2 / 8 + 1). 980 */ 981 982 int qrcodegen_getSize(const uint8_t* qrcode) { 983 assert(qrcode != null); 984 int result = qrcode[0]; 985 assert((qrcodegen_VERSION_MIN * 4 + 17) <= result 986 && result <= (qrcodegen_VERSION_MAX * 4 + 17)); 987 return result; 988 } 989 990 991 // Public function - see documentation comment in header file. 992 993 /* 994 * Returns the color of the module (pixel) at the given coordinates, which is false 995 * for white or true for black. The top left corner has the coordinates (x=0, y=0). 996 * If the given coordinates are out of bounds, then false (white) is returned. 997 */ 998 999 bool qrcodegen_getModule(const uint8_t* qrcode, int x, int y) { 1000 assert(qrcode != null); 1001 int qrsize = qrcode[0]; 1002 return (0 <= x && x < qrsize && 0 <= y && y < qrsize) && getModule(qrcode, x, y); 1003 } 1004 1005 1006 // Gets the module at the given coordinates, which must be in bounds. 1007 private bool getModule(const uint8_t* qrcode, int x, int y) { 1008 int qrsize = qrcode[0]; 1009 assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); 1010 int index = y * qrsize + x; 1011 return getBit(qrcode[(index >> 3) + 1], index & 7); 1012 } 1013 1014 1015 // Sets the module at the given coordinates, which must be in bounds. 1016 private void setModule(uint8_t* qrcode, int x, int y, bool isBlack) { 1017 int qrsize = qrcode[0]; 1018 assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); 1019 int index = y * qrsize + x; 1020 int bitIndex = index & 7; 1021 int byteIndex = (index >> 3) + 1; 1022 if (isBlack) 1023 qrcode[byteIndex] |= 1 << bitIndex; 1024 else 1025 qrcode[byteIndex] &= (1 << bitIndex) ^ 0xFF; 1026 } 1027 1028 1029 // Sets the module at the given coordinates, doing nothing if out of bounds. 1030 private void setModuleBounded(uint8_t* qrcode, int x, int y, bool isBlack) { 1031 int qrsize = qrcode[0]; 1032 if (0 <= x && x < qrsize && 0 <= y && y < qrsize) 1033 setModule(qrcode, x, y, isBlack); 1034 } 1035 1036 1037 // Returns true iff the i'th bit of x is set to 1. Requires x >= 0 and 0 <= i <= 14. 1038 static bool getBit(int x, int i) { 1039 return ((x >> i) & 1) != 0; 1040 } 1041 1042 1043 1044 /*---- Segment handling ----*/ 1045 1046 // Public function - see documentation comment in header file. 1047 1048 /* 1049 * Tests whether the given string can be encoded as a segment in alphanumeric mode. 1050 * A string is encodable iff each character is in the following set: 0 to 9, A to Z 1051 * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. 1052 */ 1053 bool qrcodegen_isAlphanumeric(const(char)* text) { 1054 assert(text != null); 1055 for (; *text != '\0'; text++) { 1056 if (strchr(ALPHANUMERIC_CHARSET, *text) == null) 1057 return false; 1058 } 1059 return true; 1060 } 1061 1062 1063 // Public function - see documentation comment in header file. 1064 1065 /* 1066 * Tests whether the given string can be encoded as a segment in numeric mode. 1067 * A string is encodable iff each character is in the range 0 to 9. 1068 */ 1069 bool qrcodegen_isNumeric(const(char)* text) { 1070 assert(text != null); 1071 for (; *text != '\0'; text++) { 1072 if (*text < '0' || *text > '9') 1073 return false; 1074 } 1075 return true; 1076 } 1077 1078 1079 // Public function - see documentation comment in header file. 1080 1081 /* 1082 * Returns the number of bytes (uint8_t) needed for the data buffer of a segment 1083 * containing the given number of characters using the given mode. Notes: 1084 * - Returns SIZE_MAX on failure, i.e. numChars > INT16_MAX or 1085 * the number of needed bits exceeds INT16_MAX (i.e. 32767). 1086 * - Otherwise, all valid results are in the range [0, ceil(INT16_MAX / 8)], i.e. at most 4096. 1087 * - It is okay for the user to allocate more bytes for the buffer than needed. 1088 * - For byte mode, numChars measures the number of bytes, not Unicode code points. 1089 * - For ECI mode, numChars must be 0, and the worst-case number of bytes is returned. 1090 * An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. 1091 */ 1092 1093 size_t qrcodegen_calcSegmentBufferSize(qrcodegen_Mode mode, size_t numChars) { 1094 int temp = calcSegmentBitLength(mode, numChars); 1095 if (temp == -1) 1096 return SIZE_MAX; 1097 assert(0 <= temp && temp <= INT16_MAX); 1098 return (cast(size_t)temp + 7) / 8; 1099 } 1100 1101 1102 // Returns the number of data bits needed to represent a segment 1103 // containing the given number of characters using the given mode. Notes: 1104 // - Returns -1 on failure, i.e. numChars > INT16_MAX or 1105 // the number of needed bits exceeds INT16_MAX (i.e. 32767). 1106 // - Otherwise, all valid results are in the range [0, INT16_MAX]. 1107 // - For byte mode, numChars measures the number of bytes, not Unicode code points. 1108 // - For ECI mode, numChars must be 0, and the worst-case number of bits is returned. 1109 // An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. 1110 private int calcSegmentBitLength(qrcodegen_Mode mode, size_t numChars) { 1111 // All calculations are designed to avoid overflow on all platforms 1112 if (numChars > cast(uint)INT16_MAX) 1113 return -1; 1114 c_long result = cast(c_long)numChars; 1115 if (mode == qrcodegen_Mode_NUMERIC) 1116 result = (result * 10 + 2) / 3; // ceil(10/3 * n) 1117 else if (mode == qrcodegen_Mode_ALPHANUMERIC) 1118 result = (result * 11 + 1) / 2; // ceil(11/2 * n) 1119 else if (mode == qrcodegen_Mode_BYTE) 1120 result *= 8; 1121 else if (mode == qrcodegen_Mode_KANJI) 1122 result *= 13; 1123 else if (mode == qrcodegen_Mode_ECI && numChars == 0) 1124 result = 3 * 8; 1125 else { // Invalid argument 1126 assert(false); 1127 } 1128 assert(result >= 0); 1129 if (result > INT16_MAX) 1130 return -1; 1131 return cast(int)result; 1132 } 1133 1134 1135 // Public function - see documentation comment in header file. 1136 1137 /* 1138 * Returns a segment representing the given binary data encoded in 1139 * byte mode. All input byte arrays are acceptable. Any text string 1140 * can be converted to UTF-8 bytes and encoded as a byte mode segment. 1141 */ 1142 1143 qrcodegen_Segment qrcodegen_makeBytes(const uint8_t* data, size_t len, uint8_t* buf) { 1144 assert(data != null || len == 0); 1145 qrcodegen_Segment result; 1146 result.mode = qrcodegen_Mode_BYTE; 1147 result.bitLength = calcSegmentBitLength(result.mode, len); 1148 assert(result.bitLength != -1); 1149 result.numChars = cast(int)len; 1150 if (len > 0) 1151 memcpy(buf, data, len * (buf[0]).sizeof); 1152 result.data = buf; 1153 return result; 1154 } 1155 1156 1157 // Public function - see documentation comment in header file. 1158 1159 /* 1160 * Returns a segment representing the given string of decimal digits encoded in numeric mode. 1161 */ 1162 1163 qrcodegen_Segment qrcodegen_makeNumeric(const(char)* digits, uint8_t* buf) { 1164 assert(digits != null); 1165 qrcodegen_Segment result; 1166 size_t len = strlen(digits); 1167 result.mode = qrcodegen_Mode_NUMERIC; 1168 int bitLen = calcSegmentBitLength(result.mode, len); 1169 assert(bitLen != -1); 1170 result.numChars = cast(int)len; 1171 if (bitLen > 0) 1172 memset(buf, 0, (cast(size_t)bitLen + 7) / 8 * (buf[0]).sizeof); 1173 result.bitLength = 0; 1174 1175 uint accumData = 0; 1176 int accumCount = 0; 1177 for (; *digits != '\0'; digits++) { 1178 char c = *digits; 1179 assert('0' <= c && c <= '9'); 1180 accumData = accumData * 10 + cast(uint)(c - '0'); 1181 accumCount++; 1182 if (accumCount == 3) { 1183 appendBitsToBuffer(accumData, 10, buf, &result.bitLength); 1184 accumData = 0; 1185 accumCount = 0; 1186 } 1187 } 1188 if (accumCount > 0) // 1 or 2 digits remaining 1189 appendBitsToBuffer(accumData, accumCount * 3 + 1, buf, &result.bitLength); 1190 assert(result.bitLength == bitLen); 1191 result.data = buf; 1192 return result; 1193 } 1194 1195 1196 // Public function - see documentation comment in header file. 1197 1198 /* 1199 * Returns a segment representing the given text string encoded in alphanumeric mode. 1200 * The characters allowed are: 0 to 9, A to Z (uppercase only), space, 1201 * dollar, percent, asterisk, plus, hyphen, period, slash, colon. 1202 */ 1203 1204 qrcodegen_Segment qrcodegen_makeAlphanumeric(const(char)* text, uint8_t* buf) { 1205 assert(text != null); 1206 qrcodegen_Segment result; 1207 size_t len = strlen(text); 1208 result.mode = qrcodegen_Mode_ALPHANUMERIC; 1209 int bitLen = calcSegmentBitLength(result.mode, len); 1210 assert(bitLen != -1); 1211 result.numChars = cast(int)len; 1212 if (bitLen > 0) 1213 memset(buf, 0, (cast(size_t)bitLen + 7) / 8 * (buf[0]).sizeof); 1214 result.bitLength = 0; 1215 1216 uint accumData = 0; 1217 int accumCount = 0; 1218 for (; *text != '\0'; text++) { 1219 const char *temp = strchr(ALPHANUMERIC_CHARSET, *text); 1220 assert(temp != null); 1221 accumData = accumData * 45 + cast(uint)(temp - ALPHANUMERIC_CHARSET); 1222 accumCount++; 1223 if (accumCount == 2) { 1224 appendBitsToBuffer(accumData, 11, buf, &result.bitLength); 1225 accumData = 0; 1226 accumCount = 0; 1227 } 1228 } 1229 if (accumCount > 0) // 1 character remaining 1230 appendBitsToBuffer(accumData, 6, buf, &result.bitLength); 1231 assert(result.bitLength == bitLen); 1232 result.data = buf; 1233 return result; 1234 } 1235 1236 1237 // Public function - see documentation comment in header file. 1238 1239 /* 1240 * Returns a segment representing an Extended Channel Interpretation 1241 * (ECI) designator with the given assignment value. 1242 */ 1243 1244 qrcodegen_Segment qrcodegen_makeEci(c_long assignVal, uint8_t* buf) { 1245 qrcodegen_Segment result; 1246 result.mode = qrcodegen_Mode_ECI; 1247 result.numChars = 0; 1248 result.bitLength = 0; 1249 if (assignVal < 0) 1250 assert(false); 1251 else if (assignVal < (1 << 7)) { 1252 memset(buf, 0, 1 * (buf[0]).sizeof); 1253 appendBitsToBuffer(cast(uint)assignVal, 8, buf, &result.bitLength); 1254 } else if (assignVal < (1 << 14)) { 1255 memset(buf, 0, 2 * (buf[0]).sizeof); 1256 appendBitsToBuffer(2, 2, buf, &result.bitLength); 1257 appendBitsToBuffer(cast(uint)assignVal, 14, buf, &result.bitLength); 1258 } else if (assignVal < 1000000L) { 1259 memset(buf, 0, 3 * (buf[0]).sizeof); 1260 appendBitsToBuffer(6, 3, buf, &result.bitLength); 1261 appendBitsToBuffer(cast(uint)(assignVal >> 10), 11, buf, &result.bitLength); 1262 appendBitsToBuffer(cast(uint)(assignVal & 0x3FF), 10, buf, &result.bitLength); 1263 } else 1264 assert(false); 1265 result.data = buf; 1266 return result; 1267 } 1268 1269 1270 // Calculates the number of bits needed to encode the given segments at the given version_. 1271 // Returns a non-negative number if successful. Otherwise returns -1 if a segment has too 1272 // many characters to fit its length field, or the total bits exceeds INT16_MAX. 1273 private int getTotalBits(const qrcodegen_Segment* segs, size_t len, int version_) { 1274 assert(segs != null || len == 0); 1275 long result = 0; 1276 for (size_t i = 0; i < len; i++) { 1277 int numChars = segs[i].numChars; 1278 int bitLength = segs[i].bitLength; 1279 assert(0 <= numChars && numChars <= INT16_MAX); 1280 assert(0 <= bitLength && bitLength <= INT16_MAX); 1281 int ccbits = numCharCountBits(segs[i].mode, version_); 1282 assert(0 <= ccbits && ccbits <= 16); 1283 if (numChars >= (1L << ccbits)) 1284 return -1; // The segment's length doesn't fit the field's bit width 1285 result += 4L + ccbits + bitLength; 1286 if (result > INT16_MAX) 1287 return -1; // The sum might overflow an int type 1288 } 1289 assert(0 <= result && result <= INT16_MAX); 1290 return cast(int)result; 1291 } 1292 1293 1294 // Returns the bit width of the character count field for a segment in the given mode 1295 // in a QR Code at the given version_ number. The result is in the range [0, 16]. 1296 static int numCharCountBits(qrcodegen_Mode mode, int version_) { 1297 assert(qrcodegen_VERSION_MIN <= version_ && version_ <= qrcodegen_VERSION_MAX); 1298 int i = (version_ + 7) / 17; 1299 switch (mode) { 1300 case qrcodegen_Mode_NUMERIC : { static immutable int[] temp1 = [10, 12, 14]; return temp1[i]; } 1301 case qrcodegen_Mode_ALPHANUMERIC: { static immutable int[] temp2 = [ 9, 11, 13]; return temp2[i]; } 1302 case qrcodegen_Mode_BYTE : { static immutable int[] temp3 = [ 8, 16, 16]; return temp3[i]; } 1303 case qrcodegen_Mode_KANJI : { static immutable int[] temp4 = [ 8, 10, 12]; return temp4[i]; } 1304 case qrcodegen_Mode_ECI : return 0; 1305 default: assert(false); // Dummy value 1306 } 1307 } 1308 1309 /++ 1310 1311 +/ 1312 struct QrCode { 1313 ubyte[qrcodegen_BUFFER_LEN_MAX] qrcode; 1314 1315 this(string text) { 1316 ubyte[qrcodegen_BUFFER_LEN_MAX] tempBuffer; 1317 bool ok = qrcodegen_encodeText((text ~ "\0").ptr, tempBuffer.ptr, qrcode.ptr, 1318 qrcodegen_Ecc_MEDIUM, qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true); 1319 if(!ok) 1320 throw new Exception("qr code generation failed"); 1321 } 1322 1323 /++ 1324 The size of the square of the code. It is size x size. 1325 +/ 1326 int size() { 1327 return qrcodegen_getSize(qrcode.ptr); 1328 } 1329 1330 /++ 1331 Returns true if it is a dark square, false if it is a light one. 1332 +/ 1333 bool opIndex(int x, int y) { 1334 return qrcodegen_getModule(qrcode.ptr, x, y); 1335 } 1336 } 1337