• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * QR Code generator library (Rust)
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 
25 //! Generates QR Codes from text strings and byte arrays.
26 //!
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.
30 //!
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)
33 //!
34 //! # Features
35 //!
36 //! Core features:
37 //!
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
45 //!
46 //! Manual parameters:
47 //!
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
52 //!
53 //! # Examples
54 //!
55 //! ```
56 //! extern crate qrcodegen;
57 //! use qrcodegen::QrCode;
58 //! use qrcodegen::QrCodeEcc;
59 //! use qrcodegen::QrSegment;
60 //! ```
61 //!
62 //! Simple operation:
63 //!
64 //! ```
65 //! let qr = QrCode::encode_text("Hello, world!",
66 //!     QrCodeEcc::Medium).unwrap();
67 //! let svg = qr.to_svg_string(4);
68 //! ```
69 //!
70 //! Manual operation:
71 //!
72 //! ```
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) ...)
80 //!     }
81 //! }
82 //! ```
83 
84 
85 /*---- QrCode functionality ----*/
86 
87 /// A QR Code symbol, which is a type of two-dimension barcode.
88 ///
89 /// Invented by Denso Wave and described in the ISO/IEC 18004 standard.
90 ///
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.
95 ///
96 /// Ways to create a QR Code object:
97 ///
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.
104 ///
105 /// (Note that all ways require supplying the desired error correction level.)
106 #[derive(Clone, PartialEq, Eq)]
107 pub struct QrCode {
108 
109 	// Scalar parameters:
110 
111 	// The version number of this QR Code, which is between 1 and 40 (inclusive).
112 	// This determines the size of this barcode.
113 	version: Version,
114 
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.
117 	size: i32,
118 
119 	// The error correction level used in this QR Code.
120 	errorcorrectionlevel: QrCodeEcc,
121 
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.
125 	mask: Mask,
126 
127 	// Grids of modules/pixels, with dimensions of size*size:
128 
129 	// The modules of this QR Code (false = white, true = black).
130 	// Immutable after constructor finishes. Accessed through get_module().
131 	modules: Vec<bool>,
132 
133 	// Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
134 	isfunction: Vec<bool>,
135 
136 }
137 
138 
139 impl QrCode {
140 
141 	/*---- Static factory functions (high level) ----*/
142 
143 	/// Returns a QR Code representing the given Unicode text string at the given error correction level.
144 	///
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.
149 	///
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.
encode_text(text: &str, ecl: QrCodeEcc) -> Result<Self,DataTooLong>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)
156 	}
157 
158 
159 	/// Returns a QR Code representing the given binary data at the given error correction level.
160 	///
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.
164 	///
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.
encode_binary(data: &[u8], ecl: QrCodeEcc) -> Result<Self,DataTooLong>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)
170 	}
171 
172 
173 	/*---- Static factory functions (mid level) ----*/
174 
175 	/// Returns a QR Code representing the given segments at the given error correction level.
176 	///
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.
179 	///
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()`.
183 	///
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.
encode_segments(segs: &[QrSegment], ecl: QrCodeEcc) -> Result<Self,DataTooLong>186 	pub fn encode_segments(segs: &[QrSegment], ecl: QrCodeEcc) -> Result<Self,DataTooLong> {
187 		QrCode::encode_segments_advanced(segs, ecl, QrCode_MIN_VERSION, QrCode_MAX_VERSION, None, true)
188 	}
189 
190 
191 	/// Returns a QR Code representing the given segments with the given encoding parameters.
192 	///
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).
198 	///
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()`.
202 	///
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.
encode_segments_advanced(segs: &[QrSegment], mut ecl: QrCodeEcc, minversion: Version, maxversion: Version, mask: Option<Mask>, boostecl: bool) -> Result<Self,DataTooLong>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");
208 
209 		// Find the minimal version number to use
210 		let mut 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),
222 				};
223 				return Err(DataTooLong(msg));
224 			} else {
225 				version = Version::new(version.value() + 1);
226 			}
227 		};
228 
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 {
232 				ecl = newecl;
233 			}
234 		}
235 
236 		// Concatenate all segments to create the data bit string
237 		let mut bb = BitBuffer(Vec::new());
238 		for seg in segs {
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);
242 		}
243 		assert_eq!(bb.0.len(), datausedbits);
244 
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 = std::cmp::min(4, datacapacitybits - bb.0.len());
249 		bb.append_bits(0, numzerobits as u8);
250 		let numzerobits = bb.0.len().wrapping_neg() & 7;
251 		bb.append_bits(0, numzerobits as u8);
252 		assert_eq!(bb.0.len() % 8, 0, "Assertion error");
253 
254 		// Pad with alternating bytes until data capacity is reached
255 		for &padbyte in [0xEC, 0x11].iter().cycle() {
256 			if bb.0.len() >= datacapacitybits {
257 				break;
258 			}
259 			bb.append_bits(padbyte, 8);
260 		}
261 
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));
266 		}
267 
268 		// Create the QR Code object
269 		Ok(QrCode::encode_codewords(version, ecl, &datacodewords, mask))
270 	}
271 
272 
273 	/*---- Constructor (low level) ----*/
274 
275 	/// Creates a new QR Code with the given version number,
276 	/// error correction level, data codeword bytes, and mask number.
277 	///
278 	/// This is a low-level API that most users should not use directly.
279 	/// A mid-level API is the `encode_segments()` function.
encode_codewords(ver: Version, ecl: QrCodeEcc, datacodewords: &[u8], mut mask: Option<Mask>) -> Self280 	pub fn encode_codewords(ver: Version, ecl: QrCodeEcc, datacodewords: &[u8], mut mask: Option<Mask>) -> Self {
281 		// Initialize fields
282 		let size = usize::from(ver.value()) * 4 + 17;
283 		let mut result = Self {
284 			version: ver,
285 			size: size as i32,
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],
290 		};
291 
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);
296 
297 		// Do masking
298 		if mask.is_none() {  // Automatically choose best mask
299 			let mut minpenalty: i32 = std::i32::MAX;
300 			for i in 0u8 .. 8 {
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;
308 				}
309 				result.apply_mask(newmask);  // Undoes the mask due to XOR
310 			}
311 		}
312 		let mask: Mask = mask.unwrap();
313 		result.mask = mask;
314 		result.apply_mask(mask);  // Apply the final choice of mask
315 		result.draw_format_bits(mask);  // Overwrite old format bits
316 
317 		result.isfunction.clear();
318 		result.isfunction.shrink_to_fit();
319 		result
320 	}
321 
322 
323 	/*---- Public methods ----*/
324 
325 	/// Returns this QR Code's version, in the range [1, 40].
version(&self) -> Version326 	pub fn version(&self) -> Version {
327 		self.version
328 	}
329 
330 
331 	/// Returns this QR Code's size, in the range [21, 177].
size(&self) -> i32332 	pub fn size(&self) -> i32 {
333 		self.size
334 	}
335 
336 
337 	/// Returns this QR Code's error correction level.
error_correction_level(&self) -> QrCodeEcc338 	pub fn error_correction_level(&self) -> QrCodeEcc {
339 		self.errorcorrectionlevel
340 	}
341 
342 
343 	/// Returns this QR Code's mask, in the range [0, 7].
mask(&self) -> Mask344 	pub fn mask(&self) -> Mask {
345 		self.mask
346 	}
347 
348 
349 	/// Returns the color of the module (pixel) at the given coordinates,
350 	/// which is `false` for white or `true` for black.
351 	///
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.
get_module(&self, x: i32, y: i32) -> bool354 	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)
356 	}
357 
358 
359 	// Returns the color of the module at the given coordinates, which must be in bounds.
module(&self, x: i32, y: i32) -> bool360 	fn module(&self, x: i32, y: i32) -> bool {
361 		self.modules[(y * self.size + x) as usize]
362 	}
363 
364 
365 	// Returns a mutable reference to the module's color at the given coordinates, which must be in bounds.
module_mut(&mut self, x: i32, y: i32) -> &mut bool366 	fn module_mut(&mut self, x: i32, y: i32) -> &mut bool {
367 		&mut self.modules[(y * self.size + x) as usize]
368 	}
369 
370 
371 	/// Returns a string of SVG code for an image depicting
372 	/// this QR Code, with the given number of border modules.
373 	///
374 	/// The string always uses Unix newlines (\n), regardless of the platform.
to_svg_string(&self, border: i32) -> String375 	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();
381 		result += &format!(
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 {
389 						result += " ";
390 					}
391 					result += &format!("M{},{}h1v1h-1z", x + border, y + border);
392 				}
393 			}
394 		}
395 		result += "\" fill=\"#000000\"/>\n";
396 		result += "</svg>\n";
397 		result
398 	}
399 
400 
401 	/*---- Private helper methods for constructor: Drawing function modules ----*/
402 
403 	// Reads this object's version field, and draws and marks all function modules.
draw_function_patterns(&mut self)404 	fn draw_function_patterns(&mut self) {
405 		// Draw horizontal and vertical timing patterns
406 		let size: i32 = self.size;
407 		for i in 0 .. size {
408 			self.set_function_module(6, i, i % 2 == 0);
409 			self.set_function_module(i, 6, i % 2 == 0);
410 		}
411 
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);
416 
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]);
425 				}
426 			}
427 		}
428 
429 		// Draw configuration data
430 		self.draw_format_bits(Mask::new(0));  // Dummy mask value; overwritten later in the constructor
431 		self.draw_version();
432 	}
433 
434 
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.
draw_format_bits(&mut self, mask: Mask)437 	fn draw_format_bits(&mut self, mask: Mask) {
438 		// Calculate error correction code and pack bits
439 		let bits: u32 = {
440 			// errcorrlvl is uint2, mask is uint3
441 			let data: u32 = self.errorcorrectionlevel.format_bits() << 3 | u32::from(mask.value());
442 			let mut rem: u32 = data;
443 			for _ in 0 .. 10 {
444 				rem = (rem << 1) ^ ((rem >> 9) * 0x537);
445 			}
446 			(data << 10 | rem) ^ 0x5412  // uint15
447 		};
448 		assert_eq!(bits >> 15, 0, "Assertion error");
449 
450 		// Draw first copy
451 		for i in 0 .. 6 {
452 			self.set_function_module(8, i, get_bit(bits, i));
453 		}
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));
457 		for i in 9 .. 15 {
458 			self.set_function_module(14 - i, 8, get_bit(bits, i));
459 		}
460 
461 		// Draw second copy
462 		let size: i32 = self.size;
463 		for i in 0 .. 8 {
464 			self.set_function_module(size - 1 - i, 8, get_bit(bits, i));
465 		}
466 		for i in 8 .. 15 {
467 			self.set_function_module(8, size - 15 + i, get_bit(bits, i));
468 		}
469 		self.set_function_module(8, size - 8, true);  // Always black
470 	}
471 
472 
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.
draw_version(&mut self)475 	fn draw_version(&mut self) {
476 		if self.version.value() < 7 {
477 			return;
478 		}
479 
480 		// Calculate error correction code and pack bits
481 		let bits: u32 = {
482 			let data = u32::from(self.version.value());  // uint6, in the range [7, 40]
483 			let mut rem: u32 = data;
484 			for _ in 0 .. 12 {
485 				rem = (rem << 1) ^ ((rem >> 11) * 0x1F25);
486 			}
487 			data << 12 | rem  // uint18
488 		};
489 		assert!(bits >> 18 == 0, "Assertion error");
490 
491 		// Draw two copies
492 		for i in 0 .. 18 {
493 			let bit: bool = get_bit(bits, i);
494 			let a: i32 = self.size - 11 + i % 3;
495 			let b: i32 = i / 3;
496 			self.set_function_module(a, b, bit);
497 			self.set_function_module(b, a, bit);
498 		}
499 	}
500 
501 
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.
draw_finder_pattern(&mut self, x: i32, y: i32)504 	fn draw_finder_pattern(&mut self, x: i32, y: i32) {
505 		for dy in -4 ..= 4 {
506 			for dx in -4 ..= 4 {
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);
512 				}
513 			}
514 		}
515 	}
516 
517 
518 	// Draws a 5*5 alignment pattern, with the center module
519 	// at (x, y). All modules must be in bounds.
draw_alignment_pattern(&mut self, x: i32, y: i32)520 	fn draw_alignment_pattern(&mut self, x: i32, y: i32) {
521 		for dy in -2 ..= 2 {
522 			for dx in -2 ..= 2 {
523 				self.set_function_module(x + dx, y + dy, std::cmp::max(dx.abs(), dy.abs()) != 1);
524 			}
525 		}
526 	}
527 
528 
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.
set_function_module(&mut self, x: i32, y: i32, isblack: bool)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;
534 	}
535 
536 
537 	/*---- Private helper methods for constructor: Codewords and masking ----*/
538 
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.
add_ecc_and_interleave(&self, data: &[u8]) -> Vec<u8>541 	fn add_ecc_and_interleave(&self, data: &[u8]) -> Vec<u8> {
542 		let ver = self.version;
543 		let ecl = self.errorcorrectionlevel;
544 		assert_eq!(data.len(), QrCode::get_num_data_codewords(ver, ecl), "Illegal argument");
545 
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;
552 
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();
560 			k += datlen;
561 			let ecc: Vec<u8> = QrCode::reed_solomon_compute_remainder(&dat, &rsdiv);
562 			if i < numshortblocks {
563 				dat.push(0);
564 			}
565 			dat.extend_from_slice(&ecc);
566 			blocks.push(dat);
567 		}
568 
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]);
576 				}
577 			}
578 		}
579 		result
580 	}
581 
582 
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.
draw_codewords(&mut self, data: &[u8])585 	fn draw_codewords(&mut self, data: &[u8]) {
586 		assert_eq!(data.len(), QrCode::get_num_raw_data_modules(self.version) / 8, "Illegal argument");
587 
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
592 			if right == 6 {
593 				right = 5;
594 			}
595 			for vert in 0 .. self.size {  // Vertical counter
596 				for j in 0 .. 2 {
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));
602 						i += 1;
603 					}
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
606 				}
607 			}
608 			right -= 2;
609 		}
610 		assert_eq!(i, data.len() * 8, "Assertion error");
611 	}
612 
613 
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 applyMask() 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.
apply_mask(&mut self, mask: Mask)619 	fn apply_mask(&mut self, mask: Mask) {
620 		let mask: u8 = mask.value();
621 		for y in 0 .. self.size {
622 			for x in 0 .. self.size {
623 				let invert: bool = match mask {
624 					0 => (x + y) % 2 == 0,
625 					1 => y % 2 == 0,
626 					2 => x % 3 == 0,
627 					3 => (x + y) % 3 == 0,
628 					4 => (x / 3 + y / 2) % 2 == 0,
629 					5 => x * y % 2 + x * y % 3 == 0,
630 					6 => (x * y % 2 + x * y % 3) % 2 == 0,
631 					7 => ((x + y) % 2 + x * y % 3) % 2 == 0,
632 					_ => unreachable!(),
633 				};
634 				*self.module_mut(x, y) ^= invert & !self.isfunction[(y * self.size + x) as usize];
635 			}
636 		}
637 	}
638 
639 
640 	// Calculates and returns the penalty score based on state of this QR Code's current modules.
641 	// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
get_penalty_score(&self) -> i32642 	fn get_penalty_score(&self) -> i32 {
643 		let mut result: i32 = 0;
644 		let size: i32 = self.size;
645 
646 		// Adjacent modules in row having same color, and finder-like patterns
647 		for y in 0 .. size {
648 			let mut runcolor = false;
649 			let mut runx: i32 = 0;
650 			let mut runhistory = FinderPenalty::new(size);
651 			for x in 0 .. size {
652 				if self.module(x, y) == runcolor {
653 					runx += 1;
654 					if runx == 5 {
655 						result += PENALTY_N1;
656 					} else if runx > 5 {
657 						result += 1;
658 					}
659 				} else {
660 					runhistory.add_history(runx);
661 					if !runcolor {
662 						result += runhistory.count_patterns() * PENALTY_N3;
663 					}
664 					runcolor = self.module(x, y);
665 					runx = 1;
666 				}
667 			}
668 			result += runhistory.terminate_and_count(runcolor, runx) * PENALTY_N3;
669 		}
670 		// Adjacent modules in column having same color, and finder-like patterns
671 		for x in 0 .. size {
672 			let mut runcolor = false;
673 			let mut runy: i32 = 0;
674 			let mut runhistory = FinderPenalty::new(size);
675 			for y in 0 .. size {
676 				if self.module(x, y) == runcolor {
677 					runy += 1;
678 					if runy == 5 {
679 						result += PENALTY_N1;
680 					} else if runy > 5 {
681 						result += 1;
682 					}
683 				} else {
684 					runhistory.add_history(runy);
685 					if !runcolor {
686 						result += runhistory.count_patterns() * PENALTY_N3;
687 					}
688 					runcolor = self.module(x, y);
689 					runy = 1;
690 				}
691 			}
692 			result += runhistory.terminate_and_count(runcolor, runy) * PENALTY_N3;
693 		}
694 
695 		// 2*2 blocks of modules having same color
696 		for y in 0 .. size - 1 {
697 			for x in 0 .. size - 1 {
698 				let color: bool = self.module(x, y);
699 				if color == self.module(x + 1, y) &&
700 				   color == self.module(x, y + 1) &&
701 				   color == self.module(x + 1, y + 1) {
702 					result += PENALTY_N2;
703 				}
704 			}
705 		}
706 
707 		// Balance of black and white modules
708 		let black: i32 = self.modules.iter().copied().map(i32::from).sum();
709 		let total: i32 = size * size;  // Note that size is odd, so black/total != 1/2
710 		// Compute the smallest integer k >= 0 such that (45-5k)% <= black/total <= (55+5k)%
711 		let k: i32 = ((black * 20 - total * 10).abs() + total - 1) / total - 1;
712 		result += k * PENALTY_N4;
713 		result
714 	}
715 
716 
717 	/*---- Private helper functions ----*/
718 
719 	// Returns an ascending list of positions of alignment patterns for this version number.
720 	// Each position is in the range [0,177), and are used on both the x and y axes.
721 	// This could be implemented as lookup table of 40 variable-length lists of unsigned bytes.
get_alignment_pattern_positions(&self) -> Vec<i32>722 	fn get_alignment_pattern_positions(&self) -> Vec<i32> {
723 		let ver = self.version.value();
724 		if ver == 1 {
725 			vec![]
726 		} else {
727 			let numalign = i32::from(ver) / 7 + 2;
728 			let step: i32 = if ver == 32 { 26 } else
729 				{(i32::from(ver)*4 + numalign*2 + 1) / (numalign*2 - 2) * 2};
730 			let mut result: Vec<i32> = (0 .. numalign - 1).map(
731 				|i| self.size - 7 - i * step).collect();
732 			result.push(6);
733 			result.reverse();
734 			result
735 		}
736 	}
737 
738 
739 	// Returns the number of data bits that can be stored in a QR Code of the given version number, after
740 	// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
741 	// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
get_num_raw_data_modules(ver: Version) -> usize742 	fn get_num_raw_data_modules(ver: Version) -> usize {
743 		let ver = usize::from(ver.value());
744 		let mut result: usize = (16 * ver + 128) * ver + 64;
745 		if ver >= 2 {
746 			let numalign: usize = ver / 7 + 2;
747 			result -= (25 * numalign - 10) * numalign - 55;
748 			if ver >= 7 {
749 				result -= 36;
750 			}
751 		}
752 		assert!(208 <= result && result <= 29648);
753 		result
754 	}
755 
756 
757 	// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
758 	// QR Code of the given version number and error correction level, with remainder bits discarded.
759 	// This stateless pure function could be implemented as a (40*4)-cell lookup table.
get_num_data_codewords(ver: Version, ecl: QrCodeEcc) -> usize760 	fn get_num_data_codewords(ver: Version, ecl: QrCodeEcc) -> usize {
761 		QrCode::get_num_raw_data_modules(ver) / 8
762 			- QrCode::table_get(&ECC_CODEWORDS_PER_BLOCK    , ver, ecl)
763 			* QrCode::table_get(&NUM_ERROR_CORRECTION_BLOCKS, ver, ecl)
764 	}
765 
766 
767 	// Returns an entry from the given table based on the given values.
table_get(table: &'static [[i8; 41]; 4], ver: Version, ecl: QrCodeEcc) -> usize768 	fn table_get(table: &'static [[i8; 41]; 4], ver: Version, ecl: QrCodeEcc) -> usize {
769 		table[ecl.ordinal()][usize::from(ver.value())] as usize
770 	}
771 
772 
773 	// Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
774 	// implemented as a lookup table over all possible parameter values, instead of as an algorithm.
reed_solomon_compute_divisor(degree: usize) -> Vec<u8>775 	fn reed_solomon_compute_divisor(degree: usize) -> Vec<u8> {
776 		assert!(1 <= degree && degree <= 255, "Degree out of range");
777 		// Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
778 		// For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
779 		let mut result = vec![0u8; degree - 1];
780 		result.push(1);  // Start off with the monomial x^0
781 
782 		// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
783 		// and drop the highest monomial term which is always 1x^degree.
784 		// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
785 		let mut root: u8 = 1;
786 		for _ in 0 .. degree {  // Unused variable i
787 			// Multiply the current product by (x - r^i)
788 			for j in 0 .. degree {
789 				result[j] = QrCode::reed_solomon_multiply(result[j], root);
790 				if j + 1 < result.len() {
791 					result[j] ^= result[j + 1];
792 				}
793 			}
794 			root = QrCode::reed_solomon_multiply(root, 0x02);
795 		}
796 		result
797 	}
798 
799 
800 	// Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
reed_solomon_compute_remainder(data: &[u8], divisor: &[u8]) -> Vec<u8>801 	fn reed_solomon_compute_remainder(data: &[u8], divisor: &[u8]) -> Vec<u8> {
802 		let mut result = vec![0u8; divisor.len()];
803 		for b in data {  // Polynomial division
804 			let factor: u8 = b ^ result.remove(0);
805 			result.push(0);
806 			for (x, &y) in result.iter_mut().zip(divisor.iter()) {
807 				*x ^= QrCode::reed_solomon_multiply(y, factor);
808 			}
809 		}
810 		result
811 	}
812 
813 
814 	// Returns the product of the two given field elements modulo GF(2^8/0x11D).
815 	// All inputs are valid. This could be implemented as a 256*256 lookup table.
reed_solomon_multiply(x: u8, y: u8) -> u8816 	fn reed_solomon_multiply(x: u8, y: u8) -> u8 {
817 		// Russian peasant multiplication
818 		let mut z: u8 = 0;
819 		for i in (0 .. 8).rev() {
820 			z = (z << 1) ^ ((z >> 7) * 0x1D);
821 			z ^= ((y >> i) & 1) * x;
822 		}
823 		z
824 	}
825 
826 }
827 
828 
829 /*---- Helper struct for get_penalty_score() ----*/
830 
831 struct FinderPenalty {
832 	qr_size: i32,
833 	run_history: [i32; 7],
834 }
835 
836 
837 impl FinderPenalty {
838 
new(size: i32) -> Self839 	pub fn new(size: i32) -> Self {
840 		Self {
841 			qr_size: size,
842 			run_history: [0i32; 7],
843 		}
844 	}
845 
846 
847 	// Pushes the given value to the front and drops the last value.
add_history(&mut self, mut currentrunlength: i32)848 	pub fn add_history(&mut self, mut currentrunlength: i32) {
849 		if self.run_history[0] == 0 {
850 			currentrunlength += self.qr_size;  // Add white border to initial run
851 		}
852 		let rh = &mut self.run_history;
853 		for i in (0 .. rh.len()-1).rev() {
854 			rh[i + 1] = rh[i];
855 		}
856 		rh[0] = currentrunlength;
857 	}
858 
859 
860 	// Can only be called immediately after a white run is added, and returns either 0, 1, or 2.
count_patterns(&self) -> i32861 	pub fn count_patterns(&self) -> i32 {
862 		let rh = &self.run_history;
863 		let n = rh[1];
864 		assert!(n <= self.qr_size * 3);
865 		let core = n > 0 && rh[2] == n && rh[3] == n * 3 && rh[4] == n && rh[5] == n;
866 		( i32::from(core && rh[0] >= n * 4 && rh[6] >= n)
867 		+ i32::from(core && rh[6] >= n * 4 && rh[0] >= n))
868 	}
869 
870 
871 	// Must be called at the end of a line (row or column) of modules.
terminate_and_count(mut self, currentruncolor: bool, mut currentrunlength: i32) -> i32872 	pub fn terminate_and_count(mut self, currentruncolor: bool, mut currentrunlength: i32) -> i32 {
873 		if currentruncolor {  // Terminate black run
874 			self.add_history(currentrunlength);
875 			currentrunlength = 0;
876 		}
877 		currentrunlength += self.qr_size;  // Add white border to final run
878 		self.add_history(currentrunlength);
879 		self.count_patterns()
880 	}
881 
882 }
883 
884 
885 /*---- Constants and tables ----*/
886 
887 /// The minimum version number supported in the QR Code Model 2 standard.
888 pub const QrCode_MIN_VERSION: Version = Version( 1);
889 
890 /// The maximum version number supported in the QR Code Model 2 standard.
891 pub const QrCode_MAX_VERSION: Version = Version(40);
892 
893 
894 // For use in get_penalty_score(), when evaluating which mask is best.
895 const PENALTY_N1: i32 =  3;
896 const PENALTY_N2: i32 =  3;
897 const PENALTY_N3: i32 = 40;
898 const PENALTY_N4: i32 = 10;
899 
900 
901 static ECC_CODEWORDS_PER_BLOCK: [[i8; 41]; 4] = [
902 	// Version: (note that index 0 is for padding, and is set to an illegal value)
903 	//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
904 	[-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
905 	[-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
906 	[-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
907 	[-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
908 ];
909 
910 static NUM_ERROR_CORRECTION_BLOCKS: [[i8; 41]; 4] = [
911 	// Version: (note that index 0 is for padding, and is set to an illegal value)
912 	//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
913 	[-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
914 	[-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
915 	[-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
916 	[-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
917 ];
918 
919 
920 
921 /*---- QrCodeEcc functionality ----*/
922 
923 /// The error correction level in a QR Code symbol.
924 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
925 pub enum QrCodeEcc {
926 	/// The QR Code can tolerate about  7% erroneous codewords.
927 	Low     ,
928 	/// The QR Code can tolerate about 15% erroneous codewords.
929 	Medium  ,
930 	/// The QR Code can tolerate about 25% erroneous codewords.
931 	Quartile,
932 	/// The QR Code can tolerate about 30% erroneous codewords.
933 	High    ,
934 }
935 
936 
937 impl QrCodeEcc {
938 
939 	// Returns an unsigned 2-bit integer (in the range 0 to 3).
ordinal(self) -> usize940 	fn ordinal(self) -> usize {
941 		use QrCodeEcc::*;
942 		match self {
943 			Low      => 0,
944 			Medium   => 1,
945 			Quartile => 2,
946 			High     => 3,
947 		}
948 	}
949 
950 
951 	// Returns an unsigned 2-bit integer (in the range 0 to 3).
format_bits(self) -> u32952 	fn format_bits(self) -> u32 {
953 		use QrCodeEcc::*;
954 		match self {
955 			Low      => 1,
956 			Medium   => 0,
957 			Quartile => 3,
958 			High     => 2,
959 		}
960 	}
961 
962 }
963 
964 
965 
966 /*---- QrSegment functionality ----*/
967 
968 /// A segment of character/binary/control data in a QR Code symbol.
969 ///
970 /// Instances of this struct are immutable.
971 ///
972 /// The mid-level way to create a segment is to take the payload data
973 /// and call a static factory function such as `QrSegment::make_numeric()`.
974 /// The low-level way to create a segment is to custom-make the bit buffer
975 /// and call the `QrSegment::new()` constructor with appropriate values.
976 ///
977 /// This segment struct imposes no length restrictions, but QR Codes have restrictions.
978 /// Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
979 /// Any segment longer than this is meaningless for the purpose of generating QR Codes.
980 #[derive(Clone, PartialEq, Eq)]
981 pub struct QrSegment {
982 
983 	// The mode indicator of this segment. Accessed through mode().
984 	mode: QrSegmentMode,
985 
986 	// The length of this segment's unencoded data. Measured in characters for
987 	// numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
988 	// Not the same as the data's bit length. Accessed through num_chars().
989 	numchars: usize,
990 
991 	// The data bits of this segment. Accessed through data().
992 	data: Vec<bool>,
993 
994 }
995 
996 
997 impl QrSegment {
998 
999 	/*---- Static factory functions (mid level) ----*/
1000 
1001 	/// Returns a segment representing the given binary data encoded in byte mode.
1002 	///
1003 	/// All input byte slices are acceptable.
1004 	///
1005 	/// Any text string can be converted to UTF-8 bytes and encoded as a byte mode segment.
make_bytes(data: &[u8]) -> Self1006 	pub fn make_bytes(data: &[u8]) -> Self {
1007 		let mut bb = BitBuffer(Vec::with_capacity(data.len() * 8));
1008 		for &b in data {
1009 			bb.append_bits(u32::from(b), 8);
1010 		}
1011 		QrSegment::new(QrSegmentMode::Byte, data.len(), bb.0)
1012 	}
1013 
1014 
1015 	/// Returns a segment representing the given string of decimal digits encoded in numeric mode.
1016 	///
1017 	/// Panics if the string contains non-digit characters.
make_numeric(text: &[char]) -> Self1018 	pub fn make_numeric(text: &[char]) -> Self {
1019 		let mut bb = BitBuffer(Vec::with_capacity(text.len() * 3 + (text.len() + 2) / 3));
1020 		let mut accumdata: u32 = 0;
1021 		let mut accumcount: u8 = 0;
1022 		for &c in text {
1023 			assert!('0' <= c && c <= '9', "String contains non-numeric characters");
1024 			accumdata = accumdata * 10 + (u32::from(c) - u32::from('0'));
1025 			accumcount += 1;
1026 			if accumcount == 3 {
1027 				bb.append_bits(accumdata, 10);
1028 				accumdata = 0;
1029 				accumcount = 0;
1030 			}
1031 		}
1032 		if accumcount > 0 {  // 1 or 2 digits remaining
1033 			bb.append_bits(accumdata, accumcount * 3 + 1);
1034 		}
1035 		QrSegment::new(QrSegmentMode::Numeric, text.len(), bb.0)
1036 	}
1037 
1038 
1039 	/// Returns a segment representing the given text string encoded in alphanumeric mode.
1040 	///
1041 	/// The characters allowed are: 0 to 9, A to Z (uppercase only), space,
1042 	/// dollar, percent, asterisk, plus, hyphen, period, slash, colon.
1043 	///
1044 	/// Panics if the string contains non-encodable characters.
make_alphanumeric(text: &[char]) -> Self1045 	pub fn make_alphanumeric(text: &[char]) -> Self {
1046 		let mut bb = BitBuffer(Vec::with_capacity(text.len() * 5 + (text.len() + 1) / 2));
1047 		let mut accumdata: u32 = 0;
1048 		let mut accumcount: u32 = 0;
1049 		for &c in text {
1050 			let i = ALPHANUMERIC_CHARSET.iter().position(|&x| x == c)
1051 				.expect("String contains unencodable characters in alphanumeric mode");
1052 			accumdata = accumdata * 45 + (i as u32);
1053 			accumcount += 1;
1054 			if accumcount == 2 {
1055 				bb.append_bits(accumdata, 11);
1056 				accumdata = 0;
1057 				accumcount = 0;
1058 			}
1059 		}
1060 		if accumcount > 0 {  // 1 character remaining
1061 			bb.append_bits(accumdata, 6);
1062 		}
1063 		QrSegment::new(QrSegmentMode::Alphanumeric, text.len(), bb.0)
1064 	}
1065 
1066 
1067 	/// Returns a list of zero or more segments to represent the given Unicode text string.
1068 	///
1069 	/// The result may use various segment modes and switch
1070 	/// modes to optimize the length of the bit stream.
make_segments(text: &[char]) -> Vec<Self>1071 	pub fn make_segments(text: &[char]) -> Vec<Self> {
1072 		if text.is_empty() {
1073 			vec![]
1074 		} else if QrSegment::is_numeric(text) {
1075 			vec![QrSegment::make_numeric(text)]
1076 		} else if QrSegment::is_alphanumeric(text) {
1077 			vec![QrSegment::make_alphanumeric(text)]
1078 		} else {
1079 			let s: String = text.iter().cloned().collect();
1080 			vec![QrSegment::make_bytes(s.as_bytes())]
1081 		}
1082 	}
1083 
1084 
1085 	/// Returns a segment representing an Extended Channel Interpretation
1086 	/// (ECI) designator with the given assignment value.
make_eci(assignval: u32) -> Self1087 	pub fn make_eci(assignval: u32) -> Self {
1088 		let mut bb = BitBuffer(Vec::with_capacity(24));
1089 		if assignval < (1 << 7) {
1090 			bb.append_bits(assignval, 8);
1091 		} else if assignval < (1 << 14) {
1092 			bb.append_bits(2, 2);
1093 			bb.append_bits(assignval, 14);
1094 		} else if assignval < 1_000_000 {
1095 			bb.append_bits(6, 3);
1096 			bb.append_bits(assignval, 21);
1097 		} else {
1098 			panic!("ECI assignment value out of range");
1099 		}
1100 		QrSegment::new(QrSegmentMode::Eci, 0, bb.0)
1101 	}
1102 
1103 
1104 	/*---- Constructor (low level) ----*/
1105 
1106 	/// Creates a new QR Code segment with the given attributes and data.
1107 	///
1108 	/// The character count (numchars) must agree with the mode and
1109 	/// the bit buffer length, but the constraint isn't checked.
new(mode: QrSegmentMode, numchars: usize, data: Vec<bool>) -> Self1110 	pub fn new(mode: QrSegmentMode, numchars: usize, data: Vec<bool>) -> Self {
1111 		Self { mode, numchars, data }
1112 	}
1113 
1114 
1115 	/*---- Instance field getters ----*/
1116 
1117 	/// Returns the mode indicator of this segment.
mode(&self) -> QrSegmentMode1118 	pub fn mode(&self) -> QrSegmentMode {
1119 		self.mode
1120 	}
1121 
1122 
1123 	/// Returns the character count field of this segment.
num_chars(&self) -> usize1124 	pub fn num_chars(&self) -> usize {
1125 		self.numchars
1126 	}
1127 
1128 
1129 	/// Returns the data bits of this segment.
data(&self) -> &Vec<bool>1130 	pub fn data(&self) -> &Vec<bool> {
1131 		&self.data
1132 	}
1133 
1134 
1135 	/*---- Other static functions ----*/
1136 
1137 	// Calculates and returns the number of bits needed to encode the given
1138 	// segments at the given version. The result is None if a segment has too many
1139 	// characters to fit its length field, or the total bits exceeds usize::MAX.
get_total_bits(segs: &[Self], version: Version) -> Option<usize>1140 	fn get_total_bits(segs: &[Self], version: Version) -> Option<usize> {
1141 		let mut result: usize = 0;
1142 		for seg in segs {
1143 			let ccbits = seg.mode.num_char_count_bits(version);
1144 			if seg.numchars >= 1 << ccbits {
1145 				return None;  // The segment's length doesn't fit the field's bit width
1146 			}
1147 			result = result.checked_add(4 + usize::from(ccbits) + seg.data.len())?;
1148 		}
1149 		Some(result)
1150 	}
1151 
1152 
1153 	// Tests whether the given string can be encoded as a segment in alphanumeric mode.
1154 	// A string is encodable iff each character is in the following set: 0 to 9, A to Z
1155 	// (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
is_alphanumeric(text: &[char]) -> bool1156 	fn is_alphanumeric(text: &[char]) -> bool {
1157 		text.iter().all(|c| ALPHANUMERIC_CHARSET.contains(c))
1158 	}
1159 
1160 
1161 	// Tests whether the given string can be encoded as a segment in numeric mode.
1162 	// A string is encodable iff each character is in the range 0 to 9.
is_numeric(text: &[char]) -> bool1163 	fn is_numeric(text: &[char]) -> bool {
1164 		text.iter().all(|&c| '0' <= c && c <= '9')
1165 	}
1166 
1167 }
1168 
1169 
1170 // The set of all legal characters in alphanumeric mode,
1171 // where each character value maps to the index in the string.
1172 static ALPHANUMERIC_CHARSET: [char; 45] = ['0','1','2','3','4','5','6','7','8','9',
1173 	'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',
1174 	' ','$','%','*','+','-','.','/',':'];
1175 
1176 
1177 
1178 /*---- QrSegmentMode functionality ----*/
1179 
1180 /// Describes how a segment's data bits are interpreted.
1181 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
1182 pub enum QrSegmentMode {
1183 	Numeric,
1184 	Alphanumeric,
1185 	Byte,
1186 	Kanji,
1187 	Eci,
1188 }
1189 
1190 
1191 impl QrSegmentMode {
1192 
1193 	// Returns an unsigned 4-bit integer value (range 0 to 15)
1194 	// representing the mode indicator bits for this mode object.
mode_bits(self) -> u321195 	fn mode_bits(self) -> u32 {
1196 		use QrSegmentMode::*;
1197 		match self {
1198 			Numeric      => 0x1,
1199 			Alphanumeric => 0x2,
1200 			Byte         => 0x4,
1201 			Kanji        => 0x8,
1202 			Eci          => 0x7,
1203 		}
1204 	}
1205 
1206 
1207 	// Returns the bit width of the character count field for a segment in this mode
1208 	// in a QR Code at the given version number. The result is in the range [0, 16].
num_char_count_bits(self, ver: Version) -> u81209 	fn num_char_count_bits(self, ver: Version) -> u8 {
1210 		use QrSegmentMode::*;
1211 		(match self {
1212 			Numeric      => [10, 12, 14],
1213 			Alphanumeric => [ 9, 11, 13],
1214 			Byte         => [ 8, 16, 16],
1215 			Kanji        => [ 8, 10, 12],
1216 			Eci          => [ 0,  0,  0],
1217 		})[usize::from((ver.value() + 7) / 17)]
1218 	}
1219 
1220 }
1221 
1222 
1223 
1224 /*---- Bit buffer functionality ----*/
1225 
1226 /// An appendable sequence of bits (0s and 1s).
1227 ///
1228 /// Mainly used by QrSegment.
1229 pub struct BitBuffer(pub Vec<bool>);
1230 
1231 
1232 impl BitBuffer {
1233 	/// Appends the given number of low-order bits of the given value to this buffer.
1234 	///
1235 	/// Requires len &#x2264; 31 and val &lt; 2<sup>len</sup>.
append_bits(&mut self, val: u32, len: u8)1236 	pub fn append_bits(&mut self, val: u32, len: u8) {
1237 		assert!(len <= 31 && (val >> len) == 0, "Value out of range");
1238 		self.0.extend((0 .. i32::from(len)).rev().map(|i| get_bit(val, i)));  // Append bit by bit
1239 	}
1240 }
1241 
1242 
1243 
1244 /*---- Miscellaneous values ----*/
1245 
1246 /// The error type when the supplied data does not fit any QR Code version.
1247 ///
1248 /// Ways to handle this exception include:
1249 ///
1250 /// - Decrease the error correction level if it was greater than `QrCodeEcc::Low`.
1251 /// - If the `encode_segments_advanced()` function was called, then increase the maxversion
1252 ///   argument if it was less than `QrCode_MAX_VERSION`. (This advice does not apply to the
1253 ///   other factory functions because they search all versions up to `QrCode_MAX_VERSION`.)
1254 /// - Split the text data into better or optimal segments in order to reduce the number of bits required.
1255 /// - Change the text or binary data to be shorter.
1256 /// - Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).
1257 /// - Propagate the error upward to the caller/user.
1258 #[derive(Debug, Clone)]
1259 pub struct DataTooLong(String);
1260 
1261 impl std::error::Error for DataTooLong {
description(&self) -> &str1262 	fn description(&self) -> &str {
1263 		&self.0
1264 	}
1265 }
1266 
1267 impl std::fmt::Display for DataTooLong {
fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result1268 	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1269 		f.write_str(&self.0)
1270 	}
1271 }
1272 
1273 
1274 /// A number between 1 and 40 (inclusive).
1275 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1276 pub struct Version(u8);
1277 
1278 impl Version {
1279 	/// Creates a version object from the given number.
1280 	///
1281 	/// Panics if the number is outside the range [1, 40].
new(ver: u8) -> Self1282 	pub fn new(ver: u8) -> Self {
1283 		assert!(QrCode_MIN_VERSION.value() <= ver && ver <= QrCode_MAX_VERSION.value(), "Version number out of range");
1284 		Self(ver)
1285 	}
1286 
1287 	/// Returns the value, which is in the range [1, 40].
value(self) -> u81288 	pub fn value(self) -> u8 {
1289 		self.0
1290 	}
1291 }
1292 
1293 
1294 /// A number between 0 and 7 (inclusive).
1295 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1296 pub struct Mask(u8);
1297 
1298 impl Mask {
1299 	/// Creates a mask object from the given number.
1300 	///
1301 	/// Panics if the number is outside the range [0, 7].
new(mask: u8) -> Self1302 	pub fn new(mask: u8) -> Self {
1303 		assert!(mask <= 7, "Mask value out of range");
1304 		Self(mask)
1305 	}
1306 
1307 	/// Returns the value, which is in the range [0, 7].
value(self) -> u81308 	pub fn value(self) -> u8 {
1309 		self.0
1310 	}
1311 }
1312 
1313 
1314 // Returns true iff the i'th bit of x is set to 1.
get_bit(x: u32, i: i32) -> bool1315 fn get_bit(x: u32, i: i32) -> bool {
1316 	(x >> i) & 1 != 0
1317 }
1318