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