1 /*
2  * QR Code generator library (C++)
3  *
4  * Copyright (c) Project Nayuki. (MIT License)
5  * https://www.nayuki.io/page/qr-code-generator-library
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  * - The above copyright notice and this permission notice shall be included in
14  *   all copies or substantial portions of the Software.
15  * - The Software is provided "as is", without warranty of any kind, express or
16  *   implied, including but not limited to the warranties of merchantability,
17  *   fitness for a particular purpose and noninfringement. In no event shall the
18  *   authors or copyright holders be liable for any claim, damages or other
19  *   liability, whether in an action of contract, tort or otherwise, arising from,
20  *   out of or in connection with the Software or the use or other dealings in the
21  *   Software.
22  */
23 
24 #include <algorithm>
25 #include <climits>
26 #include <cstddef>
27 #include <cstdlib>
28 #include <sstream>
29 #include <utility>
30 #include "BitBuffer.hpp"
31 #include "QrCode.hpp"
32 
33 using std::int8_t;
34 using std::uint8_t;
35 using std::size_t;
36 using std::vector;
37 
38 
39 namespace qrcodegen {
40 
getFormatBits(Ecc ecl)41 int QrCode::getFormatBits(Ecc ecl) {
42 	switch (ecl) {
43 		case Ecc::LOW     :  return 1;
44 		case Ecc::MEDIUM  :  return 0;
45 		case Ecc::QUARTILE:  return 3;
46 		case Ecc::HIGH    :  return 2;
47 		default:  throw std::logic_error("Assertion error");
48 	}
49 }
50 
51 
encodeText(const char * text,Ecc ecl)52 QrCode QrCode::encodeText(const char *text, Ecc ecl) {
53 	vector<QrSegment> segs = QrSegment::makeSegments(text);
54 	return encodeSegments(segs, ecl);
55 }
56 
57 
encodeBinary(const vector<uint8_t> & data,Ecc ecl)58 QrCode QrCode::encodeBinary(const vector<uint8_t> &data, Ecc ecl) {
59 	vector<QrSegment> segs{QrSegment::makeBytes(data)};
60 	return encodeSegments(segs, ecl);
61 }
62 
63 
encodeSegments(const vector<QrSegment> & segs,Ecc ecl,int minVersion,int maxVersion,int mask,bool boostEcl)64 QrCode QrCode::encodeSegments(const vector<QrSegment> &segs, Ecc ecl,
65 		int minVersion, int maxVersion, int mask, bool boostEcl) {
66 	if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7)
67 		throw std::invalid_argument("Invalid value");
68 
69 	// Find the minimal version number to use
70 	int version, dataUsedBits;
71 	for (version = minVersion; ; version++) {
72 		int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;  // Number of data bits available
73 		dataUsedBits = QrSegment::getTotalBits(segs, version);
74 		if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
75 			break;  // This version number is found to be suitable
76 		if (version >= maxVersion) {  // All versions in the range could not fit the given data
77 			std::ostringstream sb;
78 			if (dataUsedBits == -1)
79 				sb << "Segment too long";
80 			else {
81 				sb << "Data length = " << dataUsedBits << " bits, ";
82 				sb << "Max capacity = " << dataCapacityBits << " bits";
83 			}
84 			throw data_too_long(sb.str());
85 		}
86 	}
87 	if (dataUsedBits == -1)
88 		throw std::logic_error("Assertion error");
89 
90 	// Increase the error correction level while the data still fits in the current version number
91 	for (Ecc newEcl : vector<Ecc>{Ecc::MEDIUM, Ecc::QUARTILE, Ecc::HIGH}) {  // From low to high
92 		if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8)
93 			ecl = newEcl;
94 	}
95 
96 	// Concatenate all segments to create the data bit string
97 	BitBuffer bb;
98 	for (const QrSegment &seg : segs) {
99 		bb.appendBits(static_cast<uint32_t>(seg.getMode().getModeBits()), 4);
100 		bb.appendBits(static_cast<uint32_t>(seg.getNumChars()), seg.getMode().numCharCountBits(version));
101 		bb.insert(bb.end(), seg.getData().begin(), seg.getData().end());
102 	}
103 	if (bb.size() != static_cast<unsigned int>(dataUsedBits))
104 		throw std::logic_error("Assertion error");
105 
106 	// Add terminator and pad up to a byte if applicable
107 	size_t dataCapacityBits = static_cast<size_t>(getNumDataCodewords(version, ecl)) * 8;
108 	if (bb.size() > dataCapacityBits)
109 		throw std::logic_error("Assertion error");
110 	bb.appendBits(0, std::min(4, static_cast<int>(dataCapacityBits - bb.size())));
111 	bb.appendBits(0, (8 - static_cast<int>(bb.size() % 8)) % 8);
112 	if (bb.size() % 8 != 0)
113 		throw std::logic_error("Assertion error");
114 
115 	// Pad with alternating bytes until data capacity is reached
116 	for (uint8_t padByte = 0xEC; bb.size() < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
117 		bb.appendBits(padByte, 8);
118 
119 	// Pack bits into bytes in big endian
120 	vector<uint8_t> dataCodewords(bb.size() / 8);
121 	for (size_t i = 0; i < bb.size(); i++)
122 		dataCodewords[i >> 3] |= (bb.at(i) ? 1 : 0) << (7 - (i & 7));
123 
124 	// Create the QR Code object
125 	return QrCode(version, ecl, dataCodewords, mask);
126 }
127 
128 
QrCode(int ver,Ecc ecl,const vector<uint8_t> & dataCodewords,int msk)129 QrCode::QrCode(int ver, Ecc ecl, const vector<uint8_t> &dataCodewords, int msk) :
130 		// Initialize fields and check arguments
131 		version(ver),
132 		errorCorrectionLevel(ecl) {
133 	if (ver < MIN_VERSION || ver > MAX_VERSION)
134 		throw std::domain_error("Version value out of range");
135 	if (msk < -1 || msk > 7)
136 		throw std::domain_error("Mask value out of range");
137 	size = ver * 4 + 17;
138 	size_t sz = static_cast<size_t>(size);
139 	modules    = vector<vector<bool> >(sz, vector<bool>(sz));  // Initially all white
140 	isFunction = vector<vector<bool> >(sz, vector<bool>(sz));
141 
142 	// Compute ECC, draw modules
143 	drawFunctionPatterns();
144 	const vector<uint8_t> allCodewords = addEccAndInterleave(dataCodewords);
145 	drawCodewords(allCodewords);
146 
147 	// Do masking
148 	if (msk == -1) {  // Automatically choose best mask
149 		long minPenalty = LONG_MAX;
150 		for (int i = 0; i < 8; i++) {
151 			applyMask(i);
152 			drawFormatBits(i);
153 			long penalty = getPenaltyScore();
154 			if (penalty < minPenalty) {
155 				msk = i;
156 				minPenalty = penalty;
157 			}
158 			applyMask(i);  // Undoes the mask due to XOR
159 		}
160 	}
161 	if (msk < 0 || msk > 7)
162 		throw std::logic_error("Assertion error");
163 	this->mask = msk;
164 	applyMask(msk);  // Apply the final choice of mask
165 	drawFormatBits(msk);  // Overwrite old format bits
166 
167 	isFunction.clear();
168 	isFunction.shrink_to_fit();
169 }
170 
171 
getVersion() const172 int QrCode::getVersion() const {
173 	return version;
174 }
175 
176 
getSize() const177 int QrCode::getSize() const {
178 	return size;
179 }
180 
181 
getErrorCorrectionLevel() const182 QrCode::Ecc QrCode::getErrorCorrectionLevel() const {
183 	return errorCorrectionLevel;
184 }
185 
186 
getMask() const187 int QrCode::getMask() const {
188 	return mask;
189 }
190 
191 
getModule(int x,int y) const192 bool QrCode::getModule(int x, int y) const {
193 	return 0 <= x && x < size && 0 <= y && y < size && module(x, y);
194 }
195 
196 
toSvgString(int border) const197 std::string QrCode::toSvgString(int border) const {
198 	if (border < 0)
199 		throw std::domain_error("Border must be non-negative");
200 	if (border > INT_MAX / 2 || border * 2 > INT_MAX - size)
201 		throw std::overflow_error("Border too large");
202 
203 	std::ostringstream sb;
204 	sb << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
205 	sb << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
206 	sb << "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 ";
207 	sb << (size + border * 2) << " " << (size + border * 2) << "\" stroke=\"none\">\n";
208 	sb << "\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n";
209 	sb << "\t<path d=\"";
210 	for (int y = 0; y < size; y++) {
211 		for (int x = 0; x < size; x++) {
212 			if (getModule(x, y)) {
213 				if (x != 0 || y != 0)
214 					sb << " ";
215 				sb << "M" << (x + border) << "," << (y + border) << "h1v1h-1z";
216 			}
217 		}
218 	}
219 	sb << "\" fill=\"#000000\"/>\n";
220 	sb << "</svg>\n";
221 	return sb.str();
222 }
223 
224 
drawFunctionPatterns()225 void QrCode::drawFunctionPatterns() {
226 	// Draw horizontal and vertical timing patterns
227 	for (int i = 0; i < size; i++) {
228 		setFunctionModule(6, i, i % 2 == 0);
229 		setFunctionModule(i, 6, i % 2 == 0);
230 	}
231 
232 	// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
233 	drawFinderPattern(3, 3);
234 	drawFinderPattern(size - 4, 3);
235 	drawFinderPattern(3, size - 4);
236 
237 	// Draw numerous alignment patterns
238 	const vector<int> alignPatPos = getAlignmentPatternPositions();
239 	size_t numAlign = alignPatPos.size();
240 	for (size_t i = 0; i < numAlign; i++) {
241 		for (size_t j = 0; j < numAlign; j++) {
242 			// Don't draw on the three finder corners
243 			if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))
244 				drawAlignmentPattern(alignPatPos.at(i), alignPatPos.at(j));
245 		}
246 	}
247 
248 	// Draw configuration data
249 	drawFormatBits(0);  // Dummy mask value; overwritten later in the constructor
250 	drawVersion();
251 }
252 
253 
drawFormatBits(int msk)254 void QrCode::drawFormatBits(int msk) {
255 	// Calculate error correction code and pack bits
256 	int data = getFormatBits(errorCorrectionLevel) << 3 | msk;  // errCorrLvl is uint2, msk is uint3
257 	int rem = data;
258 	for (int i = 0; i < 10; i++)
259 		rem = (rem << 1) ^ ((rem >> 9) * 0x537);
260 	int bits = (data << 10 | rem) ^ 0x5412;  // uint15
261 	if (bits >> 15 != 0)
262 		throw std::logic_error("Assertion error");
263 
264 	// Draw first copy
265 	for (int i = 0; i <= 5; i++)
266 		setFunctionModule(8, i, getBit(bits, i));
267 	setFunctionModule(8, 7, getBit(bits, 6));
268 	setFunctionModule(8, 8, getBit(bits, 7));
269 	setFunctionModule(7, 8, getBit(bits, 8));
270 	for (int i = 9; i < 15; i++)
271 		setFunctionModule(14 - i, 8, getBit(bits, i));
272 
273 	// Draw second copy
274 	for (int i = 0; i < 8; i++)
275 		setFunctionModule(size - 1 - i, 8, getBit(bits, i));
276 	for (int i = 8; i < 15; i++)
277 		setFunctionModule(8, size - 15 + i, getBit(bits, i));
278 	setFunctionModule(8, size - 8, true);  // Always black
279 }
280 
281 
drawVersion()282 void QrCode::drawVersion() {
283 	if (version < 7)
284 		return;
285 
286 	// Calculate error correction code and pack bits
287 	int rem = version;  // version is uint6, in the range [7, 40]
288 	for (int i = 0; i < 12; i++)
289 		rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
290 	long bits = static_cast<long>(version) << 12 | rem;  // uint18
291 	if (bits >> 18 != 0)
292 		throw std::logic_error("Assertion error");
293 
294 	// Draw two copies
295 	for (int i = 0; i < 18; i++) {
296 		bool bit = getBit(bits, i);
297 		int a = size - 11 + i % 3;
298 		int b = i / 3;
299 		setFunctionModule(a, b, bit);
300 		setFunctionModule(b, a, bit);
301 	}
302 }
303 
304 
drawFinderPattern(int x,int y)305 void QrCode::drawFinderPattern(int x, int y) {
306 	for (int dy = -4; dy <= 4; dy++) {
307 		for (int dx = -4; dx <= 4; dx++) {
308 			int dist = std::max(std::abs(dx), std::abs(dy));  // Chebyshev/infinity norm
309 			int xx = x + dx, yy = y + dy;
310 			if (0 <= xx && xx < size && 0 <= yy && yy < size)
311 				setFunctionModule(xx, yy, dist != 2 && dist != 4);
312 		}
313 	}
314 }
315 
316 
drawAlignmentPattern(int x,int y)317 void QrCode::drawAlignmentPattern(int x, int y) {
318 	for (int dy = -2; dy <= 2; dy++) {
319 		for (int dx = -2; dx <= 2; dx++)
320 			setFunctionModule(x + dx, y + dy, std::max(std::abs(dx), std::abs(dy)) != 1);
321 	}
322 }
323 
324 
setFunctionModule(int x,int y,bool isBlack)325 void QrCode::setFunctionModule(int x, int y, bool isBlack) {
326 	size_t ux = static_cast<size_t>(x);
327 	size_t uy = static_cast<size_t>(y);
328 	modules   .at(uy).at(ux) = isBlack;
329 	isFunction.at(uy).at(ux) = true;
330 }
331 
332 
module(int x,int y) const333 bool QrCode::module(int x, int y) const {
334 	return modules.at(static_cast<size_t>(y)).at(static_cast<size_t>(x));
335 }
336 
337 
addEccAndInterleave(const vector<uint8_t> & data) const338 vector<uint8_t> QrCode::addEccAndInterleave(const vector<uint8_t> &data) const {
339 	if (data.size() != static_cast<unsigned int>(getNumDataCodewords(version, errorCorrectionLevel)))
340 		throw std::invalid_argument("Invalid argument");
341 
342 	// Calculate parameter numbers
343 	int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(errorCorrectionLevel)][version];
344 	int blockEccLen = ECC_CODEWORDS_PER_BLOCK  [static_cast<int>(errorCorrectionLevel)][version];
345 	int rawCodewords = getNumRawDataModules(version) / 8;
346 	int numShortBlocks = numBlocks - rawCodewords % numBlocks;
347 	int shortBlockLen = rawCodewords / numBlocks;
348 
349 	// Split data into blocks and append ECC to each block
350 	vector<vector<uint8_t> > blocks;
351 	const vector<uint8_t> rsDiv = reedSolomonComputeDivisor(blockEccLen);
352 	for (int i = 0, k = 0; i < numBlocks; i++) {
353 		vector<uint8_t> dat(data.cbegin() + k, data.cbegin() + (k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)));
354 		k += static_cast<int>(dat.size());
355 		const vector<uint8_t> ecc = reedSolomonComputeRemainder(dat, rsDiv);
356 		if (i < numShortBlocks)
357 			dat.push_back(0);
358 		dat.insert(dat.end(), ecc.cbegin(), ecc.cend());
359 		blocks.push_back(std::move(dat));
360 	}
361 
362 	// Interleave (not concatenate) the bytes from every block into a single sequence
363 	vector<uint8_t> result;
364 	for (size_t i = 0; i < blocks.at(0).size(); i++) {
365 		for (size_t j = 0; j < blocks.size(); j++) {
366 			// Skip the padding byte in short blocks
367 			if (i != static_cast<unsigned int>(shortBlockLen - blockEccLen) || j >= static_cast<unsigned int>(numShortBlocks))
368 				result.push_back(blocks.at(j).at(i));
369 		}
370 	}
371 	if (result.size() != static_cast<unsigned int>(rawCodewords))
372 		throw std::logic_error("Assertion error");
373 	return result;
374 }
375 
376 
drawCodewords(const vector<uint8_t> & data)377 void QrCode::drawCodewords(const vector<uint8_t> &data) {
378 	if (data.size() != static_cast<unsigned int>(getNumRawDataModules(version) / 8))
379 		throw std::invalid_argument("Invalid argument");
380 
381 	size_t i = 0;  // Bit index into the data
382 	// Do the funny zigzag scan
383 	for (int right = size - 1; right >= 1; right -= 2) {  // Index of right column in each column pair
384 		if (right == 6)
385 			right = 5;
386 		for (int vert = 0; vert < size; vert++) {  // Vertical counter
387 			for (int j = 0; j < 2; j++) {
388 				size_t x = static_cast<size_t>(right - j);  // Actual x coordinate
389 				bool upward = ((right + 1) & 2) == 0;
390 				size_t y = static_cast<size_t>(upward ? size - 1 - vert : vert);  // Actual y coordinate
391 				if (!isFunction.at(y).at(x) && i < data.size() * 8) {
392 					modules.at(y).at(x) = getBit(data.at(i >> 3), 7 - static_cast<int>(i & 7));
393 					i++;
394 				}
395 				// If this QR Code has any remainder bits (0 to 7), they were assigned as
396 				// 0/false/white by the constructor and are left unchanged by this method
397 			}
398 		}
399 	}
400 	if (i != data.size() * 8)
401 		throw std::logic_error("Assertion error");
402 }
403 
404 
applyMask(int msk)405 void QrCode::applyMask(int msk) {
406 	if (msk < 0 || msk > 7)
407 		throw std::domain_error("Mask value out of range");
408 	size_t sz = static_cast<size_t>(size);
409 	for (size_t y = 0; y < sz; y++) {
410 		for (size_t x = 0; x < sz; x++) {
411 			bool invert;
412 			switch (msk) {
413 				case 0:  invert = (x + y) % 2 == 0;                    break;
414 				case 1:  invert = y % 2 == 0;                          break;
415 				case 2:  invert = x % 3 == 0;                          break;
416 				case 3:  invert = (x + y) % 3 == 0;                    break;
417 				case 4:  invert = (x / 3 + y / 2) % 2 == 0;            break;
418 				case 5:  invert = x * y % 2 + x * y % 3 == 0;          break;
419 				case 6:  invert = (x * y % 2 + x * y % 3) % 2 == 0;    break;
420 				case 7:  invert = ((x + y) % 2 + x * y % 3) % 2 == 0;  break;
421 				default:  throw std::logic_error("Assertion error");
422 			}
423 			modules.at(y).at(x) = modules.at(y).at(x) ^ (invert & !isFunction.at(y).at(x));
424 		}
425 	}
426 }
427 
428 
getPenaltyScore() const429 long QrCode::getPenaltyScore() const {
430 	long result = 0;
431 
432 	// Adjacent modules in row having same color, and finder-like patterns
433 	for (int y = 0; y < size; y++) {
434 		bool runColor = false;
435 		int runX = 0;
436 		std::array<int,7> runHistory = {};
437 		int padRun = size;  // Add white border to initial run
438 		for (int x = 0; x < size; x++) {
439 			if (module(x, y) == runColor) {
440 				runX++;
441 				if (runX == 5)
442 					result += PENALTY_N1;
443 				else if (runX > 5)
444 					result++;
445 			} else {
446 				finderPenaltyAddHistory(runX + padRun, runHistory);
447 				padRun = 0;
448 				if (!runColor)
449 					result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
450 				runColor = module(x, y);
451 				runX = 1;
452 			}
453 		}
454 		result += finderPenaltyTerminateAndCount(runColor, runX + padRun, runHistory) * PENALTY_N3;
455 	}
456 	// Adjacent modules in column having same color, and finder-like patterns
457 	for (int x = 0; x < size; x++) {
458 		bool runColor = false;
459 		int runY = 0;
460 		std::array<int,7> runHistory = {};
461 		int padRun = size;  // Add white border to initial run
462 		for (int y = 0; y < size; y++) {
463 			if (module(x, y) == runColor) {
464 				runY++;
465 				if (runY == 5)
466 					result += PENALTY_N1;
467 				else if (runY > 5)
468 					result++;
469 			} else {
470 				finderPenaltyAddHistory(runY + padRun, runHistory);
471 				padRun = 0;
472 				if (!runColor)
473 					result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3;
474 				runColor = module(x, y);
475 				runY = 1;
476 			}
477 		}
478 		result += finderPenaltyTerminateAndCount(runColor, runY + padRun, runHistory) * PENALTY_N3;
479 	}
480 
481 	// 2*2 blocks of modules having same color
482 	for (int y = 0; y < size - 1; y++) {
483 		for (int x = 0; x < size - 1; x++) {
484 			bool  color = module(x, y);
485 			if (  color == module(x + 1, y) &&
486 			      color == module(x, y + 1) &&
487 			      color == module(x + 1, y + 1))
488 				result += PENALTY_N2;
489 		}
490 	}
491 
492 	// Balance of black and white modules
493 	int black = 0;
494 	for (const vector<bool> &row : modules) {
495 		for (bool color : row) {
496 			if (color)
497 				black++;
498 		}
499 	}
500 	int total = size * size;  // Note that size is odd, so black/total != 1/2
501 	// Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
502 	int k = static_cast<int>((std::abs(black * 20L - total * 10L) + total - 1) / total) - 1;
503 	result += k * PENALTY_N4;
504 	return result;
505 }
506 
507 
getAlignmentPatternPositions() const508 vector<int> QrCode::getAlignmentPatternPositions() const {
509 	if (version == 1)
510 		return vector<int>();
511 	else {
512 		int numAlign = version / 7 + 2;
513 		int step = (version == 32) ? 26 :
514 			(version*4 + numAlign*2 + 1) / (numAlign*2 - 2) * 2;
515 		vector<int> result;
516 		for (int i = 0, pos = size - 7; i < numAlign - 1; i++, pos -= step)
517 			result.insert(result.begin(), pos);
518 		result.insert(result.begin(), 6);
519 		return result;
520 	}
521 }
522 
523 
getNumRawDataModules(int ver)524 int QrCode::getNumRawDataModules(int ver) {
525 	if (ver < MIN_VERSION || ver > MAX_VERSION)
526 		throw std::domain_error("Version number out of range");
527 	int result = (16 * ver + 128) * ver + 64;
528 	if (ver >= 2) {
529 		int numAlign = ver / 7 + 2;
530 		result -= (25 * numAlign - 10) * numAlign - 55;
531 		if (ver >= 7)
532 			result -= 36;
533 	}
534 	if (!(208 <= result && result <= 29648))
535 		throw std::logic_error("Assertion error");
536 	return result;
537 }
538 
539 
getNumDataCodewords(int ver,Ecc ecl)540 int QrCode::getNumDataCodewords(int ver, Ecc ecl) {
541 	return getNumRawDataModules(ver) / 8
542 		- ECC_CODEWORDS_PER_BLOCK    [static_cast<int>(ecl)][ver]
543 		* NUM_ERROR_CORRECTION_BLOCKS[static_cast<int>(ecl)][ver];
544 }
545 
546 
reedSolomonComputeDivisor(int degree)547 vector<uint8_t> QrCode::reedSolomonComputeDivisor(int degree) {
548 	if (degree < 1 || degree > 255)
549 		throw std::domain_error("Degree out of range");
550 	// Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
551 	// For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
552 	vector<uint8_t> result(static_cast<size_t>(degree));
553 	result.at(result.size() - 1) = 1;  // Start off with the monomial x^0
554 
555 	// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
556 	// and drop the highest monomial term which is always 1x^degree.
557 	// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
558 	uint8_t root = 1;
559 	for (int i = 0; i < degree; i++) {
560 		// Multiply the current product by (x - r^i)
561 		for (size_t j = 0; j < result.size(); j++) {
562 			result.at(j) = reedSolomonMultiply(result.at(j), root);
563 			if (j + 1 < result.size())
564 				result.at(j) ^= result.at(j + 1);
565 		}
566 		root = reedSolomonMultiply(root, 0x02);
567 	}
568 	return result;
569 }
570 
571 
reedSolomonComputeRemainder(const vector<uint8_t> & data,const vector<uint8_t> & divisor)572 vector<uint8_t> QrCode::reedSolomonComputeRemainder(const vector<uint8_t> &data, const vector<uint8_t> &divisor) {
573 	vector<uint8_t> result(divisor.size());
574 	for (uint8_t b : data) {  // Polynomial division
575 		uint8_t factor = b ^ result.at(0);
576 		result.erase(result.begin());
577 		result.push_back(0);
578 		for (size_t i = 0; i < result.size(); i++)
579 			result.at(i) ^= reedSolomonMultiply(divisor.at(i), factor);
580 	}
581 	return result;
582 }
583 
584 
reedSolomonMultiply(uint8_t x,uint8_t y)585 uint8_t QrCode::reedSolomonMultiply(uint8_t x, uint8_t y) {
586 	// Russian peasant multiplication
587 	int z = 0;
588 	for (int i = 7; i >= 0; i--) {
589 		z = (z << 1) ^ ((z >> 7) * 0x11D);
590 		z ^= ((y >> i) & 1) * x;
591 	}
592 	if (z >> 8 != 0)
593 		throw std::logic_error("Assertion error");
594 	return static_cast<uint8_t>(z);
595 }
596 
597 
finderPenaltyCountPatterns(const std::array<int,7> & runHistory) const598 int QrCode::finderPenaltyCountPatterns(const std::array<int,7> &runHistory) const {
599 	int n = runHistory.at(1);
600 	if (n > size * 3)
601 		throw std::logic_error("Assertion error");
602 	bool core = n > 0 && runHistory.at(2) == n && runHistory.at(3) == n * 3 && runHistory.at(4) == n && runHistory.at(5) == n;
603 	return (core && runHistory.at(0) >= n * 4 && runHistory.at(6) >= n ? 1 : 0)
604 	     + (core && runHistory.at(6) >= n * 4 && runHistory.at(0) >= n ? 1 : 0);
605 }
606 
607 
finderPenaltyTerminateAndCount(bool currentRunColor,int currentRunLength,std::array<int,7> & runHistory) const608 int QrCode::finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array<int,7> &runHistory) const {
609 	if (currentRunColor) {  // Terminate black run
610 		finderPenaltyAddHistory(currentRunLength, runHistory);
611 		currentRunLength = 0;
612 	}
613 	currentRunLength += size;  // Add white border to final run
614 	finderPenaltyAddHistory(currentRunLength, runHistory);
615 	return finderPenaltyCountPatterns(runHistory);
616 }
617 
618 
finderPenaltyAddHistory(int currentRunLength,std::array<int,7> & runHistory)619 void QrCode::finderPenaltyAddHistory(int currentRunLength, std::array<int,7> &runHistory) {
620 	std::copy_backward(runHistory.cbegin(), runHistory.cend() - 1, runHistory.end());
621 	runHistory.at(0) = currentRunLength;
622 }
623 
624 
getBit(long x,int i)625 bool QrCode::getBit(long x, int i) {
626 	return ((x >> i) & 1) != 0;
627 }
628 
629 
630 /*---- Tables of constants ----*/
631 
632 const int QrCode::PENALTY_N1 =  3;
633 const int QrCode::PENALTY_N2 =  3;
634 const int QrCode::PENALTY_N3 = 40;
635 const int QrCode::PENALTY_N4 = 10;
636 
637 
638 const int8_t QrCode::ECC_CODEWORDS_PER_BLOCK[4][41] = {
639 	// Version: (note that index 0 is for padding, and is set to an illegal value)
640 	//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
641 	{-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
642 	{-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
643 	{-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
644 	{-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
645 };
646 
647 const int8_t QrCode::NUM_ERROR_CORRECTION_BLOCKS[4][41] = {
648 	// Version: (note that index 0 is for padding, and is set to an illegal value)
649 	//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
650 	{-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
651 	{-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
652 	{-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
653 	{-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
654 };
655 
656 
data_too_long(const std::string & msg)657 data_too_long::data_too_long(const std::string &msg) :
658 	std::length_error(msg) {}
659 
660 }
661