xref: /aosp_15_r20/external/cronet/third_party/rust/chromium_crates_io/vendor/qr_code-2.0.0/src/bits.rs (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 //! The `bits` module encodes binary data into raw bits used in a QR code.
2 
3 use std::cmp::min;
4 
5 use crate::cast::{As, Truncate};
6 use crate::optimize::{optimize_segmentation, total_encoded_len, Parser, Segment};
7 use crate::types::{EcLevel, Mode, QrError, QrResult, Version};
8 
9 //------------------------------------------------------------------------------
10 //{{{ Bits
11 
12 /// The `Bits` structure stores the encoded data for a QR code.
13 #[derive(Clone)]
14 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
15 pub struct Bits {
16     data: Vec<u8>,
17     bit_offset: usize,
18     version: Version,
19 }
20 
21 impl Bits {
22     /// Constructs a new, empty bits structure.
new(version: Version) -> Self23     pub fn new(version: Version) -> Self {
24         Self {
25             data: Vec::new(),
26             bit_offset: 0,
27             version,
28         }
29     }
30 
31     /// Pushes an N-bit big-endian integer to the end of the bits.
32     ///
33     /// Note: It is up to the developer to ensure that `number` really only is
34     /// `n` bit in size. Otherwise the excess bits may stomp on the existing
35     /// ones.
push_number(&mut self, n: usize, number: u16)36     fn push_number(&mut self, n: usize, number: u16) {
37         debug_assert!(
38             n == 16 || n < 16 && number < (1 << n),
39             "{} is too big as a {}-bit number",
40             number,
41             n
42         );
43 
44         let b = self.bit_offset + n;
45         let last_index = self.data.len().wrapping_sub(1);
46         match (self.bit_offset, b) {
47             (0, 0..=8) => {
48                 self.data.push((number << (8 - b)).truncate_as_u8());
49             }
50             (0, _) => {
51                 self.data.push((number >> (b - 8)).truncate_as_u8());
52                 self.data.push((number << (16 - b)).truncate_as_u8());
53             }
54             (_, 0..=8) => {
55                 self.data[last_index] |= (number << (8 - b)).truncate_as_u8();
56             }
57             (_, 9..=16) => {
58                 self.data[last_index] |= (number >> (b - 8)).truncate_as_u8();
59                 self.data.push((number << (16 - b)).truncate_as_u8());
60             }
61             _ => {
62                 self.data[last_index] |= (number >> (b - 8)).truncate_as_u8();
63                 self.data.push((number >> (b - 16)).truncate_as_u8());
64                 self.data.push((number << (24 - b)).truncate_as_u8());
65             }
66         }
67         self.bit_offset = b & 7;
68     }
69 
70     /// Pushes an N-bit big-endian integer to the end of the bits, and check
71     /// that the number does not overflow the bits.
72     ///
73     /// Returns `Err(QrError::DataTooLong)` on overflow.
push_number_checked(&mut self, n: usize, number: usize) -> QrResult<()>74     pub fn push_number_checked(&mut self, n: usize, number: usize) -> QrResult<()> {
75         if n > 16 || number >= (1 << n) {
76             Err(QrError::DataTooLong)
77         } else {
78             self.push_number(n, number.as_u16());
79             Ok(())
80         }
81     }
82 
83     /// Reserves `n` extra bits of space for pushing.
reserve(&mut self, n: usize)84     fn reserve(&mut self, n: usize) {
85         let extra_bytes = (n + (8 - self.bit_offset) % 8) / 8;
86         self.data.reserve(extra_bytes);
87     }
88 
89     /// Convert the bits into a bytes vector.
into_bytes(self) -> Vec<u8>90     pub fn into_bytes(self) -> Vec<u8> {
91         self.data
92     }
93 
94     /// Total number of bits currently pushed.
len(&self) -> usize95     pub fn len(&self) -> usize {
96         if self.bit_offset == 0 {
97             self.data.len() * 8
98         } else {
99             (self.data.len() - 1) * 8 + self.bit_offset
100         }
101     }
102 
103     /// Whether there are any bits pushed.
is_empty(&self) -> bool104     pub fn is_empty(&self) -> bool {
105         self.data.is_empty()
106     }
107 
108     /// The maximum number of bits allowed by the provided QR code version and
109     /// error correction level.
110     ///
111     /// # Errors
112     ///
113     /// Returns `Err(QrError::InvalidVersion)` if it is not valid to use the
114     /// `ec_level` for the given version (e.g. `Version::Micro(1)` with
115     /// `EcLevel::H`).
max_len(&self, ec_level: EcLevel) -> QrResult<usize>116     pub fn max_len(&self, ec_level: EcLevel) -> QrResult<usize> {
117         self.version.fetch(ec_level, &DATA_LENGTHS)
118     }
119 
120     /// Version of the QR code.
version(&self) -> Version121     pub fn version(&self) -> Version {
122         self.version
123     }
124 }
125 
126 #[test]
test_push_number()127 fn test_push_number() {
128     let mut bits = Bits::new(Version::Normal(1));
129 
130     bits.push_number(3, 0b010); // 0:0 .. 0:3
131     bits.push_number(3, 0b110); // 0:3 .. 0:6
132     bits.push_number(3, 0b101); // 0:6 .. 1:1
133     bits.push_number(7, 0b001_1010); // 1:1 .. 2:0
134     bits.push_number(4, 0b1100); // 2:0 .. 2:4
135     bits.push_number(12, 0b1011_0110_1101); // 2:4 .. 4:0
136     bits.push_number(10, 0b01_1001_0001); // 4:0 .. 5:2
137     bits.push_number(15, 0b111_0010_1110_0011); // 5:2 .. 7:1
138 
139     let bytes = bits.into_bytes();
140 
141     assert_eq!(
142         bytes,
143         vec![
144             0b010__110__10, // 90
145             0b1__001_1010,  // 154
146             0b1100__1011,   // 203
147             0b0110_1101,    // 109
148             0b01_1001_00,   // 100
149             0b01__111_001,  // 121
150             0b0_1110_001,   // 113
151             0b1__0000000,   // 128
152         ]
153     );
154 }
155 
156 #[cfg(bench)]
157 #[bench]
bench_push_splitted_bytes(bencher: &mut test::Bencher)158 fn bench_push_splitted_bytes(bencher: &mut test::Bencher) {
159     bencher.iter(|| {
160         let mut bits = Bits::new(Version::Normal(40));
161         bits.push_number(4, 0b0101);
162         for _ in 0..1024 {
163             bits.push_number(8, 0b10101010);
164         }
165         bits.into_bytes()
166     });
167 }
168 
169 //}}}
170 //------------------------------------------------------------------------------
171 //{{{ Mode indicator
172 
173 /// An "extended" mode indicator, includes all indicators supported by QR code
174 /// beyond those bearing data.
175 #[derive(Copy, Clone)]
176 pub enum ExtendedMode {
177     /// ECI mode indicator, to introduce an ECI designator.
178     Eci,
179 
180     /// The normal mode to introduce data.
181     Data(Mode),
182 
183     /// FNC-1 mode in the first position.
184     Fnc1First,
185 
186     /// FNC-1 mode in the second position.
187     Fnc1Second,
188 
189     /// Structured append.
190     StructuredAppend,
191 }
192 
193 impl Bits {
194     /// Push the mode indicator to the end of the bits.
195     ///
196     /// # Errors
197     ///
198     /// If the mode is not supported in the provided version, this method
199     /// returns `Err(QrError::UnsupportedCharacterSet)`.
push_mode_indicator(&mut self, mode: ExtendedMode) -> QrResult<()>200     pub fn push_mode_indicator(&mut self, mode: ExtendedMode) -> QrResult<()> {
201         #[allow(clippy::match_same_arms)]
202         let number = match (self.version, mode) {
203             (Version::Micro(1), ExtendedMode::Data(Mode::Numeric)) => return Ok(()),
204             (Version::Micro(_), ExtendedMode::Data(Mode::Numeric)) => 0,
205             (Version::Micro(_), ExtendedMode::Data(Mode::Alphanumeric)) => 1,
206             (Version::Micro(_), ExtendedMode::Data(Mode::Byte)) => 0b10,
207             (Version::Micro(_), ExtendedMode::Data(Mode::Kanji)) => 0b11,
208             (Version::Micro(_), _) => return Err(QrError::UnsupportedCharacterSet),
209             (_, ExtendedMode::Data(Mode::Numeric)) => 0b0001,
210             (_, ExtendedMode::Data(Mode::Alphanumeric)) => 0b0010,
211             (_, ExtendedMode::Data(Mode::Byte)) => 0b0100,
212             (_, ExtendedMode::Data(Mode::Kanji)) => 0b1000,
213             (_, ExtendedMode::Eci) => 0b0111,
214             (_, ExtendedMode::Fnc1First) => 0b0101,
215             (_, ExtendedMode::Fnc1Second) => 0b1001,
216             (_, ExtendedMode::StructuredAppend) => 0b0011,
217         };
218         let bits = self.version.mode_bits_count();
219         self.push_number_checked(bits, number)
220             .or(Err(QrError::UnsupportedCharacterSet))
221     }
222 }
223 
224 //}}}
225 //------------------------------------------------------------------------------
226 //{{{ ECI
227 
228 impl Bits {
229     /// Push an ECI (Extended Channel Interpretation) designator to the bits.
230     ///
231     /// An ECI designator is a 6-digit number to specify the character set of
232     /// the following binary data. After calling this method, one could call
233     /// `.push_byte_data()` or similar methods to insert the actual data, e.g.
234     ///
235     ///     #![allow(unused_must_use)]
236     ///
237     ///     use qr_code::bits::Bits;
238     ///     use qr_code::types::Version;
239     ///
240     ///     let mut bits = Bits::new(Version::Normal(1));
241     ///     bits.push_eci_designator(9); // 9 = ISO-8859-7 (Greek).
242     ///     bits.push_byte_data(b"\xa1\xa2\xa3\xa4\xa5"); // ΑΒΓΔΕ
243     ///
244     ///
245     /// The full list of ECI designator values can be found from
246     /// <http://strokescribe.com/en/ECI.html>. Some example values are:
247     ///
248     /// ECI # | Character set
249     /// ------|-------------------------------------
250     /// 3     | ISO-8859-1 (Western European)
251     /// 20    | Shift JIS (Japanese)
252     /// 23    | Windows 1252 (Latin 1) (Western European)
253     /// 25    | UTF-16 Big Endian
254     /// 26    | UTF-8
255     /// 28    | Big 5 (Traditional Chinese)
256     /// 29    | GB-18030 (Simplified Chinese)
257     /// 30    | EUC-KR (Korean)
258     ///
259     /// # Errors
260     ///
261     /// If the QR code version does not support ECI, this method will return
262     /// `Err(QrError::UnsupportedCharacterSet)`.
263     ///
264     /// If the designator is outside of the expected range, this method will
265     /// return `Err(QrError::InvalidECIDesignator)`.
push_eci_designator(&mut self, eci_designator: u32) -> QrResult<()>266     pub fn push_eci_designator(&mut self, eci_designator: u32) -> QrResult<()> {
267         self.reserve(12); // assume the common case that eci_designator <= 127.
268         self.push_mode_indicator(ExtendedMode::Eci)?;
269         match eci_designator {
270             0..=127 => {
271                 self.push_number(8, eci_designator.as_u16());
272             }
273             128..=16383 => {
274                 self.push_number(2, 0b10);
275                 self.push_number(14, eci_designator.as_u16());
276             }
277             16384..=999_999 => {
278                 self.push_number(3, 0b110);
279                 self.push_number(5, (eci_designator >> 16).as_u16());
280                 self.push_number(16, (eci_designator & 0xffff).as_u16());
281             }
282             _ => return Err(QrError::InvalidEciDesignator),
283         }
284         Ok(())
285     }
286 }
287 
288 #[cfg(test)]
289 mod eci_tests {
290     use crate::bits::Bits;
291     use crate::types::{QrError, Version};
292 
293     #[test]
test_9()294     fn test_9() {
295         let mut bits = Bits::new(Version::Normal(1));
296         assert_eq!(bits.push_eci_designator(9), Ok(()));
297         assert_eq!(bits.into_bytes(), vec![0b0111__0000, 0b1001__0000]);
298     }
299 
300     #[test]
test_899()301     fn test_899() {
302         let mut bits = Bits::new(Version::Normal(1));
303         assert_eq!(bits.push_eci_designator(899), Ok(()));
304         assert_eq!(
305             bits.into_bytes(),
306             vec![0b0111__10_00, 0b00111000, 0b0011__0000]
307         );
308     }
309 
310     #[test]
test_999999()311     fn test_999999() {
312         let mut bits = Bits::new(Version::Normal(1));
313         assert_eq!(bits.push_eci_designator(999999), Ok(()));
314         assert_eq!(
315             bits.into_bytes(),
316             vec![0b0111__110_0, 0b11110100, 0b00100011, 0b1111__0000]
317         );
318     }
319 
320     #[test]
test_invalid_designator()321     fn test_invalid_designator() {
322         let mut bits = Bits::new(Version::Normal(1));
323         assert_eq!(
324             bits.push_eci_designator(1000000),
325             Err(QrError::InvalidEciDesignator)
326         );
327     }
328 
329     #[test]
test_unsupported_character_set()330     fn test_unsupported_character_set() {
331         let mut bits = Bits::new(Version::Micro(4));
332         assert_eq!(
333             bits.push_eci_designator(9),
334             Err(QrError::UnsupportedCharacterSet)
335         );
336     }
337 }
338 
339 //}}}
340 //------------------------------------------------------------------------------
341 //{{{ Mode::Numeric mode
342 
343 impl Bits {
push_header(&mut self, mode: Mode, raw_data_len: usize) -> QrResult<()>344     fn push_header(&mut self, mode: Mode, raw_data_len: usize) -> QrResult<()> {
345         let length_bits = mode.length_bits_count(self.version);
346         //println!("push_header length_bits:{} raw_data_len:{}", length_bits, raw_data_len);
347         self.reserve(length_bits + 4 + mode.data_bits_count(raw_data_len));
348         self.push_mode_indicator(ExtendedMode::Data(mode))?;
349         self.push_number_checked(length_bits, raw_data_len)?;
350         Ok(())
351     }
352 
353     /// Encodes a numeric string to the bits.
354     ///
355     /// The data should only contain the characters 0 to 9.
356     ///
357     /// # Errors
358     ///
359     /// Returns `Err(QrError::DataTooLong)` on overflow.
push_numeric_data(&mut self, data: &[u8]) -> QrResult<()>360     pub fn push_numeric_data(&mut self, data: &[u8]) -> QrResult<()> {
361         self.push_header(Mode::Numeric, data.len())?;
362         for chunk in data.chunks(3) {
363             let number = chunk
364                 .iter()
365                 .map(|b| u16::from(*b - b'0'))
366                 .fold(0, |a, b| a * 10 + b);
367             let length = chunk.len() * 3 + 1;
368             self.push_number(length, number);
369         }
370         Ok(())
371     }
372 }
373 
374 #[cfg(test)]
375 mod numeric_tests {
376     use crate::bits::Bits;
377     use crate::types::{QrError, Version};
378 
379     #[test]
test_iso_18004_2006_example_1()380     fn test_iso_18004_2006_example_1() {
381         let mut bits = Bits::new(Version::Normal(1));
382         assert_eq!(bits.push_numeric_data(b"01234567"), Ok(()));
383         assert_eq!(
384             bits.into_bytes(),
385             vec![
386                 0b0001_0000,
387                 0b001000_00,
388                 0b00001100,
389                 0b01010110,
390                 0b01_100001,
391                 0b1__0000000
392             ]
393         );
394     }
395 
396     #[test]
test_iso_18004_2000_example_2()397     fn test_iso_18004_2000_example_2() {
398         let mut bits = Bits::new(Version::Normal(1));
399         assert_eq!(bits.push_numeric_data(b"0123456789012345"), Ok(()));
400         assert_eq!(
401             bits.into_bytes(),
402             vec![
403                 0b0001_0000,
404                 0b010000_00,
405                 0b00001100,
406                 0b01010110,
407                 0b01_101010,
408                 0b0110_1110,
409                 0b000101_00,
410                 0b11101010,
411                 0b0101__0000,
412             ]
413         );
414     }
415 
416     #[test]
test_iso_18004_2006_example_2()417     fn test_iso_18004_2006_example_2() {
418         let mut bits = Bits::new(Version::Micro(3));
419         assert_eq!(bits.push_numeric_data(b"0123456789012345"), Ok(()));
420         assert_eq!(
421             bits.into_bytes(),
422             vec![
423                 0b00_10000_0,
424                 0b00000110,
425                 0b0_0101011,
426                 0b001_10101,
427                 0b00110_111,
428                 0b0000101_0,
429                 0b01110101,
430                 0b00101__000,
431             ]
432         );
433     }
434 
435     #[test]
test_data_too_long_error()436     fn test_data_too_long_error() {
437         let mut bits = Bits::new(Version::Micro(1));
438         assert_eq!(
439             bits.push_numeric_data(b"12345678"),
440             Err(QrError::DataTooLong)
441         );
442     }
443 }
444 
445 //}}}
446 //------------------------------------------------------------------------------
447 //{{{ Mode::Alphanumeric mode
448 
449 /// In QR code `Mode::Alphanumeric` mode, a pair of alphanumeric characters will
450 /// be encoded as a base-45 integer. `alphanumeric_digit` converts each
451 /// character into its corresponding base-45 digit.
452 ///
453 /// The conversion is specified in ISO/IEC 18004:2006, §8.4.3, Table 5.
454 #[inline]
alphanumeric_digit(character: u8) -> u16455 fn alphanumeric_digit(character: u8) -> u16 {
456     match character {
457         b'0'..=b'9' => u16::from(character - b'0'),
458         b'A'..=b'Z' => u16::from(character - b'A') + 10,
459         b' ' => 36,
460         b'$' => 37,
461         b'%' => 38,
462         b'*' => 39,
463         b'+' => 40,
464         b'-' => 41,
465         b'.' => 42,
466         b'/' => 43,
467         b':' => 44,
468         _ => 0,
469     }
470 }
471 
472 impl Bits {
473     /// Encodes an alphanumeric string to the bits.
474     ///
475     /// The data should only contain the charaters A to Z (excluding lowercase),
476     /// 0 to 9, space, `$`, `%`, `*`, `+`, `-`, `.`, `/` or `:`.
477     ///
478     /// # Errors
479     ///
480     /// Returns `Err(QrError::DataTooLong)` on overflow.
push_alphanumeric_data(&mut self, data: &[u8]) -> QrResult<()>481     pub fn push_alphanumeric_data(&mut self, data: &[u8]) -> QrResult<()> {
482         self.push_header(Mode::Alphanumeric, data.len())?;
483         for chunk in data.chunks(2) {
484             let number = chunk
485                 .iter()
486                 .map(|b| alphanumeric_digit(*b))
487                 .fold(0, |a, b| a * 45 + b);
488             let length = chunk.len() * 5 + 1;
489             self.push_number(length, number);
490         }
491         Ok(())
492     }
493 }
494 
495 #[cfg(test)]
496 mod alphanumeric_tests {
497     use crate::bits::Bits;
498     use crate::types::{QrError, Version};
499 
500     #[test]
test_iso_18004_2006_example()501     fn test_iso_18004_2006_example() {
502         let mut bits = Bits::new(Version::Normal(1));
503         assert_eq!(bits.push_alphanumeric_data(b"AC-42"), Ok(()));
504         assert_eq!(
505             bits.into_bytes(),
506             vec![
507                 0b0010_0000,
508                 0b00101_001,
509                 0b11001110,
510                 0b11100111,
511                 0b001_00001,
512                 0b0__0000000
513             ]
514         );
515     }
516 
517     #[test]
test_micro_qr_unsupported()518     fn test_micro_qr_unsupported() {
519         let mut bits = Bits::new(Version::Micro(1));
520         assert_eq!(
521             bits.push_alphanumeric_data(b"A"),
522             Err(QrError::UnsupportedCharacterSet)
523         );
524     }
525 
526     #[test]
test_data_too_long()527     fn test_data_too_long() {
528         let mut bits = Bits::new(Version::Micro(2));
529         assert_eq!(
530             bits.push_alphanumeric_data(b"ABCDEFGH"),
531             Err(QrError::DataTooLong)
532         );
533     }
534 }
535 
536 //}}}
537 //------------------------------------------------------------------------------
538 //{{{ Mode::Byte mode
539 
540 impl Bits {
541     /// Encodes 8-bit byte data to the bits.
542     ///
543     /// # Errors
544     ///
545     /// Returns `Err(QrError::DataTooLong)` on overflow.
push_byte_data(&mut self, data: &[u8]) -> QrResult<()>546     pub fn push_byte_data(&mut self, data: &[u8]) -> QrResult<()> {
547         self.push_header(Mode::Byte, data.len())?;
548         for b in data {
549             self.push_number(8, u16::from(*b));
550         }
551         Ok(())
552     }
553 }
554 
555 #[cfg(test)]
556 mod byte_tests {
557     use crate::bits::Bits;
558     use crate::types::{QrError, Version};
559 
560     #[test]
test()561     fn test() {
562         let mut bits = Bits::new(Version::Normal(1));
563         assert_eq!(
564             bits.push_byte_data(b"\x12\x34\x56\x78\x9a\xbc\xde\xf0"),
565             Ok(())
566         );
567         assert_eq!(
568             bits.into_bytes(),
569             vec![
570                 0b0100_0000,
571                 0b1000_0001,
572                 0b0010_0011,
573                 0b0100_0101,
574                 0b0110_0111,
575                 0b1000_1001,
576                 0b1010_1011,
577                 0b1100_1101,
578                 0b1110_1111,
579                 0b0000__0000,
580             ]
581         );
582     }
583 
584     #[test]
test_micro_qr_unsupported()585     fn test_micro_qr_unsupported() {
586         let mut bits = Bits::new(Version::Micro(2));
587         assert_eq!(
588             bits.push_byte_data(b"?"),
589             Err(QrError::UnsupportedCharacterSet)
590         );
591     }
592 
593     #[test]
test_data_too_long()594     fn test_data_too_long() {
595         let mut bits = Bits::new(Version::Micro(3));
596         assert_eq!(
597             bits.push_byte_data(b"0123456701234567"),
598             Err(QrError::DataTooLong)
599         );
600     }
601 }
602 
603 //}}}
604 //------------------------------------------------------------------------------
605 //{{{ Mode::Kanji mode
606 
607 impl Bits {
608     /// Encodes Shift JIS double-byte data to the bits.
609     ///
610     /// # Errors
611     ///
612     /// Returns `Err(QrError::DataTooLong)` on overflow.
613     ///
614     /// Returns `Err(QrError::InvalidCharacter)` if the data is not Shift JIS
615     /// double-byte data (e.g. if the length of data is not an even number).
push_kanji_data(&mut self, data: &[u8]) -> QrResult<()>616     pub fn push_kanji_data(&mut self, data: &[u8]) -> QrResult<()> {
617         self.push_header(Mode::Kanji, data.len() / 2)?;
618         for kanji in data.chunks(2) {
619             if kanji.len() != 2 {
620                 return Err(QrError::InvalidCharacter);
621             }
622             let cp = u16::from(kanji[0]) * 256 + u16::from(kanji[1]);
623             let bytes = if cp < 0xe040 {
624                 cp - 0x8140
625             } else {
626                 cp - 0xc140
627             };
628             let number = (bytes >> 8) * 0xc0 + (bytes & 0xff);
629             self.push_number(13, number);
630         }
631         Ok(())
632     }
633 }
634 
635 #[cfg(test)]
636 mod kanji_tests {
637     use crate::bits::Bits;
638     use crate::types::{QrError, Version};
639 
640     #[test]
test_iso_18004_example()641     fn test_iso_18004_example() {
642         let mut bits = Bits::new(Version::Normal(1));
643         assert_eq!(bits.push_kanji_data(b"\x93\x5f\xe4\xaa"), Ok(()));
644         assert_eq!(
645             bits.into_bytes(),
646             vec![
647                 0b1000_0000,
648                 0b0010_0110,
649                 0b11001111,
650                 0b1_1101010,
651                 0b101010__00
652             ]
653         );
654     }
655 
656     #[test]
test_micro_qr_unsupported()657     fn test_micro_qr_unsupported() {
658         let mut bits = Bits::new(Version::Micro(2));
659         assert_eq!(
660             bits.push_kanji_data(b"?"),
661             Err(QrError::UnsupportedCharacterSet)
662         );
663     }
664 
665     #[test]
test_data_too_long()666     fn test_data_too_long() {
667         let mut bits = Bits::new(Version::Micro(3));
668         assert_eq!(
669             bits.push_kanji_data(b"\x93_\x93_\x93_\x93_\x93_\x93_\x93_\x93_"),
670             Err(QrError::DataTooLong)
671         );
672     }
673 }
674 
675 //}}}
676 //------------------------------------------------------------------------------
677 //{{{ FNC1 mode
678 
679 impl Bits {
680     /// Encodes an indicator that the following data are formatted according to
681     /// the UCC/EAN Application Identifiers standard.
682     ///
683     ///     #![allow(unused_must_use)]
684     ///
685     ///     use qr_code::bits::Bits;
686     ///     use qr_code::types::Version;
687     ///
688     ///     let mut bits = Bits::new(Version::Normal(1));
689     ///     bits.push_fnc1_first_position();
690     ///     bits.push_numeric_data(b"01049123451234591597033130128");
691     ///     bits.push_alphanumeric_data(b"%10ABC123");
692     ///
693     /// In QR code, the character `%` is used as the data field separator (0x1D).
694     ///
695     /// # Errors
696     ///
697     /// If the mode is not supported in the provided version, this method
698     /// returns `Err(QrError::UnsupportedCharacterSet)`.
push_fnc1_first_position(&mut self) -> QrResult<()>699     pub fn push_fnc1_first_position(&mut self) -> QrResult<()> {
700         self.push_mode_indicator(ExtendedMode::Fnc1First)
701     }
702 
703     /// Encodes an indicator that the following data are formatted in accordance
704     /// with specific industry or application specifications previously agreed
705     /// with AIM International.
706     ///
707     ///     #![allow(unused_must_use)]
708     ///
709     ///     use qr_code::bits::Bits;
710     ///     use qr_code::types::Version;
711     ///
712     ///     let mut bits = Bits::new(Version::Normal(1));
713     ///     bits.push_fnc1_second_position(37);
714     ///     bits.push_alphanumeric_data(b"AA1234BBB112");
715     ///     bits.push_byte_data(b"text text text text\r");
716     ///
717     /// If the application indicator is a single Latin alphabet (a–z / A–Z),
718     /// please pass in its ASCII value + 100:
719     ///
720     /// ```ignore
721     /// bits.push_fnc1_second_position(b'A' + 100);
722     /// ```
723     ///
724     /// # Errors
725     ///
726     /// If the mode is not supported in the provided version, this method
727     /// returns `Err(QrError::UnsupportedCharacterSet)`.
push_fnc1_second_position(&mut self, application_indicator: u8) -> QrResult<()>728     pub fn push_fnc1_second_position(&mut self, application_indicator: u8) -> QrResult<()> {
729         self.push_mode_indicator(ExtendedMode::Fnc1Second)?;
730         self.push_number(8, u16::from(application_indicator));
731         Ok(())
732     }
733 }
734 
735 //}}}
736 //------------------------------------------------------------------------------
737 //{{{ Finish
738 
739 // This table is copied from ISO/IEC 18004:2006 §6.4.10, Table 7.
740 static DATA_LENGTHS: [[usize; 4]; 44] = [
741     // Normal versions
742     [152, 128, 104, 72],
743     [272, 224, 176, 128],
744     [440, 352, 272, 208],
745     [640, 512, 384, 288],
746     [864, 688, 496, 368],
747     [1088, 864, 608, 480],
748     [1248, 992, 704, 528],
749     [1552, 1232, 880, 688],
750     [1856, 1456, 1056, 800],
751     [2192, 1728, 1232, 976],
752     [2592, 2032, 1440, 1120],
753     [2960, 2320, 1648, 1264],
754     [3424, 2672, 1952, 1440],
755     [3688, 2920, 2088, 1576],
756     [4184, 3320, 2360, 1784],
757     [4712, 3624, 2600, 2024],
758     [5176, 4056, 2936, 2264],
759     [5768, 4504, 3176, 2504],
760     [6360, 5016, 3560, 2728],
761     [6888, 5352, 3880, 3080],
762     [7456, 5712, 4096, 3248],
763     [8048, 6256, 4544, 3536],
764     [8752, 6880, 4912, 3712],
765     [9392, 7312, 5312, 4112],
766     [10208, 8000, 5744, 4304],
767     [10960, 8496, 6032, 4768],
768     [11744, 9024, 6464, 5024],
769     [12248, 9544, 6968, 5288],
770     [13048, 10136, 7288, 5608],
771     [13880, 10984, 7880, 5960],
772     [14744, 11640, 8264, 6344],
773     [15640, 12328, 8920, 6760],
774     [16568, 13048, 9368, 7208],
775     [17528, 13800, 9848, 7688],
776     [18448, 14496, 10288, 7888],
777     [19472, 15312, 10832, 8432],
778     [20528, 15936, 11408, 8768],
779     [21616, 16816, 12016, 9136],
780     [22496, 17728, 12656, 9776],
781     [23648, 18672, 13328, 10208],
782     // Micro versions
783     [20, 0, 0, 0],
784     [40, 32, 0, 0],
785     [84, 68, 0, 0],
786     [128, 112, 80, 0],
787 ];
788 
789 impl Bits {
790     /// Pushes the ending bits to indicate no more data.
791     ///
792     /// # Errors
793     ///
794     /// Returns `Err(QrError::DataTooLong)` on overflow.
795     ///
796     /// Returns `Err(QrError::InvalidVersion)` if it is not valid to use the
797     /// `ec_level` for the given version (e.g. `Version::Micro(1)` with
798     /// `EcLevel::H`).
push_terminator(&mut self, ec_level: EcLevel) -> QrResult<()>799     pub fn push_terminator(&mut self, ec_level: EcLevel) -> QrResult<()> {
800         let terminator_size = match self.version {
801             Version::Micro(a) => a.as_usize() * 2 + 1,
802             _ => 4,
803         };
804 
805         let cur_length = self.len();
806         let data_length = self.max_len(ec_level)?;
807         if cur_length > data_length {
808             return Err(QrError::DataTooLong);
809         }
810 
811         let terminator_size = min(terminator_size, data_length - cur_length);
812         if terminator_size > 0 {
813             self.push_number(terminator_size, 0);
814         }
815 
816         if self.len() < data_length {
817             const PADDING_BYTES: &[u8] = &[0b1110_1100, 0b0001_0001];
818 
819             self.bit_offset = 0;
820             let data_bytes_length = data_length / 8;
821             let padding_bytes_count = data_bytes_length - self.data.len();
822             let padding = PADDING_BYTES
823                 .iter()
824                 .cloned()
825                 .cycle()
826                 .take(padding_bytes_count);
827             self.data.extend(padding);
828         }
829 
830         if self.len() < data_length {
831             self.data.push(0);
832         }
833 
834         Ok(())
835     }
836 }
837 
838 #[cfg(test)]
839 mod finish_tests {
840     use crate::bits::Bits;
841     use crate::types::{EcLevel, QrError, Version};
842 
843     #[test]
test_hello_world()844     fn test_hello_world() {
845         let mut bits = Bits::new(Version::Normal(1));
846         assert_eq!(bits.push_alphanumeric_data(b"HELLO WORLD"), Ok(()));
847         assert_eq!(bits.push_terminator(EcLevel::Q), Ok(()));
848         assert_eq!(
849             bits.into_bytes(),
850             vec![
851                 0b00100000, 0b01011011, 0b00001011, 0b01111000, 0b11010001, 0b01110010, 0b11011100,
852                 0b01001101, 0b01000011, 0b01000000, 0b11101100, 0b00010001, 0b11101100,
853             ]
854         );
855     }
856 
857     #[test]
test_too_long()858     fn test_too_long() {
859         let mut bits = Bits::new(Version::Micro(1));
860         assert_eq!(bits.push_numeric_data(b"9999999"), Ok(()));
861         assert_eq!(bits.push_terminator(EcLevel::L), Err(QrError::DataTooLong));
862     }
863 
864     #[test]
test_no_terminator()865     fn test_no_terminator() {
866         let mut bits = Bits::new(Version::Micro(1));
867         assert_eq!(bits.push_numeric_data(b"99999"), Ok(()));
868         assert_eq!(bits.push_terminator(EcLevel::L), Ok(()));
869         assert_eq!(
870             bits.into_bytes(),
871             vec![0b101_11111, 0b00111_110, 0b0011__0000]
872         );
873     }
874 
875     #[test]
test_no_padding()876     fn test_no_padding() {
877         let mut bits = Bits::new(Version::Micro(1));
878         assert_eq!(bits.push_numeric_data(b"9999"), Ok(()));
879         assert_eq!(bits.push_terminator(EcLevel::L), Ok(()));
880         assert_eq!(
881             bits.into_bytes(),
882             vec![0b100_11111, 0b00111_100, 0b1_000__0000]
883         );
884     }
885 
886     #[test]
test_micro_version_1_half_byte_padding()887     fn test_micro_version_1_half_byte_padding() {
888         let mut bits = Bits::new(Version::Micro(1));
889         assert_eq!(bits.push_numeric_data(b"999"), Ok(()));
890         assert_eq!(bits.push_terminator(EcLevel::L), Ok(()));
891         assert_eq!(
892             bits.into_bytes(),
893             vec![0b011_11111, 0b00111_000, 0b0000__0000]
894         );
895     }
896 
897     #[test]
test_micro_version_1_full_byte_padding()898     fn test_micro_version_1_full_byte_padding() {
899         let mut bits = Bits::new(Version::Micro(1));
900         assert_eq!(bits.push_numeric_data(b""), Ok(()));
901         assert_eq!(bits.push_terminator(EcLevel::L), Ok(()));
902         assert_eq!(bits.into_bytes(), vec![0b000_000_00, 0b11101100, 0]);
903     }
904 }
905 
906 //}}}
907 //------------------------------------------------------------------------------
908 //{{{ Front end.
909 
910 impl Bits {
911     /// Push a segmented data to the bits, and then terminate it.
912     ///
913     /// # Errors
914     ///
915     /// Returns `Err(QrError::DataTooLong)` on overflow.
916     ///
917     /// Returns `Err(QrError::InvalidData)` if the segment refers to incorrectly
918     /// encoded byte sequence.
push_segments<I>(&mut self, data: &[u8], segments_iter: I) -> QrResult<()> where I: Iterator<Item = Segment>,919     pub fn push_segments<I>(&mut self, data: &[u8], segments_iter: I) -> QrResult<()>
920     where
921         I: Iterator<Item = Segment>,
922     {
923         for segment in segments_iter {
924             let slice = &data[segment.begin..segment.end];
925             match segment.mode {
926                 Mode::Numeric => self.push_numeric_data(slice),
927                 Mode::Alphanumeric => self.push_alphanumeric_data(slice),
928                 Mode::Byte => self.push_byte_data(slice),
929                 Mode::Kanji => self.push_kanji_data(slice),
930             }?;
931         }
932         Ok(())
933     }
934 
935     /// Pushes the data the bits, using the optimal encoding.
936     ///
937     /// # Errors
938     ///
939     /// Returns `Err(QrError::DataTooLong)` on overflow.
push_optimal_data(&mut self, data: &[u8]) -> QrResult<()>940     pub fn push_optimal_data(&mut self, data: &[u8]) -> QrResult<()> {
941         let segments: Vec<Segment> = Parser::new(data).collect();
942         let segments = optimize_segmentation(&segments, self.version);
943         self.push_segments(data, segments.into_iter())
944     }
945 }
946 
947 #[cfg(test)]
948 mod encode_tests {
949     use crate::bits::Bits;
950     use crate::types::{EcLevel, QrError, QrResult, Version};
951 
encode(data: &[u8], version: Version, ec_level: EcLevel) -> QrResult<Vec<u8>>952     fn encode(data: &[u8], version: Version, ec_level: EcLevel) -> QrResult<Vec<u8>> {
953         let mut bits = Bits::new(version);
954         bits.push_optimal_data(data)?;
955         bits.push_terminator(ec_level)?;
956         Ok(bits.into_bytes())
957     }
958 
959     #[test]
test_alphanumeric()960     fn test_alphanumeric() {
961         let res = encode(b"HELLO WORLD", Version::Normal(1), EcLevel::Q);
962         assert_eq!(
963             res,
964             Ok(vec![
965                 0b00100000, 0b01011011, 0b00001011, 0b01111000, 0b11010001, 0b01110010, 0b11011100,
966                 0b01001101, 0b01000011, 0b01000000, 0b11101100, 0b00010001, 0b11101100,
967             ])
968         );
969     }
970 
971     #[test]
test_auto_mode_switch()972     fn test_auto_mode_switch() {
973         let res = encode(b"123A", Version::Micro(2), EcLevel::L);
974         assert_eq!(
975             res,
976             Ok(vec![
977                 0b0_0011_000,
978                 0b1111011_1,
979                 0b001_00101,
980                 0b0_00000__00,
981                 0b11101100
982             ])
983         );
984     }
985 
986     #[test]
test_too_long()987     fn test_too_long() {
988         let res = encode(b">>>>>>>>", Version::Normal(1), EcLevel::H);
989         assert_eq!(res, Err(QrError::DataTooLong));
990     }
991 }
992 
993 //}}}
994 //------------------------------------------------------------------------------
995 //{{{ Auto version minimization
996 
997 /// Automatically determines the minimum version to store the data, and encode
998 /// the result.
999 ///
1000 /// This method will not consider any Micro QR code versions.
1001 ///
1002 /// # Errors
1003 ///
1004 /// Returns `Err(QrError::DataTooLong)` if the data is too long to fit even the
1005 /// highest QR code version.
encode_auto(data: &[u8], ec_level: EcLevel) -> QrResult<Bits>1006 pub fn encode_auto(data: &[u8], ec_level: EcLevel) -> QrResult<Bits> {
1007     let mut segments = None;
1008     for version in &[Version::Normal(9), Version::Normal(26), Version::Normal(40)] {
1009         let data_capacity = version
1010             .fetch(ec_level, &DATA_LENGTHS)
1011             .expect("invalid DATA_LENGTHS");
1012         let best_case_len = {
1013             let only_digits = Segment {
1014                 mode: Mode::Numeric,
1015                 begin: 0,
1016                 end: data.len(),
1017             };
1018             only_digits.encoded_len(*version)
1019         };
1020         if best_case_len <= data_capacity {
1021             let segments =
1022                 segments.get_or_insert_with(|| Parser::new(data).collect::<Vec<Segment>>());
1023             let opt_segments = optimize_segmentation(segments.as_slice(), *version);
1024             let total_len = total_encoded_len(&*opt_segments, *version);
1025             if total_len <= data_capacity {
1026                 let min_version = find_min_version(total_len, ec_level);
1027                 let mut bits = Bits::new(min_version);
1028                 bits.reserve(total_len);
1029                 bits.push_segments(data, opt_segments.into_iter())?;
1030                 bits.push_terminator(ec_level)?;
1031                 return Ok(bits);
1032             }
1033         }
1034     }
1035     Err(QrError::DataTooLong)
1036 }
1037 
1038 /// Finds the smallest version (QR code only) that can store N bits of data
1039 /// in the given error correction level.
find_min_version(length: usize, ec_level: EcLevel) -> Version1040 fn find_min_version(length: usize, ec_level: EcLevel) -> Version {
1041     let mut base = 0_usize;
1042     let mut size = 39;
1043     while size > 1 {
1044         let half = size / 2;
1045         let mid = base + half;
1046         // mid is always in [0, size).
1047         // mid >= 0: by definition
1048         // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1049         base = if DATA_LENGTHS[mid][ec_level as usize] > length {
1050             base
1051         } else {
1052             mid
1053         };
1054         size -= half;
1055     }
1056     // base is always in [0, mid) because base <= mid.
1057     base = if DATA_LENGTHS[base][ec_level as usize] >= length {
1058         base
1059     } else {
1060         base + 1
1061     };
1062     Version::Normal((base + 1).as_i16())
1063 }
1064 
1065 #[cfg(test)]
1066 mod encode_auto_tests {
1067     use crate::bits::{encode_auto, find_min_version};
1068     use crate::types::{EcLevel, Version};
1069 
1070     #[test]
test_find_min_version()1071     fn test_find_min_version() {
1072         assert_eq!(find_min_version(60, EcLevel::L), Version::Normal(1));
1073         assert_eq!(find_min_version(200, EcLevel::L), Version::Normal(2));
1074         assert_eq!(find_min_version(200, EcLevel::H), Version::Normal(3));
1075         assert_eq!(find_min_version(20000, EcLevel::L), Version::Normal(37));
1076         assert_eq!(find_min_version(640, EcLevel::L), Version::Normal(4));
1077         assert_eq!(find_min_version(641, EcLevel::L), Version::Normal(5));
1078         assert_eq!(find_min_version(999999, EcLevel::H), Version::Normal(40));
1079     }
1080 
1081     #[test]
test_alpha_q()1082     fn test_alpha_q() {
1083         let bits = encode_auto(b"HELLO WORLD", EcLevel::Q).unwrap();
1084         assert_eq!(bits.version(), Version::Normal(1));
1085     }
1086 
1087     #[test]
test_alpha_h()1088     fn test_alpha_h() {
1089         let bits = encode_auto(b"HELLO WORLD", EcLevel::H).unwrap();
1090         assert_eq!(bits.version(), Version::Normal(2));
1091     }
1092 
1093     #[test]
test_mixed()1094     fn test_mixed() {
1095         let bits = encode_auto(b"This is a mixed data test. 1234567890", EcLevel::H).unwrap();
1096         assert_eq!(bits.version(), Version::Normal(4));
1097     }
1098 }
1099 
1100 #[cfg(bench)]
1101 #[bench]
bench_find_min_version(bencher: &mut test::Bencher)1102 fn bench_find_min_version(bencher: &mut test::Bencher) {
1103     use test::black_box;
1104 
1105     bencher.iter(|| {
1106         black_box(find_min_version(60, EcLevel::L));
1107         black_box(find_min_version(200, EcLevel::L));
1108         black_box(find_min_version(200, EcLevel::H));
1109         black_box(find_min_version(20000, EcLevel::L));
1110         black_box(find_min_version(640, EcLevel::L));
1111         black_box(find_min_version(641, EcLevel::L));
1112         black_box(find_min_version(999999, EcLevel::H));
1113     })
1114 }
1115 
1116 //}}}
1117 //------------------------------------------------------------------------------
1118