2 * QR Code generator library (Rust)
4 * Copyright (c) Project Nayuki. (MIT License)
5 * https://www.nayuki.io/page/qr-code-generator-library
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
25 //! Generates QR Codes from text strings and byte arrays.
27 //! This project aims to be the best, clearest QR Code generator library.
28 //! The primary goals are flexible options and absolute correctness.
29 //! Secondary goals are compact implementation size and good documentation comments.
31 //! Home page with live JavaScript demo, extensive descriptions, and competitor comparisons:
32 //! [https://www.nayuki.io/page/qr-code-generator-library](https://www.nayuki.io/page/qr-code-generator-library)
38 //! - Available in 6 programming languages, all with nearly equal functionality: Java, TypeScript/JavaScript, Python, Rust, C++, C
39 //! - Significantly shorter code but more documentation comments compared to competing libraries
40 //! - Supports encoding all 40 versions (sizes) and all 4 error correction levels, as per the QR Code Model 2 standard
41 //! - Output formats: Raw modules/pixels of the QR symbol, SVG XML string
42 //! - Detects finder-like penalty patterns more accurately than other implementations
43 //! - Encodes numeric and special-alphanumeric text in less space than general text
44 //! - Open source code under the permissive MIT License
46 //! Manual parameters:
48 //! - User can specify minimum and maximum version numbers allowed, then library will automatically choose smallest version in the range that fits the data
49 //! - User can specify mask pattern manually, otherwise library will automatically evaluate all 8 masks and select the optimal one
50 //! - User can specify absolute error correction level, or allow the library to boost it if it doesn't increase the version number
51 //! - User can create a list of data segments manually and add ECI segments
56 //! extern crate qrcodegen;
57 //! use qrcodegen::QrCode;
58 //! use qrcodegen::QrCodeEcc;
59 //! use qrcodegen::QrSegment;
65 //! let qr = QrCode::encode_text("Hello, world!",
66 //! QrCodeEcc::Medium).unwrap();
67 //! let svg = qr.to_svg_string(4);
73 //! let chrs: Vec<char> = "3141592653589793238462643383".chars().collect();
74 //! let segs = QrSegment::make_segments(&chrs);
75 //! let qr = QrCode::encode_segments_advanced(
76 //! &segs, QrCodeEcc::High, 5, 5, Some(Mask::new(2)), false).unwrap();
77 //! for y in 0 .. qr.size() {
78 //! for x in 0 .. qr.size() {
79 //! (... paint qr.get_module(x, y) ...)
85 /*---- QrCode functionality ----*/
87 /// A QR Code symbol, which is a type of two-dimension barcode.
89 /// Invented by Denso Wave and described in the ISO/IEC 18004 standard.
91 /// Instances of this struct represent an immutable square grid of black and white cells.
92 /// The impl provides static factory functions to create a QR Code from text or binary data.
93 /// The struct and impl cover the QR Code Model 2 specification, supporting all versions
94 /// (sizes) from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
96 /// Ways to create a QR Code object:
98 /// - High level: Take the payload data and call `QrCode::encode_text()` or `QrCode::encode_binary()`.
99 /// - Mid level: Custom-make the list of segments and call
100 /// `QrCode::encode_segments()` or `QrCode::encode_segments_advanced()`.
101 /// - Low level: Custom-make the array of data codeword bytes (including segment
102 /// headers and final padding, excluding error correction codewords), supply the
103 /// appropriate version number, and call the `QrCode::encode_codewords()` constructor.
105 /// (Note that all ways require supplying the desired error correction level.)
106 #[derive(Clone, PartialEq, Eq)]
109 // Scalar parameters:
111 // The version number of this QR Code, which is between 1 and 40 (inclusive).
112 // This determines the size of this barcode.
115 // The width and height of this QR Code, measured in modules, between
116 // 21 and 177 (inclusive). This is equal to version * 4 + 17.
119 // The error correction level used in this QR Code.
120 errorcorrectionlevel: QrCodeEcc,
122 // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
123 // Even if a QR Code is created with automatic masking requested (mask = None),
124 // the resulting object still has a mask value between 0 and 7.
127 // Grids of modules/pixels, with dimensions of size*size:
129 // The modules of this QR Code (false = white, true = black).
130 // Immutable after constructor finishes. Accessed through get_module().
133 // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
134 isfunction: Vec<bool>,
141 /*---- Static factory functions (high level) ----*/
143 /// Returns a QR Code representing the given Unicode text string at the given error correction level.
145 /// As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer Unicode
146 /// code points (not UTF-8 code units) if the low error correction level is used. The smallest possible
147 /// QR Code version is automatically chosen for the output. The ECC level of the result may be higher than
148 /// the ecl argument if it can be done without increasing the version.
150 /// Returns a wrapped `QrCode` if successful, or `Err` if the
151 /// data is too long to fit in any version at the given ECC level.
152 pub fn encode_text(text: &str, ecl: QrCodeEcc) -> Result<Self,DataTooLong> {
153 let chrs: Vec<char> = text.chars().collect();
154 let segs: Vec<QrSegment> = QrSegment::make_segments(&chrs);
155 QrCode::encode_segments(&segs, ecl)
159 /// Returns a QR Code representing the given binary data at the given error correction level.
161 /// This function always encodes using the binary segment mode, not any text mode. The maximum number of
162 /// bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
163 /// The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
165 /// Returns a wrapped `QrCode` if successful, or `Err` if the
166 /// data is too long to fit in any version at the given ECC level.
167 pub fn encode_binary(data: &[u8], ecl: QrCodeEcc) -> Result<Self,DataTooLong> {
168 let segs: [QrSegment; 1] = [QrSegment::make_bytes(data)];
169 QrCode::encode_segments(&segs, ecl)
173 /*---- Static factory functions (mid level) ----*/
175 /// Returns a QR Code representing the given segments at the given error correction level.
177 /// The smallest possible QR Code version is automatically chosen for the output. The ECC level
178 /// of the result may be higher than the ecl argument if it can be done without increasing the version.
180 /// This function allows the user to create a custom sequence of segments that switches
181 /// between modes (such as alphanumeric and byte) to encode text in less space.
182 /// This is a mid-level API; the high-level API is `encode_text()` and `encode_binary()`.
184 /// Returns a wrapped `QrCode` if successful, or `Err` if the
185 /// data is too long to fit in any version at the given ECC level.
186 pub fn encode_segments(segs: &[QrSegment], ecl: QrCodeEcc) -> Result<Self,DataTooLong> {
187 QrCode::encode_segments_advanced(segs, ecl, Version::MIN, Version::MAX, None, true)
191 /// Returns a QR Code representing the given segments with the given encoding parameters.
193 /// The smallest possible QR Code version within the given range is automatically
194 /// chosen for the output. Iff boostecl is `true`, then the ECC level of the result
195 /// may be higher than the ecl argument if it can be done without increasing the
196 /// version. The mask number is either between 0 to 7 (inclusive) to force that
197 /// mask, or `None` to automatically choose an appropriate mask (which may be slow).
199 /// This function allows the user to create a custom sequence of segments that switches
200 /// between modes (such as alphanumeric and byte) to encode text in less space.
201 /// This is a mid-level API; the high-level API is `encode_text()` and `encode_binary()`.
203 /// Returns a wrapped `QrCode` if successful, or `Err` if the data is too
204 /// long to fit in any version in the given range at the given ECC level.
205 pub fn encode_segments_advanced(segs: &[QrSegment], mut ecl: QrCodeEcc,
206 minversion: Version, maxversion: Version, mask: Option<Mask>, boostecl: bool) -> Result<Self,DataTooLong> {
207 assert!(minversion.value() <= maxversion.value(), "Invalid value");
209 // Find the minimal version number to use
210 let mut version: Version = minversion;
211 let datausedbits: usize = loop {
212 // Number of data bits available
213 let datacapacitybits: usize = QrCode::get_num_data_codewords(version, ecl) * 8;
214 let dataused: Option<usize> = QrSegment::get_total_bits(segs, version);
215 if dataused.map_or(false, |n| n <= datacapacitybits) {
216 break dataused.unwrap(); // This version number is found to be suitable
217 } else if version.value() >= maxversion.value() { // All versions in the range could not fit the given data
218 let msg: String = match dataused {
219 None => String::from("Segment too long"),
220 Some(n) => format!("Data length = {} bits, Max capacity = {} bits",
221 n, datacapacitybits),
223 return Err(DataTooLong(msg));
225 version = Version::new(version.value() + 1);
229 // Increase the error correction level while the data still fits in the current version number
230 for &newecl in &[QrCodeEcc::Medium, QrCodeEcc::Quartile, QrCodeEcc::High] { // From low to high
231 if boostecl && datausedbits <= QrCode::get_num_data_codewords(version, newecl) * 8 {
236 // Concatenate all segments to create the data bit string
237 let mut bb = BitBuffer(Vec::new());
239 bb.append_bits(seg.mode.mode_bits(), 4);
240 bb.append_bits(seg.numchars as u32, seg.mode.num_char_count_bits(version));
241 bb.0.extend_from_slice(&seg.data);
243 assert_eq!(bb.0.len(), datausedbits);
245 // Add terminator and pad up to a byte if applicable
246 let datacapacitybits: usize = QrCode::get_num_data_codewords(version, ecl) * 8;
247 assert!(bb.0.len() <= datacapacitybits);
248 let numzerobits: usize = std::cmp::min(4, datacapacitybits - bb.0.len());
249 bb.append_bits(0, numzerobits as u8);
250 let numzerobits: usize = bb.0.len().wrapping_neg() & 7;
251 bb.append_bits(0, numzerobits as u8);
252 assert_eq!(bb.0.len() % 8, 0, "Assertion error");
254 // Pad with alternating bytes until data capacity is reached
255 for &padbyte in [0xEC, 0x11].iter().cycle() {
256 if bb.0.len() >= datacapacitybits {
259 bb.append_bits(padbyte, 8);
262 // Pack bits into bytes in big endian
263 let mut datacodewords = vec![0u8; bb.0.len() / 8];
264 for (i, &bit) in bb.0.iter().enumerate() {
265 datacodewords[i >> 3] |= u8::from(bit) << (7 - (i & 7));
268 // Create the QR Code object
269 Ok(QrCode::encode_codewords(version, ecl, &datacodewords, mask))
273 /*---- Constructor (low level) ----*/
275 /// Creates a new QR Code with the given version number,
276 /// error correction level, data codeword bytes, and mask number.
278 /// This is a low-level API that most users should not use directly.
279 /// A mid-level API is the `encode_segments()` function.
280 pub fn encode_codewords(ver: Version, ecl: QrCodeEcc, datacodewords: &[u8], mut mask: Option<Mask>) -> Self {
282 let size = usize::from(ver.value()) * 4 + 17;
283 let mut result = Self {
286 mask: Mask::new(0), // Dummy value
287 errorcorrectionlevel: ecl,
288 modules : vec![false; size * size], // Initially all white
289 isfunction: vec![false; size * size],
292 // Compute ECC, draw modules
293 result.draw_function_patterns();
294 let allcodewords: Vec<u8> = result.add_ecc_and_interleave(datacodewords);
295 result.draw_codewords(&allcodewords);
298 if mask.is_none() { // Automatically choose best mask
299 let mut minpenalty = std::i32::MAX;
301 let newmask = Mask::new(i);
302 result.apply_mask(newmask);
303 result.draw_format_bits(newmask);
304 let penalty: i32 = result.get_penalty_score();
305 if penalty < minpenalty {
306 mask = Some(newmask);
307 minpenalty = penalty;
309 result.apply_mask(newmask); // Undoes the mask due to XOR
312 let mask: Mask = mask.unwrap();
314 result.apply_mask(mask); // Apply the final choice of mask
315 result.draw_format_bits(mask); // Overwrite old format bits
317 result.isfunction.clear();
318 result.isfunction.shrink_to_fit();
323 /*---- Public methods ----*/
325 /// Returns this QR Code's version, in the range [1, 40].
326 pub fn version(&self) -> Version {
331 /// Returns this QR Code's size, in the range [21, 177].
332 pub fn size(&self) -> i32 {
337 /// Returns this QR Code's error correction level.
338 pub fn error_correction_level(&self) -> QrCodeEcc {
339 self.errorcorrectionlevel
343 /// Returns this QR Code's mask, in the range [0, 7].
344 pub fn mask(&self) -> Mask {
349 /// Returns the color of the module (pixel) at the given coordinates,
350 /// which is `false` for white or `true` for black.
352 /// The top left corner has the coordinates (x=0, y=0). If the given
353 /// coordinates are out of bounds, then `false` (white) is returned.
354 pub fn get_module(&self, x: i32, y: i32) -> bool {
355 0 <= x && x < self.size && 0 <= y && y < self.size && self.module(x, y)
359 // Returns the color of the module at the given coordinates, which must be in bounds.
360 fn module(&self, x: i32, y: i32) -> bool {
361 self.modules[(y * self.size + x) as usize]
365 // Returns a mutable reference to the module's color at the given coordinates, which must be in bounds.
366 fn module_mut(&mut self, x: i32, y: i32) -> &mut bool {
367 &mut self.modules[(y * self.size + x) as usize]
371 /// Returns a string of SVG code for an image depicting
372 /// this QR Code, with the given number of border modules.
374 /// The string always uses Unix newlines (\n), regardless of the platform.
375 pub fn to_svg_string(&self, border: i32) -> String {
376 assert!(border >= 0, "Border must be non-negative");
377 let mut result = String::new();
378 result += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
379 result += "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
380 let dimension = self.size.checked_add(border.checked_mul(2).unwrap()).unwrap();
382 "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 {0} {0}\" stroke=\"none\">\n", dimension);
383 result += "\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n";
384 result += "\t<path d=\"";
385 for y in 0 .. self.size {
386 for x in 0 .. self.size {
387 if self.get_module(x, y) {
388 if x != 0 || y != 0 {
391 result += &format!("M{},{}h1v1h-1z", x + border, y + border);
395 result += "\" fill=\"#000000\"/>\n";
396 result += "</svg>\n";
401 /*---- Private helper methods for constructor: Drawing function modules ----*/
403 // Reads this object's version field, and draws and marks all function modules.
404 fn draw_function_patterns(&mut self) {
405 // Draw horizontal and vertical timing patterns
406 let size: i32 = self.size;
408 self.set_function_module(6, i, i % 2 == 0);
409 self.set_function_module(i, 6, i % 2 == 0);
412 // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
413 self.draw_finder_pattern(3, 3);
414 self.draw_finder_pattern(size - 4, 3);
415 self.draw_finder_pattern(3, size - 4);
417 // Draw numerous alignment patterns
418 let alignpatpos: Vec<i32> = self.get_alignment_pattern_positions();
419 let numalign: usize = alignpatpos.len();
420 for i in 0 .. numalign {
421 for j in 0 .. numalign {
422 // Don't draw on the three finder corners
423 if !(i == 0 && j == 0 || i == 0 && j == numalign - 1 || i == numalign - 1 && j == 0) {
424 self.draw_alignment_pattern(alignpatpos[i], alignpatpos[j]);
429 // Draw configuration data
430 self.draw_format_bits(Mask::new(0)); // Dummy mask value; overwritten later in the constructor
435 // Draws two copies of the format bits (with its own error correction code)
436 // based on the given mask and this object's error correction level field.
437 fn draw_format_bits(&mut self, mask: Mask) {
438 // Calculate error correction code and pack bits
440 // errcorrlvl is uint2, mask is uint3
441 let data: u32 = u32::from(self.errorcorrectionlevel.format_bits() << 3 | mask.value());
442 let mut rem: u32 = data;
444 rem = (rem << 1) ^ ((rem >> 9) * 0x537);
446 (data << 10 | rem) ^ 0x5412 // uint15
448 assert_eq!(bits >> 15, 0, "Assertion error");
452 self.set_function_module(8, i, get_bit(bits, i));
454 self.set_function_module(8, 7, get_bit(bits, 6));
455 self.set_function_module(8, 8, get_bit(bits, 7));
456 self.set_function_module(7, 8, get_bit(bits, 8));
458 self.set_function_module(14 - i, 8, get_bit(bits, i));
462 let size: i32 = self.size;
464 self.set_function_module(size - 1 - i, 8, get_bit(bits, i));
467 self.set_function_module(8, size - 15 + i, get_bit(bits, i));
469 self.set_function_module(8, size - 8, true); // Always black
473 // Draws two copies of the version bits (with its own error correction code),
474 // based on this object's version field, iff 7 <= version <= 40.
475 fn draw_version(&mut self) {
476 if self.version.value() < 7 {
480 // Calculate error correction code and pack bits
482 let data = u32::from(self.version.value()); // uint6, in the range [7, 40]
483 let mut rem: u32 = data;
485 rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
487 data << 12 | rem // uint18
489 assert!(bits >> 18 == 0, "Assertion error");
493 let bit: bool = get_bit(bits, i);
494 let a: i32 = self.size - 11 + i % 3;
496 self.set_function_module(a, b, bit);
497 self.set_function_module(b, a, bit);
502 // Draws a 9*9 finder pattern including the border separator,
503 // with the center module at (x, y). Modules can be out of bounds.
504 fn draw_finder_pattern(&mut self, x: i32, y: i32) {
507 let xx: i32 = x + dx;
508 let yy: i32 = y + dy;
509 if 0 <= xx && xx < self.size && 0 <= yy && yy < self.size {
510 let dist: i32 = std::cmp::max(dx.abs(), dy.abs()); // Chebyshev/infinity norm
511 self.set_function_module(xx, yy, dist != 2 && dist != 4);
518 // Draws a 5*5 alignment pattern, with the center module
519 // at (x, y). All modules must be in bounds.
520 fn draw_alignment_pattern(&mut self, x: i32, y: i32) {
523 self.set_function_module(x + dx, y + dy, std::cmp::max(dx.abs(), dy.abs()) != 1);
529 // Sets the color of a module and marks it as a function module.
530 // Only used by the constructor. Coordinates must be in bounds.
531 fn set_function_module(&mut self, x: i32, y: i32, isblack: bool) {
532 *self.module_mut(x, y) = isblack;
533 self.isfunction[(y * self.size + x) as usize] = true;
537 /*---- Private helper methods for constructor: Codewords and masking ----*/
539 // Returns a new byte string representing the given data with the appropriate error correction
540 // codewords appended to it, based on this object's version and error correction level.
541 fn add_ecc_and_interleave(&self, data: &[u8]) -> Vec<u8> {
542 let ver: Version = self.version;
543 let ecl: QrCodeEcc = self.errorcorrectionlevel;
544 assert_eq!(data.len(), QrCode::get_num_data_codewords(ver, ecl), "Illegal argument");
546 // Calculate parameter numbers
547 let numblocks: usize = QrCode::table_get(&NUM_ERROR_CORRECTION_BLOCKS, ver, ecl);
548 let blockecclen: usize = QrCode::table_get(&ECC_CODEWORDS_PER_BLOCK , ver, ecl);
549 let rawcodewords: usize = QrCode::get_num_raw_data_modules(ver) / 8;
550 let numshortblocks: usize = numblocks - rawcodewords % numblocks;
551 let shortblocklen: usize = rawcodewords / numblocks;
553 // Split data into blocks and append ECC to each block
554 let mut blocks = Vec::<Vec<u8>>::with_capacity(numblocks);
555 let rsdiv: Vec<u8> = QrCode::reed_solomon_compute_divisor(blockecclen);
556 let mut k: usize = 0;
557 for i in 0 .. numblocks {
558 let datlen: usize = shortblocklen - blockecclen + usize::from(i >= numshortblocks);
559 let mut dat = data[k .. k + datlen].to_vec();
561 let ecc: Vec<u8> = QrCode::reed_solomon_compute_remainder(&dat, &rsdiv);
562 if i < numshortblocks {
565 dat.extend_from_slice(&ecc);
569 // Interleave (not concatenate) the bytes from every block into a single sequence
570 let mut result = Vec::<u8>::with_capacity(rawcodewords);
571 for i in 0 ..= shortblocklen {
572 for (j, block) in blocks.iter().enumerate() {
573 // Skip the padding byte in short blocks
574 if i != shortblocklen - blockecclen || j >= numshortblocks {
575 result.push(block[i]);
583 // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
584 // data area of this QR Code. Function modules need to be marked off before this is called.
585 fn draw_codewords(&mut self, data: &[u8]) {
586 assert_eq!(data.len(), QrCode::get_num_raw_data_modules(self.version) / 8, "Illegal argument");
588 let mut i: usize = 0; // Bit index into the data
589 // Do the funny zigzag scan
590 let mut right: i32 = self.size - 1;
591 while right >= 1 { // Index of right column in each column pair
595 for vert in 0 .. self.size { // Vertical counter
597 let x: i32 = right - j; // Actual x coordinate
598 let upward: bool = (right + 1) & 2 == 0;
599 let y: i32 = if upward { self.size - 1 - vert } else { vert }; // Actual y coordinate
600 if !self.isfunction[(y * self.size + x) as usize] && i < data.len() * 8 {
601 *self.module_mut(x, y) = get_bit(u32::from(data[i >> 3]), 7 - ((i & 7) as i32));
604 // If this QR Code has any remainder bits (0 to 7), they were assigned as
605 // 0/false/white by the constructor and are left unchanged by this method
610 assert_eq!(i, data.len() * 8, "Assertion error");
614 // XORs the codeword modules in this QR Code with the given mask pattern.
615 // The function modules must be marked and the codeword bits must be drawn
616 // before masking. Due to the arithmetic of XOR, calling apply_mask() with
617 // the same mask value a second time will undo the mask. A final well-formed
618 // QR Code needs exactly one (not zero, two, etc.) mask applied.
619 fn apply_mask(&mut self, mask: Mask) {
620 for y in 0 .. self.size {
621 for x in 0 .. self.size {
622 let invert: bool = match mask.value() {
623 0 => (x + y) % 2 == 0,
626 3 => (x + y) % 3 == 0,
627 4 => (x / 3 + y / 2) % 2 == 0,
628 5 => x * y % 2 + x * y % 3 == 0,
629 6 => (x * y % 2 + x * y % 3) % 2 == 0,
630 7 => ((x + y) % 2 + x * y % 3) % 2 == 0,
633 *self.module_mut(x, y) ^= invert & !self.isfunction[(y * self.size + x) as usize];
639 // Calculates and returns the penalty score based on state of this QR Code's current modules.
640 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
641 fn get_penalty_score(&self) -> i32 {
642 let mut result: i32 = 0;
643 let size: i32 = self.size;
645 // Adjacent modules in row having same color, and finder-like patterns
647 let mut runcolor = false;
648 let mut runx: i32 = 0;
649 let mut runhistory = FinderPenalty::new(size);
651 if self.module(x, y) == runcolor {
654 result += PENALTY_N1;
659 runhistory.add_history(runx);
661 result += runhistory.count_patterns() * PENALTY_N3;
663 runcolor = self.module(x, y);
667 result += runhistory.terminate_and_count(runcolor, runx) * PENALTY_N3;
669 // Adjacent modules in column having same color, and finder-like patterns
671 let mut runcolor = false;
672 let mut runy: i32 = 0;
673 let mut runhistory = FinderPenalty::new(size);
675 if self.module(x, y) == runcolor {
678 result += PENALTY_N1;
683 runhistory.add_history(runy);
685 result += runhistory.count_patterns() * PENALTY_N3;
687 runcolor = self.module(x, y);
691 result += runhistory.terminate_and_count(runcolor, runy) * PENALTY_N3;
694 // 2*2 blocks of modules having same color
695 for y in 0 .. size - 1 {
696 for x in 0 .. size - 1 {
697 let color: bool = self.module(x, y);
698 if color == self.module(x + 1, y) &&
699 color == self.module(x, y + 1) &&
700 color == self.module(x + 1, y + 1) {
701 result += PENALTY_N2;
706 // Balance of black and white modules
707 let black: i32 = self.modules.iter().copied().map(i32::from).sum();
708 let total: i32 = size * size; // Note that size is odd, so black/total != 1/2
709 // Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
710 let k: i32 = ((black * 20 - total * 10).abs() + total - 1) / total - 1;
711 result += k * PENALTY_N4;
716 /*---- Private helper functions ----*/
718 // Returns an ascending list of positions of alignment patterns for this version number.
719 // Each position is in the range [0,177), and are used on both the x and y axes.
720 // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
721 fn get_alignment_pattern_positions(&self) -> Vec<i32> {
722 let ver: u8 = self.version.value();
726 let numalign = i32::from(ver) / 7 + 2;
727 let step: i32 = if ver == 32 { 26 } else
728 {(i32::from(ver)*4 + numalign*2 + 1) / (numalign*2 - 2) * 2};
729 let mut result: Vec<i32> = (0 .. numalign - 1).map(
730 |i| self.size - 7 - i * step).collect();
738 // Returns the number of data bits that can be stored in a QR Code of the given version number, after
739 // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
740 // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
741 fn get_num_raw_data_modules(ver: Version) -> usize {
742 let ver = usize::from(ver.value());
743 let mut result: usize = (16 * ver + 128) * ver + 64;
745 let numalign: usize = ver / 7 + 2;
746 result -= (25 * numalign - 10) * numalign - 55;
751 assert!(208 <= result && result <= 29648);
756 // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
757 // QR Code of the given version number and error correction level, with remainder bits discarded.
758 // This stateless pure function could be implemented as a (40*4)-cell lookup table.
759 fn get_num_data_codewords(ver: Version, ecl: QrCodeEcc) -> usize {
760 QrCode::get_num_raw_data_modules(ver) / 8
761 - QrCode::table_get(&ECC_CODEWORDS_PER_BLOCK , ver, ecl)
762 * QrCode::table_get(&NUM_ERROR_CORRECTION_BLOCKS, ver, ecl)
766 // Returns an entry from the given table based on the given values.
767 fn table_get(table: &'static [[i8; 41]; 4], ver: Version, ecl: QrCodeEcc) -> usize {
768 table[ecl.ordinal()][usize::from(ver.value())] as usize
772 // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
773 // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
774 fn reed_solomon_compute_divisor(degree: usize) -> Vec<u8> {
775 assert!(1 <= degree && degree <= 255, "Degree out of range");
776 // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
777 // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
778 let mut result = vec![0u8; degree - 1];
779 result.push(1); // Start off with the monomial x^0
781 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
782 // and drop the highest monomial term which is always 1x^degree.
783 // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
784 let mut root: u8 = 1;
785 for _ in 0 .. degree { // Unused variable i
786 // Multiply the current product by (x - r^i)
787 for j in 0 .. degree {
788 result[j] = QrCode::reed_solomon_multiply(result[j], root);
789 if j + 1 < result.len() {
790 result[j] ^= result[j + 1];
793 root = QrCode::reed_solomon_multiply(root, 0x02);
799 // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
800 fn reed_solomon_compute_remainder(data: &[u8], divisor: &[u8]) -> Vec<u8> {
801 let mut result = vec![0u8; divisor.len()];
802 for b in data { // Polynomial division
803 let factor: u8 = b ^ result.remove(0);
805 for (x, &y) in result.iter_mut().zip(divisor.iter()) {
806 *x ^= QrCode::reed_solomon_multiply(y, factor);
813 // Returns the product of the two given field elements modulo GF(2^8/0x11D).
814 // All inputs are valid. This could be implemented as a 256*256 lookup table.
815 fn reed_solomon_multiply(x: u8, y: u8) -> u8 {
816 // Russian peasant multiplication
818 for i in (0 .. 8).rev() {
819 z = (z << 1) ^ ((z >> 7) * 0x1D);
820 z ^= ((y >> i) & 1) * x;
828 /*---- Helper struct for get_penalty_score() ----*/
830 struct FinderPenalty {
832 run_history: [i32; 7],
838 pub fn new(size: i32) -> Self {
841 run_history: [0i32; 7],
846 // Pushes the given value to the front and drops the last value.
847 pub fn add_history(&mut self, mut currentrunlength: i32) {
848 if self.run_history[0] == 0 {
849 currentrunlength += self.qr_size; // Add white border to initial run
851 let rh = &mut self.run_history;
852 for i in (0 .. rh.len()-1).rev() {
855 rh[0] = currentrunlength;
859 // Can only be called immediately after a white run is added, and returns either 0, 1, or 2.
860 pub fn count_patterns(&self) -> i32 {
861 let rh = &self.run_history;
863 assert!(n <= self.qr_size * 3);
864 let core = n > 0 && rh[2] == n && rh[3] == n * 3 && rh[4] == n && rh[5] == n;
865 ( i32::from(core && rh[0] >= n * 4 && rh[6] >= n)
866 + i32::from(core && rh[6] >= n * 4 && rh[0] >= n))
870 // Must be called at the end of a line (row or column) of modules.
871 pub fn terminate_and_count(mut self, currentruncolor: bool, mut currentrunlength: i32) -> i32 {
872 if currentruncolor { // Terminate black run
873 self.add_history(currentrunlength);
874 currentrunlength = 0;
876 currentrunlength += self.qr_size; // Add white border to final run
877 self.add_history(currentrunlength);
878 self.count_patterns()
884 /*---- Constants and tables ----*/
886 // For use in get_penalty_score(), when evaluating which mask is best.
887 const PENALTY_N1: i32 = 3;
888 const PENALTY_N2: i32 = 3;
889 const PENALTY_N3: i32 = 40;
890 const PENALTY_N4: i32 = 10;
893 static ECC_CODEWORDS_PER_BLOCK: [[i8; 41]; 4] = [
894 // Version: (note that index 0 is for padding, and is set to an illegal value)
895 //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
896 [-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
897 [-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
898 [-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
899 [-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
902 static NUM_ERROR_CORRECTION_BLOCKS: [[i8; 41]; 4] = [
903 // Version: (note that index 0 is for padding, and is set to an illegal value)
904 //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
905 [-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
906 [-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
907 [-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
908 [-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
913 /*---- QrCodeEcc functionality ----*/
915 /// The error correction level in a QR Code symbol.
916 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
918 /// The QR Code can tolerate about 7% erroneous codewords.
920 /// The QR Code can tolerate about 15% erroneous codewords.
922 /// The QR Code can tolerate about 25% erroneous codewords.
924 /// The QR Code can tolerate about 30% erroneous codewords.
931 // Returns an unsigned 2-bit integer (in the range 0 to 3).
932 fn ordinal(self) -> usize {
943 // Returns an unsigned 2-bit integer (in the range 0 to 3).
944 fn format_bits(self) -> u8 {
958 /*---- QrSegment functionality ----*/
960 /// A segment of character/binary/control data in a QR Code symbol.
962 /// Instances of this struct are immutable.
964 /// The mid-level way to create a segment is to take the payload data
965 /// and call a static factory function such as `QrSegment::make_numeric()`.
966 /// The low-level way to create a segment is to custom-make the bit buffer
967 /// and call the `QrSegment::new()` constructor with appropriate values.
969 /// This segment struct imposes no length restrictions, but QR Codes have restrictions.
970 /// Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
971 /// Any segment longer than this is meaningless for the purpose of generating QR Codes.
972 #[derive(Clone, PartialEq, Eq)]
973 pub struct QrSegment {
975 // The mode indicator of this segment. Accessed through mode().
978 // The length of this segment's unencoded data. Measured in characters for
979 // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
980 // Not the same as the data's bit length. Accessed through num_chars().
983 // The data bits of this segment. Accessed through data().
991 /*---- Static factory functions (mid level) ----*/
993 /// Returns a segment representing the given binary data encoded in byte mode.
995 /// All input byte slices are acceptable.
997 /// Any text string can be converted to UTF-8 bytes and encoded as a byte mode segment.
998 pub fn make_bytes(data: &[u8]) -> Self {
999 let mut bb = BitBuffer(Vec::with_capacity(data.len() * 8));
1001 bb.append_bits(u32::from(b), 8);
1003 QrSegment::new(QrSegmentMode::Byte, data.len(), bb.0)
1007 /// Returns a segment representing the given string of decimal digits encoded in numeric mode.
1009 /// Panics if the string contains non-digit characters.
1010 pub fn make_numeric(text: &[char]) -> Self {
1011 let mut bb = BitBuffer(Vec::with_capacity(text.len() * 3 + (text.len() + 2) / 3));
1012 let mut accumdata: u32 = 0;
1013 let mut accumcount: u8 = 0;
1015 assert!('0' <= c && c <= '9', "String contains non-numeric characters");
1016 accumdata = accumdata * 10 + (u32::from(c) - u32::from('0'));
1018 if accumcount == 3 {
1019 bb.append_bits(accumdata, 10);
1024 if accumcount > 0 { // 1 or 2 digits remaining
1025 bb.append_bits(accumdata, accumcount * 3 + 1);
1027 QrSegment::new(QrSegmentMode::Numeric, text.len(), bb.0)
1031 /// Returns a segment representing the given text string encoded in alphanumeric mode.
1033 /// The characters allowed are: 0 to 9, A to Z (uppercase only), space,
1034 /// dollar, percent, asterisk, plus, hyphen, period, slash, colon.
1036 /// Panics if the string contains non-encodable characters.
1037 pub fn make_alphanumeric(text: &[char]) -> Self {
1038 let mut bb = BitBuffer(Vec::with_capacity(text.len() * 5 + (text.len() + 1) / 2));
1039 let mut accumdata: u32 = 0;
1040 let mut accumcount: u32 = 0;
1042 let i: usize = ALPHANUMERIC_CHARSET.iter().position(|&x| x == c)
1043 .expect("String contains unencodable characters in alphanumeric mode");
1044 accumdata = accumdata * 45 + (i as u32);
1046 if accumcount == 2 {
1047 bb.append_bits(accumdata, 11);
1052 if accumcount > 0 { // 1 character remaining
1053 bb.append_bits(accumdata, 6);
1055 QrSegment::new(QrSegmentMode::Alphanumeric, text.len(), bb.0)
1059 /// Returns a list of zero or more segments to represent the given Unicode text string.
1061 /// The result may use various segment modes and switch
1062 /// modes to optimize the length of the bit stream.
1063 pub fn make_segments(text: &[char]) -> Vec<Self> {
1064 if text.is_empty() {
1066 } else if QrSegment::is_numeric(text) {
1067 vec![QrSegment::make_numeric(text)]
1068 } else if QrSegment::is_alphanumeric(text) {
1069 vec![QrSegment::make_alphanumeric(text)]
1071 let s: String = text.iter().cloned().collect();
1072 vec![QrSegment::make_bytes(s.as_bytes())]
1077 /// Returns a segment representing an Extended Channel Interpretation
1078 /// (ECI) designator with the given assignment value.
1079 pub fn make_eci(assignval: u32) -> Self {
1080 let mut bb = BitBuffer(Vec::with_capacity(24));
1081 if assignval < (1 << 7) {
1082 bb.append_bits(assignval, 8);
1083 } else if assignval < (1 << 14) {
1084 bb.append_bits(2, 2);
1085 bb.append_bits(assignval, 14);
1086 } else if assignval < 1_000_000 {
1087 bb.append_bits(6, 3);
1088 bb.append_bits(assignval, 21);
1090 panic!("ECI assignment value out of range");
1092 QrSegment::new(QrSegmentMode::Eci, 0, bb.0)
1096 /*---- Constructor (low level) ----*/
1098 /// Creates a new QR Code segment with the given attributes and data.
1100 /// The character count (numchars) must agree with the mode and
1101 /// the bit buffer length, but the constraint isn't checked.
1102 pub fn new(mode: QrSegmentMode, numchars: usize, data: Vec<bool>) -> Self {
1103 Self { mode, numchars, data }
1107 /*---- Instance field getters ----*/
1109 /// Returns the mode indicator of this segment.
1110 pub fn mode(&self) -> QrSegmentMode {
1115 /// Returns the character count field of this segment.
1116 pub fn num_chars(&self) -> usize {
1121 /// Returns the data bits of this segment.
1122 pub fn data(&self) -> &Vec<bool> {
1127 /*---- Other static functions ----*/
1129 // Calculates and returns the number of bits needed to encode the given
1130 // segments at the given version. The result is None if a segment has too many
1131 // characters to fit its length field, or the total bits exceeds usize::MAX.
1132 fn get_total_bits(segs: &[Self], version: Version) -> Option<usize> {
1133 let mut result: usize = 0;
1135 let ccbits: u8 = seg.mode.num_char_count_bits(version);
1136 // ccbits can be as large as 16, but usize can be as small as 16
1137 if let Some(limit) = 1usize.checked_shl(u32::from(ccbits)) {
1138 if seg.numchars >= limit {
1139 return None; // The segment's length doesn't fit the field's bit width
1142 result = result.checked_add(4 + usize::from(ccbits))?;
1143 result = result.checked_add(seg.data.len())?;
1149 // Tests whether the given string can be encoded as a segment in alphanumeric mode.
1150 // A string is encodable iff each character is in the following set: 0 to 9, A to Z
1151 // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
1152 fn is_alphanumeric(text: &[char]) -> bool {
1153 text.iter().all(|c| ALPHANUMERIC_CHARSET.contains(c))
1157 // Tests whether the given string can be encoded as a segment in numeric mode.
1158 // A string is encodable iff each character is in the range 0 to 9.
1159 fn is_numeric(text: &[char]) -> bool {
1160 text.iter().all(|&c| '0' <= c && c <= '9')
1166 // The set of all legal characters in alphanumeric mode,
1167 // where each character value maps to the index in the string.
1168 static ALPHANUMERIC_CHARSET: [char; 45] = ['0','1','2','3','4','5','6','7','8','9',
1169 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
1170 ' ','$','%','*','+','-','.','/',':'];
1174 /*---- QrSegmentMode functionality ----*/
1176 /// Describes how a segment's data bits are interpreted.
1177 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
1178 pub enum QrSegmentMode {
1187 impl QrSegmentMode {
1189 // Returns an unsigned 4-bit integer value (range 0 to 15)
1190 // representing the mode indicator bits for this mode object.
1191 fn mode_bits(self) -> u32 {
1192 use QrSegmentMode::*;
1195 Alphanumeric => 0x2,
1203 // Returns the bit width of the character count field for a segment in this mode
1204 // in a QR Code at the given version number. The result is in the range [0, 16].
1205 fn num_char_count_bits(self, ver: Version) -> u8 {
1206 use QrSegmentMode::*;
1208 Numeric => [10, 12, 14],
1209 Alphanumeric => [ 9, 11, 13],
1210 Byte => [ 8, 16, 16],
1211 Kanji => [ 8, 10, 12],
1213 })[usize::from((ver.value() + 7) / 17)]
1220 /*---- Bit buffer functionality ----*/
1222 /// An appendable sequence of bits (0s and 1s).
1224 /// Mainly used by QrSegment.
1225 pub struct BitBuffer(pub Vec<bool>);
1229 /// Appends the given number of low-order bits of the given value to this buffer.
1231 /// Requires len ≤ 31 and val < 2<sup>len</sup>.
1232 pub fn append_bits(&mut self, val: u32, len: u8) {
1233 assert!(len <= 31 && (val >> len) == 0, "Value out of range");
1234 self.0.extend((0 .. i32::from(len)).rev().map(|i| get_bit(val, i))); // Append bit by bit
1240 /*---- Miscellaneous values ----*/
1242 /// The error type when the supplied data does not fit any QR Code version.
1244 /// Ways to handle this exception include:
1246 /// - Decrease the error correction level if it was greater than `QrCodeEcc::Low`.
1247 /// - If the `encode_segments_advanced()` function was called, then increase the maxversion
1248 /// argument if it was less than `Version::MAX`. (This advice does not apply to the
1249 /// other factory functions because they search all versions up to `Version::MAX`.)
1250 /// - Split the text data into better or optimal segments in order to reduce the number of bits required.
1251 /// - Change the text or binary data to be shorter.
1252 /// - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).
1253 /// - Propagate the error upward to the caller/user.
1254 #[derive(Debug, Clone)]
1255 pub struct DataTooLong(String);
1257 impl std::error::Error for DataTooLong {
1258 fn description(&self) -> &str {
1263 impl std::fmt::Display for DataTooLong {
1264 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1265 f.write_str(&self.0)
1270 /// A number between 1 and 40 (inclusive).
1271 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1272 pub struct Version(u8);
1275 /// The minimum version number supported in the QR Code Model 2 standard.
1276 pub const MIN: Version = Version( 1);
1278 /// The maximum version number supported in the QR Code Model 2 standard.
1279 pub const MAX: Version = Version(40);
1281 /// Creates a version object from the given number.
1283 /// Panics if the number is outside the range [1, 40].
1284 pub fn new(ver: u8) -> Self {
1285 assert!(Version::MIN.value() <= ver && ver <= Version::MAX.value(), "Version number out of range");
1289 /// Returns the value, which is in the range [1, 40].
1290 pub fn value(self) -> u8 {
1296 /// A number between 0 and 7 (inclusive).
1297 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1298 pub struct Mask(u8);
1301 /// Creates a mask object from the given number.
1303 /// Panics if the number is outside the range [0, 7].
1304 pub fn new(mask: u8) -> Self {
1305 assert!(mask <= 7, "Mask value out of range");
1309 /// Returns the value, which is in the range [0, 7].
1310 pub fn value(self) -> u8 {
1316 // Returns true iff the i'th bit of x is set to 1.
1317 fn get_bit(x: u32, i: i32) -> bool {