Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / examples / common / QRCode / repo / java / src / main / java / io / nayuki / qrcodegen / QrCode.java
1 /* 
2  * QR Code generator library (Java)
3  * 
4  * Copyright (c) Project Nayuki. (MIT License)
5  * https://www.nayuki.io/page/qr-code-generator-library
6  * 
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  * - The above copyright notice and this permission notice shall be included in
14  *   all copies or substantial portions of the Software.
15  * - The Software is provided "as is", without warranty of any kind, express or
16  *   implied, including but not limited to the warranties of merchantability,
17  *   fitness for a particular purpose and noninfringement. In no event shall the
18  *   authors or copyright holders be liable for any claim, damages or other
19  *   liability, whether in an action of contract, tort or otherwise, arising from,
20  *   out of or in connection with the Software or the use or other dealings in the
21  *   Software.
22  */
23
24 package io.nayuki.qrcodegen;
25
26 import java.awt.image.BufferedImage;
27 import java.util.Arrays;
28 import java.util.List;
29 import java.util.Objects;
30
31
32 /**
33  * A QR Code symbol, which is a type of two-dimension barcode.
34  * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
35  * <p>Instances of this class represent an immutable square grid of black and white cells.
36  * The class provides static factory functions to create a QR Code from text or binary data.
37  * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
38  * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.</p>
39  * <p>Ways to create a QR Code object:</p>
40  * <ul>
41  *   <li><p>High level: Take the payload data and call {@link QrCode#encodeText(String,Ecc)}
42  *     or {@link QrCode#encodeBinary(byte[],Ecc)}.</p></li>
43  *   <li><p>Mid level: Custom-make the list of {@link QrSegment segments}
44  *     and call {@link QrCode#encodeSegments(List,Ecc)} or
45  *     {@link QrCode#encodeSegments(List,Ecc,int,int,int,boolean)}</p></li>
46  *   <li><p>Low level: Custom-make the array of data codeword bytes (including segment headers and
47  *     final padding, excluding error correction codewords), supply the appropriate version number,
48  *     and call the {@link QrCode#QrCode(int,Ecc,byte[],int) constructor}.</p></li>
49  * </ul>
50  * <p>(Note that all ways require supplying the desired error correction level.)</p>
51  * @see QrSegment
52  */
53 public final class QrCode {
54         
55         /*---- Static factory functions (high level) ----*/
56         
57         /**
58          * Returns a QR Code representing the specified Unicode text string at the specified error correction level.
59          * As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
60          * Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
61          * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
62          * ecl argument if it can be done without increasing the version.
63          * @param text the text to be encoded (not {@code null}), which can be any Unicode string
64          * @param ecl the error correction level to use (not {@code null}) (boostable)
65          * @return a QR Code (not {@code null}) representing the text
66          * @throws NullPointerException if the text or error correction level is {@code null}
67          * @throws DataTooLongException if the text fails to fit in the
68          * largest version QR Code at the ECL, which means it is too long
69          */
70         public static QrCode encodeText(String text, Ecc ecl) {
71                 Objects.requireNonNull(text);
72                 Objects.requireNonNull(ecl);
73                 List<QrSegment> segs = QrSegment.makeSegments(text);
74                 return encodeSegments(segs, ecl);
75         }
76         
77         
78         /**
79          * Returns a QR Code representing the specified binary data at the specified error correction level.
80          * This function always encodes using the binary segment mode, not any text mode. The maximum number of
81          * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
82          * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
83          * @param data the binary data to encode (not {@code null})
84          * @param ecl the error correction level to use (not {@code null}) (boostable)
85          * @return a QR Code (not {@code null}) representing the data
86          * @throws NullPointerException if the data or error correction level is {@code null}
87          * @throws DataTooLongException if the data fails to fit in the
88          * largest version QR Code at the ECL, which means it is too long
89          */
90         public static QrCode encodeBinary(byte[] data, Ecc ecl) {
91                 Objects.requireNonNull(data);
92                 Objects.requireNonNull(ecl);
93                 QrSegment seg = QrSegment.makeBytes(data);
94                 return encodeSegments(Arrays.asList(seg), ecl);
95         }
96         
97         
98         /*---- Static factory functions (mid level) ----*/
99         
100         /**
101          * Returns a QR Code representing the specified segments at the specified error correction
102          * level. The smallest possible QR Code version is automatically chosen for the output. The ECC level
103          * of the result may be higher than the ecl argument if it can be done without increasing the version.
104          * <p>This function allows the user to create a custom sequence of segments that switches
105          * between modes (such as alphanumeric and byte) to encode text in less space.
106          * This is a mid-level API; the high-level API is {@link #encodeText(String,Ecc)}
107          * and {@link #encodeBinary(byte[],Ecc)}.</p>
108          * @param segs the segments to encode
109          * @param ecl the error correction level to use (not {@code null}) (boostable)
110          * @return a QR Code (not {@code null}) representing the segments
111          * @throws NullPointerException if the list of segments, any segment, or the error correction level is {@code null}
112          * @throws DataTooLongException if the segments fail to fit in the
113          * largest version QR Code at the ECL, which means they are too long
114          */
115         public static QrCode encodeSegments(List<QrSegment> segs, Ecc ecl) {
116                 return encodeSegments(segs, ecl, MIN_VERSION, MAX_VERSION, -1, true);
117         }
118         
119         
120         /**
121          * Returns a QR Code representing the specified segments with the specified encoding parameters.
122          * The smallest possible QR Code version within the specified range is automatically
123          * chosen for the output. Iff boostEcl is {@code true}, then the ECC level of the
124          * result may be higher than the ecl argument if it can be done without increasing
125          * the version. The mask number is either between 0 to 7 (inclusive) to force that
126          * mask, or &#x2212;1 to automatically choose an appropriate mask (which may be slow).
127          * <p>This function allows the user to create a custom sequence of segments that switches
128          * between modes (such as alphanumeric and byte) to encode text in less space.
129          * This is a mid-level API; the high-level API is {@link #encodeText(String,Ecc)}
130          * and {@link #encodeBinary(byte[],Ecc)}.</p>
131          * @param segs the segments to encode
132          * @param ecl the error correction level to use (not {@code null}) (boostable)
133          * @param minVersion the minimum allowed version of the QR Code (at least 1)
134          * @param maxVersion the maximum allowed version of the QR Code (at most 40)
135          * @param mask the mask number to use (between 0 and 7 (inclusive)), or &#x2212;1 for automatic mask
136          * @param boostEcl increases the ECC level as long as it doesn't increase the version number
137          * @return a QR Code (not {@code null}) representing the segments
138          * @throws NullPointerException if the list of segments, any segment, or the error correction level is {@code null}
139          * @throws IllegalArgumentException if 1 &#x2264; minVersion &#x2264; maxVersion &#x2264; 40
140          * or &#x2212;1 &#x2264; mask &#x2264; 7 is violated
141          * @throws DataTooLongException if the segments fail to fit in
142          * the maxVersion QR Code at the ECL, which means they are too long
143          */
144         public static QrCode encodeSegments(List<QrSegment> segs, Ecc ecl, int minVersion, int maxVersion, int mask, boolean boostEcl) {
145                 Objects.requireNonNull(segs);
146                 Objects.requireNonNull(ecl);
147                 if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7)
148                         throw new IllegalArgumentException("Invalid value");
149                 
150                 // Find the minimal version number to use
151                 int version, dataUsedBits;
152                 for (version = minVersion; ; version++) {
153                         int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;  // Number of data bits available
154                         dataUsedBits = QrSegment.getTotalBits(segs, version);
155                         if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
156                                 break;  // This version number is found to be suitable
157                         if (version >= maxVersion) {  // All versions in the range could not fit the given data
158                                 String msg = "Segment too long";
159                                 if (dataUsedBits != -1)
160                                         msg = String.format("Data length = %d bits, Max capacity = %d bits", dataUsedBits, dataCapacityBits);
161                                 throw new DataTooLongException(msg);
162                         }
163                 }
164                 assert dataUsedBits != -1;
165                 
166                 // Increase the error correction level while the data still fits in the current version number
167                 for (Ecc newEcl : Ecc.values()) {  // From low to high
168                         if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8)
169                                 ecl = newEcl;
170                 }
171                 
172                 // Concatenate all segments to create the data bit string
173                 BitBuffer bb = new BitBuffer();
174                 for (QrSegment seg : segs) {
175                         bb.appendBits(seg.mode.modeBits, 4);
176                         bb.appendBits(seg.numChars, seg.mode.numCharCountBits(version));
177                         bb.appendData(seg.data);
178                 }
179                 assert bb.bitLength() == dataUsedBits;
180                 
181                 // Add terminator and pad up to a byte if applicable
182                 int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;
183                 assert bb.bitLength() <= dataCapacityBits;
184                 bb.appendBits(0, Math.min(4, dataCapacityBits - bb.bitLength()));
185                 bb.appendBits(0, (8 - bb.bitLength() % 8) % 8);
186                 assert bb.bitLength() % 8 == 0;
187                 
188                 // Pad with alternating bytes until data capacity is reached
189                 for (int padByte = 0xEC; bb.bitLength() < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
190                         bb.appendBits(padByte, 8);
191                 
192                 // Pack bits into bytes in big endian
193                 byte[] dataCodewords = new byte[bb.bitLength() / 8];
194                 for (int i = 0; i < bb.bitLength(); i++)
195                         dataCodewords[i >>> 3] |= bb.getBit(i) << (7 - (i & 7));
196                 
197                 // Create the QR Code object
198                 return new QrCode(version, ecl, dataCodewords, mask);
199         }
200         
201         
202         
203         /*---- Instance fields ----*/
204         
205         // Public immutable scalar parameters:
206         
207         /** The version number of this QR Code, which is between 1 and 40 (inclusive).
208          * This determines the size of this barcode. */
209         public final int version;
210         
211         /** The width and height of this QR Code, measured in modules, between
212          * 21 and 177 (inclusive). This is equal to version &#xD7; 4 + 17. */
213         public final int size;
214         
215         /** The error correction level used in this QR Code, which is not {@code null}. */
216         public final Ecc errorCorrectionLevel;
217         
218         /** The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
219          * <p>Even if a QR Code is created with automatic masking requested (mask =
220          * &#x2212;1), the resulting object still has a mask value between 0 and 7. */
221         public final int mask;
222         
223         // Private grids of modules/pixels, with dimensions of size*size:
224         
225         // The modules of this QR Code (false = white, true = black).
226         // Immutable after constructor finishes. Accessed through getModule().
227         private boolean[][] modules;
228         
229         // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
230         private boolean[][] isFunction;
231         
232         
233         
234         /*---- Constructor (low level) ----*/
235         
236         /**
237          * Constructs a QR Code with the specified version number,
238          * error correction level, data codeword bytes, and mask number.
239          * <p>This is a low-level API that most users should not use directly. A mid-level
240          * API is the {@link #encodeSegments(List,Ecc,int,int,int,boolean)} function.</p>
241          * @param ver the version number to use, which must be in the range 1 to 40 (inclusive)
242          * @param ecl the error correction level to use
243          * @param dataCodewords the bytes representing segments to encode (without ECC)
244          * @param msk the mask pattern to use, which is either &#x2212;1 for automatic choice or from 0 to 7 for fixed choice
245          * @throws NullPointerException if the byte array or error correction level is {@code null}
246          * @throws IllegalArgumentException if the version or mask value is out of range,
247          * or if the data is the wrong length for the specified version and error correction level
248          */
249         public QrCode(int ver, Ecc ecl, byte[] dataCodewords, int msk) {
250                 // Check arguments and initialize fields
251                 if (ver < MIN_VERSION || ver > MAX_VERSION)
252                         throw new IllegalArgumentException("Version value out of range");
253                 if (msk < -1 || msk > 7)
254                         throw new IllegalArgumentException("Mask value out of range");
255                 version = ver;
256                 size = ver * 4 + 17;
257                 errorCorrectionLevel = Objects.requireNonNull(ecl);
258                 Objects.requireNonNull(dataCodewords);
259                 modules    = new boolean[size][size];  // Initially all white
260                 isFunction = new boolean[size][size];
261                 
262                 // Compute ECC, draw modules, do masking
263                 drawFunctionPatterns();
264                 byte[] allCodewords = addEccAndInterleave(dataCodewords);
265                 drawCodewords(allCodewords);
266                 this.mask = handleConstructorMasking(msk);
267                 isFunction = null;
268         }
269         
270         
271         
272         /*---- Public instance methods ----*/
273         
274         /**
275          * Returns the color of the module (pixel) at the specified coordinates, which is {@code false}
276          * for white or {@code true} for black. The top left corner has the coordinates (x=0, y=0).
277          * If the specified coordinates are out of bounds, then {@code false} (white) is returned.
278          * @param x the x coordinate, where 0 is the left edge and size&#x2212;1 is the right edge
279          * @param y the y coordinate, where 0 is the top edge and size&#x2212;1 is the bottom edge
280          * @return {@code true} if the coordinates are in bounds and the module
281          * at that location is black, or {@code false} (white) otherwise
282          */
283         public boolean getModule(int x, int y) {
284                 return 0 <= x && x < size && 0 <= y && y < size && modules[y][x];
285         }
286         
287         
288         /**
289          * Returns a raster image depicting this QR Code, with the specified module scale and border modules.
290          * <p>For example, toImage(scale=10, border=4) means to pad the QR Code with 4 white
291          * border modules on all four sides, and use 10&#xD7;10 pixels to represent each module.
292          * The resulting image only contains the hex colors 000000 and FFFFFF.
293          * @param scale the side length (measured in pixels, must be positive) of each module
294          * @param border the number of border modules to add, which must be non-negative
295          * @return a new image representing this QR Code, with padding and scaling
296          * @throws IllegalArgumentException if the scale or border is out of range, or if
297          * {scale, border, size} cause the image dimensions to exceed Integer.MAX_VALUE
298          */
299         public BufferedImage toImage(int scale, int border) {
300                 if (scale <= 0 || border < 0)
301                         throw new IllegalArgumentException("Value out of range");
302                 if (border > Integer.MAX_VALUE / 2 || size + border * 2L > Integer.MAX_VALUE / scale)
303                         throw new IllegalArgumentException("Scale or border too large");
304                 
305                 BufferedImage result = new BufferedImage((size + border * 2) * scale, (size + border * 2) * scale, BufferedImage.TYPE_INT_RGB);
306                 for (int y = 0; y < result.getHeight(); y++) {
307                         for (int x = 0; x < result.getWidth(); x++) {
308                                 boolean color = getModule(x / scale - border, y / scale - border);
309                                 result.setRGB(x, y, color ? 0x000000 : 0xFFFFFF);
310                         }
311                 }
312                 return result;
313         }
314         
315         
316         /**
317          * Returns a string of SVG code for an image depicting this QR Code, with the specified number
318          * of border modules. The string always uses Unix newlines (\n), regardless of the platform.
319          * @param border the number of border modules to add, which must be non-negative
320          * @return a string representing this QR Code as an SVG XML document
321          * @throws IllegalArgumentException if the border is negative
322          */
323         public String toSvgString(int border) {
324                 if (border < 0)
325                         throw new IllegalArgumentException("Border must be non-negative");
326                 long brd = border;
327                 StringBuilder sb = new StringBuilder()
328                         .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
329                         .append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n")
330                         .append(String.format("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 %1$d %1$d\" stroke=\"none\">\n",
331                                 size + brd * 2))
332                         .append("\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n")
333                         .append("\t<path d=\"");
334                 for (int y = 0; y < size; y++) {
335                         for (int x = 0; x < size; x++) {
336                                 if (getModule(x, y)) {
337                                         if (x != 0 || y != 0)
338                                                 sb.append(" ");
339                                         sb.append(String.format("M%d,%dh1v1h-1z", x + brd, y + brd));
340                                 }
341                         }
342                 }
343                 return sb
344                         .append("\" fill=\"#000000\"/>\n")
345                         .append("</svg>\n")
346                         .toString();
347         }
348         
349         
350         
351         /*---- Private helper methods for constructor: Drawing function modules ----*/
352         
353         // Reads this object's version field, and draws and marks all function modules.
354         private void drawFunctionPatterns() {
355                 // Draw horizontal and vertical timing patterns
356                 for (int i = 0; i < size; i++) {
357                         setFunctionModule(6, i, i % 2 == 0);
358                         setFunctionModule(i, 6, i % 2 == 0);
359                 }
360                 
361                 // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
362                 drawFinderPattern(3, 3);
363                 drawFinderPattern(size - 4, 3);
364                 drawFinderPattern(3, size - 4);
365                 
366                 // Draw numerous alignment patterns
367                 int[] alignPatPos = getAlignmentPatternPositions();
368                 int numAlign = alignPatPos.length;
369                 for (int i = 0; i < numAlign; i++) {
370                         for (int j = 0; j < numAlign; j++) {
371                                 // Don't draw on the three finder corners
372                                 if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
373                                         drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
374                         }
375                 }
376                 
377                 // Draw configuration data
378                 drawFormatBits(0);  // Dummy mask value; overwritten later in the constructor
379                 drawVersion();
380         }
381         
382         
383         // Draws two copies of the format bits (with its own error correction code)
384         // based on the given mask and this object's error correction level field.
385         private void drawFormatBits(int msk) {
386                 // Calculate error correction code and pack bits
387                 int data = errorCorrectionLevel.formatBits << 3 | msk;  // errCorrLvl is uint2, mask is uint3
388                 int rem = data;
389                 for (int i = 0; i < 10; i++)
390                         rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
391                 int bits = (data << 10 | rem) ^ 0x5412;  // uint15
392                 assert bits >>> 15 == 0;
393                 
394                 // Draw first copy
395                 for (int i = 0; i <= 5; i++)
396                         setFunctionModule(8, i, getBit(bits, i));
397                 setFunctionModule(8, 7, getBit(bits, 6));
398                 setFunctionModule(8, 8, getBit(bits, 7));
399                 setFunctionModule(7, 8, getBit(bits, 8));
400                 for (int i = 9; i < 15; i++)
401                         setFunctionModule(14 - i, 8, getBit(bits, i));
402                 
403                 // Draw second copy
404                 for (int i = 0; i < 8; i++)
405                         setFunctionModule(size - 1 - i, 8, getBit(bits, i));
406                 for (int i = 8; i < 15; i++)
407                         setFunctionModule(8, size - 15 + i, getBit(bits, i));
408                 setFunctionModule(8, size - 8, true);  // Always black
409         }
410         
411         
412         // Draws two copies of the version bits (with its own error correction code),
413         // based on this object's version field, iff 7 <= version <= 40.
414         private void drawVersion() {
415                 if (version < 7)
416                         return;
417                 
418                 // Calculate error correction code and pack bits
419                 int rem = version;  // version is uint6, in the range [7, 40]
420                 for (int i = 0; i < 12; i++)
421                         rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
422                 int bits = version << 12 | rem;  // uint18
423                 assert bits >>> 18 == 0;
424                 
425                 // Draw two copies
426                 for (int i = 0; i < 18; i++) {
427                         boolean bit = getBit(bits, i);
428                         int a = size - 11 + i % 3;
429                         int b = i / 3;
430                         setFunctionModule(a, b, bit);
431                         setFunctionModule(b, a, bit);
432                 }
433         }
434         
435         
436         // Draws a 9*9 finder pattern including the border separator,
437         // with the center module at (x, y). Modules can be out of bounds.
438         private void drawFinderPattern(int x, int y) {
439                 for (int dy = -4; dy <= 4; dy++) {
440                         for (int dx = -4; dx <= 4; dx++) {
441                                 int dist = Math.max(Math.abs(dx), Math.abs(dy));  // Chebyshev/infinity norm
442                                 int xx = x + dx, yy = y + dy;
443                                 if (0 <= xx && xx < size && 0 <= yy && yy < size)
444                                         setFunctionModule(xx, yy, dist != 2 && dist != 4);
445                         }
446                 }
447         }
448         
449         
450         // Draws a 5*5 alignment pattern, with the center module
451         // at (x, y). All modules must be in bounds.
452         private void drawAlignmentPattern(int x, int y) {
453                 for (int dy = -2; dy <= 2; dy++) {
454                         for (int dx = -2; dx <= 2; dx++)
455                                 setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
456                 }
457         }
458         
459         
460         // Sets the color of a module and marks it as a function module.
461         // Only used by the constructor. Coordinates must be in bounds.
462         private void setFunctionModule(int x, int y, boolean isBlack) {
463                 modules[y][x] = isBlack;
464                 isFunction[y][x] = true;
465         }
466         
467         
468         /*---- Private helper methods for constructor: Codewords and masking ----*/
469         
470         // Returns a new byte string representing the given data with the appropriate error correction
471         // codewords appended to it, based on this object's version and error correction level.
472         private byte[] addEccAndInterleave(byte[] data) {
473                 Objects.requireNonNull(data);
474                 if (data.length != getNumDataCodewords(version, errorCorrectionLevel))
475                         throw new IllegalArgumentException();
476                 
477                 // Calculate parameter numbers
478                 int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[errorCorrectionLevel.ordinal()][version];
479                 int blockEccLen = ECC_CODEWORDS_PER_BLOCK  [errorCorrectionLevel.ordinal()][version];
480                 int rawCodewords = getNumRawDataModules(version) / 8;
481                 int numShortBlocks = numBlocks - rawCodewords % numBlocks;
482                 int shortBlockLen = rawCodewords / numBlocks;
483                 
484                 // Split data into blocks and append ECC to each block
485                 byte[][] blocks = new byte[numBlocks][];
486                 byte[] rsDiv = reedSolomonComputeDivisor(blockEccLen);
487                 for (int i = 0, k = 0; i < numBlocks; i++) {
488                         byte[] dat = Arrays.copyOfRange(data, k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
489                         k += dat.length;
490                         byte[] block = Arrays.copyOf(dat, shortBlockLen + 1);
491                         byte[] ecc = reedSolomonComputeRemainder(dat, rsDiv);
492                         System.arraycopy(ecc, 0, block, block.length - blockEccLen, ecc.length);
493                         blocks[i] = block;
494                 }
495                 
496                 // Interleave (not concatenate) the bytes from every block into a single sequence
497                 byte[] result = new byte[rawCodewords];
498                 for (int i = 0, k = 0; i < blocks[0].length; i++) {
499                         for (int j = 0; j < blocks.length; j++) {
500                                 // Skip the padding byte in short blocks
501                                 if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) {
502                                         result[k] = blocks[j][i];
503                                         k++;
504                                 }
505                         }
506                 }
507                 return result;
508         }
509         
510         
511         // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
512         // data area of this QR Code. Function modules need to be marked off before this is called.
513         private void drawCodewords(byte[] data) {
514                 Objects.requireNonNull(data);
515                 if (data.length != getNumRawDataModules(version) / 8)
516                         throw new IllegalArgumentException();
517                 
518                 int i = 0;  // Bit index into the data
519                 // Do the funny zigzag scan
520                 for (int right = size - 1; right >= 1; right -= 2) {  // Index of right column in each column pair
521                         if (right == 6)
522                                 right = 5;
523                         for (int vert = 0; vert < size; vert++) {  // Vertical counter
524                                 for (int j = 0; j < 2; j++) {
525                                         int x = right - j;  // Actual x coordinate
526                                         boolean upward = ((right + 1) & 2) == 0;
527                                         int y = upward ? size - 1 - vert : vert;  // Actual y coordinate
528                                         if (!isFunction[y][x] && i < data.length * 8) {
529                                                 modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
530                                                 i++;
531                                         }
532                                         // If this QR Code has any remainder bits (0 to 7), they were assigned as
533                                         // 0/false/white by the constructor and are left unchanged by this method
534                                 }
535                         }
536                 }
537                 assert i == data.length * 8;
538         }
539         
540         
541         // XORs the codeword modules in this QR Code with the given mask pattern.
542         // The function modules must be marked and the codeword bits must be drawn
543         // before masking. Due to the arithmetic of XOR, calling applyMask() with
544         // the same mask value a second time will undo the mask. A final well-formed
545         // QR Code needs exactly one (not zero, two, etc.) mask applied.
546         private void applyMask(int msk) {
547                 if (msk < 0 || msk > 7)
548                         throw new IllegalArgumentException("Mask value out of range");
549                 for (int y = 0; y < size; y++) {
550                         for (int x = 0; x < size; x++) {
551                                 boolean invert;
552                                 switch (msk) {
553                                         case 0:  invert = (x + y) % 2 == 0;                    break;
554                                         case 1:  invert = y % 2 == 0;                          break;
555                                         case 2:  invert = x % 3 == 0;                          break;
556                                         case 3:  invert = (x + y) % 3 == 0;                    break;
557                                         case 4:  invert = (x / 3 + y / 2) % 2 == 0;            break;
558                                         case 5:  invert = x * y % 2 + x * y % 3 == 0;          break;
559                                         case 6:  invert = (x * y % 2 + x * y % 3) % 2 == 0;    break;
560                                         case 7:  invert = ((x + y) % 2 + x * y % 3) % 2 == 0;  break;
561                                         default:  throw new AssertionError();
562                                 }
563                                 modules[y][x] ^= invert & !isFunction[y][x];
564                         }
565                 }
566         }
567         
568         
569         // A messy helper function for the constructor. This QR Code must be in an unmasked state when this
570         // method is called. The given argument is the requested mask, which is -1 for auto or 0 to 7 for fixed.
571         // This method applies and returns the actual mask chosen, from 0 to 7.
572         private int handleConstructorMasking(int msk) {
573                 if (msk == -1) {  // Automatically choose best mask
574                         int minPenalty = Integer.MAX_VALUE;
575                         for (int i = 0; i < 8; i++) {
576                                 applyMask(i);
577                                 drawFormatBits(i);
578                                 int penalty = getPenaltyScore();
579                                 if (penalty < minPenalty) {
580                                         msk = i;
581                                         minPenalty = penalty;
582                                 }
583                                 applyMask(i);  // Undoes the mask due to XOR
584                         }
585                 }
586                 assert 0 <= msk && msk <= 7;
587                 applyMask(msk);  // Apply the final choice of mask
588                 drawFormatBits(msk);  // Overwrite old format bits
589                 return msk;  // The caller shall assign this value to the final-declared field
590         }
591         
592         
593         // Calculates and returns the penalty score based on state of this QR Code's current modules.
594         // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
595         private int getPenaltyScore() {
596                 int result = 0;
597                 
598                 // Adjacent modules in row having same color, and finder-like patterns
599                 for (int y = 0; y < size; y++) {
600                         boolean runColor = false;
601                         int runX = 0;
602                         int[] runHistory = new int[7];
603                         for (int x = 0; x < size; x++) {
604                                 if (modules[y][x] == runColor) {
605                                         runX++;
606                                         if (runX == 5)
607                                                 result += PENALTY_N1;
608                                         else if (runX > 5)
609                                                 result++;
610                                 } else {
611                                         finderPenaltyAddHistory(runX, runHistory);
612                                         if (!runColor)
613                                                 result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
614                                         runColor = modules[y][x];
615                                         runX = 1;
616                                 }
617                         }
618                         result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3;
619                 }
620                 // Adjacent modules in column having same color, and finder-like patterns
621                 for (int x = 0; x < size; x++) {
622                         boolean runColor = false;
623                         int runY = 0;
624                         int[] runHistory = new int[7];
625                         for (int y = 0; y < size; y++) {
626                                 if (modules[y][x] == runColor) {
627                                         runY++;
628                                         if (runY == 5)
629                                                 result += PENALTY_N1;
630                                         else if (runY > 5)
631                                                 result++;
632                                 } else {
633                                         finderPenaltyAddHistory(runY, runHistory);
634                                         if (!runColor)
635                                                 result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
636                                         runColor = modules[y][x];
637                                         runY = 1;
638                                 }
639                         }
640                         result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3;
641                 }
642                 
643                 // 2*2 blocks of modules having same color
644                 for (int y = 0; y < size - 1; y++) {
645                         for (int x = 0; x < size - 1; x++) {
646                                 boolean color = modules[y][x];
647                                 if (  color == modules[y][x + 1] &&
648                                       color == modules[y + 1][x] &&
649                                       color == modules[y + 1][x + 1])
650                                         result += PENALTY_N2;
651                         }
652                 }
653                 
654                 // Balance of black and white modules
655                 int black = 0;
656                 for (boolean[] row : modules) {
657                         for (boolean color : row) {
658                                 if (color)
659                                         black++;
660                         }
661                 }
662                 int total = size * size;  // Note that size is odd, so black/total != 1/2
663                 // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
664                 int k = (Math.abs(black * 20 - total * 10) + total - 1) / total - 1;
665                 result += k * PENALTY_N4;
666                 return result;
667         }
668         
669         
670         
671         /*---- Private helper functions ----*/
672         
673         // Returns an ascending list of positions of alignment patterns for this version number.
674         // Each position is in the range [0,177), and are used on both the x and y axes.
675         // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
676         private int[] getAlignmentPatternPositions() {
677                 if (version == 1)
678                         return new int[]{};
679                 else {
680                         int numAlign = version / 7 + 2;
681                         int step;
682                         if (version == 32)  // Special snowflake
683                                 step = 26;
684                         else  // step = ceil[(size - 13) / (numAlign*2 - 2)] * 2
685                                 step = (version*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2;
686                         int[] result = new int[numAlign];
687                         result[0] = 6;
688                         for (int i = result.length - 1, pos = size - 7; i >= 1; i--, pos -= step)
689                                 result[i] = pos;
690                         return result;
691                 }
692         }
693         
694         
695         // Returns the number of data bits that can be stored in a QR Code of the given version number, after
696         // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
697         // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
698         private static int getNumRawDataModules(int ver) {
699                 if (ver < MIN_VERSION || ver > MAX_VERSION)
700                         throw new IllegalArgumentException("Version number out of range");
701                 
702                 int size = ver * 4 + 17;
703                 int result = size * size;   // Number of modules in the whole QR Code square
704                 result -= 8 * 8 * 3;        // Subtract the three finders with separators
705                 result -= 15 * 2 + 1;       // Subtract the format information and black module
706                 result -= (size - 16) * 2;  // Subtract the timing patterns (excluding finders)
707                 // The five lines above are equivalent to: int result = (16 * ver + 128) * ver + 64;
708                 if (ver >= 2) {
709                         int numAlign = ver / 7 + 2;
710                         result -= (numAlign - 1) * (numAlign - 1) * 25;  // Subtract alignment patterns not overlapping with timing patterns
711                         result -= (numAlign - 2) * 2 * 20;  // Subtract alignment patterns that overlap with timing patterns
712                         // The two lines above are equivalent to: result -= (25 * numAlign - 10) * numAlign - 55;
713                         if (ver >= 7)
714                                 result -= 6 * 3 * 2;  // Subtract version information
715                 }
716                 assert 208 <= result && result <= 29648;
717                 return result;
718         }
719         
720         
721         // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
722         // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
723         private static byte[] reedSolomonComputeDivisor(int degree) {
724                 if (degree < 1 || degree > 255)
725                         throw new IllegalArgumentException("Degree out of range");
726                 // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
727                 // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
728                 byte[] result = new byte[degree];
729                 result[degree - 1] = 1;  // Start off with the monomial x^0
730                 
731                 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
732                 // and drop the highest monomial term which is always 1x^degree.
733                 // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
734                 int root = 1;
735                 for (int i = 0; i < degree; i++) {
736                         // Multiply the current product by (x - r^i)
737                         for (int j = 0; j < result.length; j++) {
738                                 result[j] = (byte)reedSolomonMultiply(result[j] & 0xFF, root);
739                                 if (j + 1 < result.length)
740                                         result[j] ^= result[j + 1];
741                         }
742                         root = reedSolomonMultiply(root, 0x02);
743                 }
744                 return result;
745         }
746         
747         
748         // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
749         private static byte[] reedSolomonComputeRemainder(byte[] data, byte[] divisor) {
750                 Objects.requireNonNull(data);
751                 Objects.requireNonNull(divisor);
752                 byte[] result = new byte[divisor.length];
753                 for (byte b : data) {  // Polynomial division
754                         int factor = (b ^ result[0]) & 0xFF;
755                         System.arraycopy(result, 1, result, 0, result.length - 1);
756                         result[result.length - 1] = 0;
757                         for (int i = 0; i < result.length; i++)
758                                 result[i] ^= reedSolomonMultiply(divisor[i] & 0xFF, factor);
759                 }
760                 return result;
761         }
762         
763         
764         // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
765         // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
766         private static int reedSolomonMultiply(int x, int y) {
767                 assert x >> 8 == 0 && y >> 8 == 0;
768                 // Russian peasant multiplication
769                 int z = 0;
770                 for (int i = 7; i >= 0; i--) {
771                         z = (z << 1) ^ ((z >>> 7) * 0x11D);
772                         z ^= ((y >>> i) & 1) * x;
773                 }
774                 assert z >>> 8 == 0;
775                 return z;
776         }
777         
778         
779         // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
780         // QR Code of the given version number and error correction level, with remainder bits discarded.
781         // This stateless pure function could be implemented as a (40*4)-cell lookup table.
782         static int getNumDataCodewords(int ver, Ecc ecl) {
783                 return getNumRawDataModules(ver) / 8
784                         - ECC_CODEWORDS_PER_BLOCK    [ecl.ordinal()][ver]
785                         * NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal()][ver];
786         }
787         
788         
789         // Can only be called immediately after a white run is added, and
790         // returns either 0, 1, or 2. A helper function for getPenaltyScore().
791         private int finderPenaltyCountPatterns(int[] runHistory) {
792                 int n = runHistory[1];
793                 assert n <= size * 3;
794                 boolean core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
795                 return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
796                      + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
797         }
798         
799         
800         // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
801         private int finderPenaltyTerminateAndCount(boolean currentRunColor, int currentRunLength, int[] runHistory) {
802                 if (currentRunColor) {  // Terminate black run
803                         finderPenaltyAddHistory(currentRunLength, runHistory);
804                         currentRunLength = 0;
805                 }
806                 currentRunLength += size;  // Add white border to final run
807                 finderPenaltyAddHistory(currentRunLength, runHistory);
808                 return finderPenaltyCountPatterns(runHistory);
809         }
810         
811         
812         // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
813         private void finderPenaltyAddHistory(int currentRunLength, int[] runHistory) {
814                 if (runHistory[0] == 0)
815                         currentRunLength += size;  // Add white border to initial run
816                 System.arraycopy(runHistory, 0, runHistory, 1, runHistory.length - 1);
817                 runHistory[0] = currentRunLength;
818         }
819         
820         
821         // Returns true iff the i'th bit of x is set to 1.
822         static boolean getBit(int x, int i) {
823                 return ((x >>> i) & 1) != 0;
824         }
825         
826         
827         /*---- Constants and tables ----*/
828         
829         /** The minimum version number  (1) supported in the QR Code Model 2 standard. */
830         public static final int MIN_VERSION =  1;
831         
832         /** The maximum version number (40) supported in the QR Code Model 2 standard. */
833         public static final int MAX_VERSION = 40;
834         
835         
836         // For use in getPenaltyScore(), when evaluating which mask is best.
837         private static final int PENALTY_N1 =  3;
838         private static final int PENALTY_N2 =  3;
839         private static final int PENALTY_N3 = 40;
840         private static final int PENALTY_N4 = 10;
841         
842         
843         private static final byte[][] ECC_CODEWORDS_PER_BLOCK = {
844                 // Version: (note that index 0 is for padding, and is set to an illegal value)
845                 //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
846                 {-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
847                 {-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
848                 {-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
849                 {-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
850         };
851         
852         private static final byte[][] NUM_ERROR_CORRECTION_BLOCKS = {
853                 // Version: (note that index 0 is for padding, and is set to an illegal value)
854                 //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
855                 {-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
856                 {-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
857                 {-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
858                 {-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
859         };
860         
861         
862         
863         /*---- Public helper enumeration ----*/
864         
865         /**
866          * The error correction level in a QR Code symbol.
867          */
868         public enum Ecc {
869                 // Must be declared in ascending order of error protection
870                 // so that the implicit ordinal() and values() work properly
871                 /** The QR Code can tolerate about  7% erroneous codewords. */ LOW(1),
872                 /** The QR Code can tolerate about 15% erroneous codewords. */ MEDIUM(0),
873                 /** The QR Code can tolerate about 25% erroneous codewords. */ QUARTILE(3),
874                 /** The QR Code can tolerate about 30% erroneous codewords. */ HIGH(2);
875                 
876                 // In the range 0 to 3 (unsigned 2-bit integer).
877                 final int formatBits;
878                 
879                 // Constructor.
880                 private Ecc(int fb) {
881                         formatBits = fb;
882                 }
883         }
884         
885 }