qrcode-core 2.0.0

Zero-dependency QR code encoding core (no_std + alloc) — the encoding primitive layer of qrcode-rs.
Documentation
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
#![allow(clippy::unreadable_literal, clippy::unusual_byte_groupings)]
//! Bit-level data encoding for QR codes.
//!
//! This module handles the conversion of raw input data into the bit stream
//! that gets placed onto the QR code canvas. It supports all four data modes:
//!
//! - **Numeric** — digits 0-9 (most efficient)
//! - **Alphanumeric** — uppercase letters, digits, and a few symbols
//! - **Byte** — arbitrary 8-bit data (including UTF-8)
//! - **Kanji** — Shift JIS encoded double-byte characters
//!
//! The [`Bits`] struct is the main entry point. Use [`encode_auto`] or
//! [`encode_auto_micro`] for automatic version and mode selection, or
//! construct a [`Bits`] manually for advanced use cases like ECI designators
//! or FNC1 patterns.

#[cfg(not(feature = "std"))]
#[allow(unused_imports)]
use alloc::{
    borrow::ToOwned,
    format,
    string::{String, ToString},
    vec,
    vec::Vec,
};

use core::cmp::min;

use crate::cast::{As, Truncate};
use crate::mode::EncodingMode;
use crate::optimize::{Optimizer, Parser, Segment, total_encoded_len};
use crate::types::{EcLevel, Mode, QrError, QrResult, Version};

//------------------------------------------------------------------------------
//{{{ Bits

/// The `Bits` structure stores the encoded data for a QR code.
pub struct Bits {
    data: Vec<u8>,
    bit_offset: usize,
    version: Version,
}

impl Bits {
    /// Constructs a new, empty bits structure.
    pub const fn new(version: Version) -> Self {
        Self { data: Vec::new(), bit_offset: 0, version }
    }

    /// Pushes an N-bit big-endian integer to the end of the bits.
    ///
    /// Note: It is up to the developer to ensure that `number` really only is
    /// `n` bit in size. Otherwise, the excess bits may stomp on the existing
    /// ones.
    fn push_number(&mut self, n: usize, number: u16) {
        debug_assert!(n == 16 || n < 16 && number < (1 << n), "{number} is too big as a {n}-bit number");

        let b = self.bit_offset + n;
        let last_index = self.data.len().wrapping_sub(1);
        match (self.bit_offset, b) {
            (0, 0..=8) => {
                self.data.push((number << (8 - b)).truncate_as_u8());
            }
            (0, _) => {
                self.data.push((number >> (b - 8)).truncate_as_u8());
                self.data.push((number << (16 - b)).truncate_as_u8());
            }
            (_, 0..=8) => {
                self.data[last_index] |= (number << (8 - b)).truncate_as_u8();
            }
            (_, 9..=16) => {
                self.data[last_index] |= (number >> (b - 8)).truncate_as_u8();
                self.data.push((number << (16 - b)).truncate_as_u8());
            }
            _ => {
                self.data[last_index] |= (number >> (b - 8)).truncate_as_u8();
                self.data.push((number >> (b - 16)).truncate_as_u8());
                self.data.push((number << (24 - b)).truncate_as_u8());
            }
        }
        self.bit_offset = b & 7;
    }

    /// Pushes an N-bit big-endian integer to the end of the bits, and check
    /// that the number does not overflow the bits.
    ///
    /// Returns `Err(QrError::DataTooLong)` on overflow.
    pub fn push_number_checked(&mut self, n: usize, number: usize) -> QrResult<()> {
        if n > 16 || number >= (1 << n) {
            Err(QrError::DataTooLong)
        } else {
            self.push_number(n, number.as_u16());
            Ok(())
        }
    }

    /// Reserves `n` extra bits of space for pushing.
    pub fn reserve(&mut self, n: usize) {
        let extra_bytes = (n + (8 - self.bit_offset) % 8) / 8;
        self.data.reserve(extra_bytes);
    }

    /// Convert the bits into a byte vector.
    pub fn into_bytes(self) -> Vec<u8> {
        self.data
    }

    /// Total number of bits currently pushed.
    pub fn len(&self) -> usize {
        if self.bit_offset == 0 { self.data.len() * 8 } else { (self.data.len() - 1) * 8 + self.bit_offset }
    }

    /// Whether there are any bits pushed.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// The maximum number of bits allowed by the provided QR code version and
    /// error correction level.
    ///
    /// # Errors
    ///
    /// Returns `Err(QrError::InvalidVersion)` if it is not valid to use the
    /// `ec_level` for the given version (e.g. `Version::Micro(1)` with
    /// `EcLevel::H`).
    pub fn max_len(&self, ec_level: EcLevel) -> QrResult<usize> {
        self.version.fetch(ec_level, &DATA_LENGTHS)
    }

    /// Version of the QR code.
    pub fn version(&self) -> Version {
        self.version
    }
}

#[test]
fn test_push_number() {
    let mut bits = Bits::new(Version::Normal(1));

    bits.push_number(3, 0b010); // 0:0 .. 0:3
    bits.push_number(3, 0b110); // 0:3 .. 0:6
    bits.push_number(3, 0b101); // 0:6 .. 1:1
    bits.push_number(7, 0b001_1010); // 1:1 .. 2:0
    bits.push_number(4, 0b1100); // 2:0 .. 2:4
    bits.push_number(12, 0b1011_0110_1101); // 2:4 .. 4:0
    bits.push_number(10, 0b01_1001_0001); // 4:0 .. 5:2
    bits.push_number(15, 0b111_0010_1110_0011); // 5:2 .. 7:1

    let bytes = bits.into_bytes();

    assert_eq!(
        bytes,
        vec![
            0b010_110_10, // 90
            0b1_001_1010, // 154
            0b1100_1011,  // 203
            0b0110_1101,  // 109
            0b01_1001_00, // 100
            0b01_111_001, // 121
            0b0_1110_001, // 113
            0b1_0000000,  // 128
        ]
    );
}

//}}}
//------------------------------------------------------------------------------
//{{{ Mode indicator

/// An "extended" mode indicator, includes all indicators supported by QR code
/// beyond those bearing data.
#[derive(Copy, Clone)]
pub enum ExtendedMode {
    /// ECI mode indicator, to introduce an ECI designator.
    Eci,

    /// The normal mode to introduce data.
    Data(Mode),

    /// FNC-1 mode in the first position.
    Fnc1First,

    /// FNC-1 mode in the second position.
    Fnc1Second,

    /// Structured append.
    StructuredAppend,
}

impl Bits {
    /// Push the mode indicator to the end of the bits.
    ///
    /// # Errors
    ///
    /// If the mode is not supported in the provided version, this method
    /// returns `Err(QrError::UnsupportedCharacterSet)`.
    pub fn push_mode_indicator(&mut self, mode: ExtendedMode) -> QrResult<()> {
        #[allow(clippy::match_same_arms)]
        let number = match (self.version, mode) {
            (Version::Micro(1), ExtendedMode::Data(Mode::Numeric)) => return Ok(()),
            (Version::Micro(_), ExtendedMode::Data(Mode::Numeric)) => 0,
            (Version::Micro(_), ExtendedMode::Data(Mode::Alphanumeric)) => 1,
            (Version::Micro(_), ExtendedMode::Data(Mode::Byte)) => 0b10,
            (Version::Micro(_), ExtendedMode::Data(Mode::Kanji)) => 0b11,
            (Version::Micro(_), _) => return Err(QrError::UnsupportedCharacterSet),
            (_, ExtendedMode::Data(Mode::Numeric)) => 0b0001,
            (_, ExtendedMode::Data(Mode::Alphanumeric)) => 0b0010,
            (_, ExtendedMode::Data(Mode::Byte)) => 0b0100,
            (_, ExtendedMode::Data(Mode::Kanji)) => 0b1000,
            (_, ExtendedMode::Eci) => 0b0111,
            (_, ExtendedMode::Fnc1First) => 0b0101,
            (_, ExtendedMode::Fnc1Second) => 0b1001,
            (_, ExtendedMode::StructuredAppend) => 0b0011,
        };
        let bits = self.version.mode_bits_count();
        self.push_number_checked(bits, number).or(Err(QrError::UnsupportedCharacterSet))
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ ECI

impl Bits {
    /// Push an ECI (Extended Channel Interpretation) designator to the bits.
    ///
    /// An ECI designator is a 6-digit number to specify the character set of
    /// the following binary data. After calling this method, one could call
    /// `.push_byte_data()` or similar methods to insert the actual data, e.g.
    ///
    ///     #![allow(unused_must_use)]
    ///
    ///     use qrcode_core::bits::Bits;
    ///     use qrcode_core::types::Version;
    ///
    ///     let mut bits = Bits::new(Version::Normal(1));
    ///     bits.push_eci_designator(9); // 9 = ISO-8859-7 (Greek).
    ///     bits.push_byte_data(b"\xa1\xa2\xa3\xa4\xa5"); // ΑΒΓΔΕ
    ///
    ///
    /// The full list of ECI designator values can be found from
    /// <http://strokescribe.com/en/ECI.html>. Some example values are:
    ///
    /// ECI # | Character set
    /// ------|-------------------------------------
    /// 3     | ISO-8859-1 (Western European)
    /// 20    | Shift JIS (Japanese)
    /// 23    | Windows 1252 (Latin 1) (Western European)
    /// 25    | UTF-16 Big Endian
    /// 26    | UTF-8
    /// 28    | Big 5 (Traditional Chinese)
    /// 29    | GB-18030 (Simplified Chinese)
    /// 30    | EUC-KR (Korean)
    ///
    /// # Errors
    ///
    /// If the QR code version does not support ECI, this method will return
    /// `Err(QrError::UnsupportedCharacterSet)`.
    ///
    /// If the designator is outside the expected range, this method will
    /// return `Err(QrError::InvalidECIDesignator)`.
    pub fn push_eci_designator(&mut self, eci_designator: u32) -> QrResult<()> {
        self.reserve(12); // assume the common case that eci_designator <= 127.
        self.push_mode_indicator(ExtendedMode::Eci)?;
        match eci_designator {
            0..=127 => {
                self.push_number(8, eci_designator.as_u16());
            }
            128..=16383 => {
                self.push_number(2, 0b10);
                self.push_number(14, eci_designator.as_u16());
            }
            16384..=999_999 => {
                self.push_number(3, 0b110);
                self.push_number(5, (eci_designator >> 16).as_u16());
                self.push_number(16, (eci_designator & 0xffff).as_u16());
            }
            _ => return Err(QrError::InvalidEciDesignator { value: eci_designator }),
        }
        Ok(())
    }
}

#[cfg(test)]
mod eci_tests {
    use crate::bits::Bits;
    use crate::types::{QrError, Version};

    #[test]
    fn test_9() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_eci_designator(9), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b0111_0000, 0b1001_0000]);
    }

    #[test]
    fn test_899() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_eci_designator(899), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b0111_10_00, 0b00111000, 0b0011_0000]);
    }

    #[test]
    fn test_999999() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_eci_designator(999999), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b0111_110_0, 0b11110100, 0b00100011, 0b1111_0000]);
    }

    #[test]
    fn test_invalid_designator() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_eci_designator(1000000), Err(QrError::InvalidEciDesignator { value: 1000000 }));
    }

    #[test]
    fn test_unsupported_character_set() {
        let mut bits = Bits::new(Version::Micro(4));
        assert_eq!(bits.push_eci_designator(9), Err(QrError::UnsupportedCharacterSet));
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Mode::Numeric mode

impl Bits {
    fn push_header(&mut self, mode: Mode, raw_data_len: usize) -> QrResult<()> {
        let length_bits = mode.length_bits_count(self.version);
        self.reserve(length_bits + 4 + mode.data_bits_count(raw_data_len));
        self.push_mode_indicator(ExtendedMode::Data(mode))?;
        self.push_number_checked(length_bits, raw_data_len)?;
        Ok(())
    }

    /// Encodes a numeric string to the bits.
    ///
    /// The data should only contain the characters 0 to 9.
    ///
    /// # Errors
    ///
    /// Returns `Err(QrError::DataTooLong)` on overflow.
    pub fn push_numeric_data(&mut self, data: &[u8]) -> QrResult<()> {
        self.push_header(Mode::Numeric, data.len())?;
        for chunk in data.chunks(3) {
            let number = chunk.iter().map(|b| u16::from(*b - b'0')).fold(0, |a, b| a * 10 + b);
            let length = chunk.len() * 3 + 1;
            self.push_number(length, number);
        }
        Ok(())
    }
}

#[cfg(test)]
mod numeric_tests {
    use crate::bits::Bits;
    use crate::types::{QrError, Version};

    #[test]
    fn test_iso_18004_2006_example_1() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_numeric_data(b"01234567"), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b0001_0000, 0b001000_00, 0b00001100, 0b01010110, 0b01_100001, 0b1_0000000]);
    }

    #[test]
    fn test_iso_18004_2000_example_2() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_numeric_data(b"0123456789012345"), Ok(()));
        assert_eq!(
            bits.into_bytes(),
            vec![
                0b0001_0000,
                0b010000_00,
                0b00001100,
                0b01010110,
                0b01_101010,
                0b0110_1110,
                0b000101_00,
                0b11101010,
                0b0101_0000,
            ]
        );
    }

    #[test]
    fn test_iso_18004_2006_example_2() {
        let mut bits = Bits::new(Version::Micro(3));
        assert_eq!(bits.push_numeric_data(b"0123456789012345"), Ok(()));
        assert_eq!(
            bits.into_bytes(),
            vec![0b00_10000_0, 0b00000110, 0b0_0101011, 0b001_10101, 0b00110_111, 0b0000101_0, 0b01110101, 0b00101_000,]
        );
    }

    #[test]
    fn test_data_too_long_error() {
        let mut bits = Bits::new(Version::Micro(1));
        assert_eq!(bits.push_numeric_data(b"12345678"), Err(QrError::DataTooLong));
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Mode::Alphanumeric mode

/// In QR code `Mode::Alphanumeric` mode, a pair of alphanumeric characters will
/// be encoded as a base-45 integer. `alphanumeric_digit` converts each
/// character into its corresponding base-45 digit.
///
/// The conversion is specified in ISO/IEC 18004:2006, §8.4.3, Table 5.
#[inline]
fn alphanumeric_digit(character: u8) -> u16 {
    match character {
        b'0'..=b'9' => u16::from(character - b'0'),
        b'A'..=b'Z' => u16::from(character - b'A') + 10,
        b' ' => 36,
        b'$' => 37,
        b'%' => 38,
        b'*' => 39,
        b'+' => 40,
        b'-' => 41,
        b'.' => 42,
        b'/' => 43,
        b':' => 44,
        _ => 0,
    }
}

impl Bits {
    /// Encodes an alphanumeric string to the bits.
    ///
    /// The data should only contain the characters A to Z (excluding lowercase),
    /// 0 to 9, space, `$`, `%`, `*`, `+`, `-`, `.`, `/` or `:`.
    ///
    /// # Errors
    ///
    /// Returns `Err(QrError::DataTooLong)` on overflow.
    pub fn push_alphanumeric_data(&mut self, data: &[u8]) -> QrResult<()> {
        self.push_header(Mode::Alphanumeric, data.len())?;
        for chunk in data.chunks(2) {
            let number = chunk.iter().map(|b| alphanumeric_digit(*b)).fold(0, |a, b| a * 45 + b);
            let length = chunk.len() * 5 + 1;
            self.push_number(length, number);
        }
        Ok(())
    }
}

#[cfg(test)]
mod alphanumeric_tests {
    use crate::bits::Bits;
    use crate::types::{QrError, Version};

    #[test]
    fn test_iso_18004_2006_example() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_alphanumeric_data(b"AC-42"), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b0010_0000, 0b00101_001, 0b11001110, 0b11100111, 0b001_00001, 0b0_0000000]);
    }

    #[test]
    fn test_micro_qr_unsupported() {
        let mut bits = Bits::new(Version::Micro(1));
        assert_eq!(bits.push_alphanumeric_data(b"A"), Err(QrError::UnsupportedCharacterSet));
    }

    #[test]
    fn test_data_too_long() {
        let mut bits = Bits::new(Version::Micro(2));
        assert_eq!(bits.push_alphanumeric_data(b"ABCDEFGH"), Err(QrError::DataTooLong));
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Mode::Byte mode

impl Bits {
    /// Encodes 8-bit byte data to the bits.
    ///
    /// # Errors
    ///
    /// Returns `Err(QrError::DataTooLong)` on overflow.
    pub fn push_byte_data(&mut self, data: &[u8]) -> QrResult<()> {
        self.push_header(Mode::Byte, data.len())?;
        for b in data {
            self.push_number(8, u16::from(*b));
        }
        Ok(())
    }
}

#[cfg(test)]
mod byte_tests {
    use crate::bits::Bits;
    use crate::types::{QrError, Version};

    #[test]
    fn test() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_byte_data(b"\x12\x34\x56\x78\x9a\xbc\xde\xf0"), Ok(()));
        assert_eq!(
            bits.into_bytes(),
            vec![
                0b0100_0000,
                0b1000_0001,
                0b0010_0011,
                0b0100_0101,
                0b0110_0111,
                0b1000_1001,
                0b1010_1011,
                0b1100_1101,
                0b1110_1111,
                0b0000_0000,
            ]
        );
    }

    #[test]
    fn test_micro_qr_unsupported() {
        let mut bits = Bits::new(Version::Micro(2));
        assert_eq!(bits.push_byte_data(b"?"), Err(QrError::UnsupportedCharacterSet));
    }

    #[test]
    fn test_data_too_long() {
        let mut bits = Bits::new(Version::Micro(3));
        assert_eq!(bits.push_byte_data(b"0123456701234567"), Err(QrError::DataTooLong));
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Mode::Kanji mode

impl Bits {
    /// Encodes Shift JIS double-byte data to the bits.
    ///
    /// # Errors
    ///
    /// Returns `Err(QrError::DataTooLong)` on overflow.
    ///
    /// Returns `Err(QrError::InvalidCharacter)` if the data is not Shift JIS
    /// double-byte data (e.g. if the length of data is not an even number).
    pub fn push_kanji_data(&mut self, data: &[u8]) -> QrResult<()> {
        self.push_header(Mode::Kanji, data.len() / 2)?;
        for (i, kanji) in data.chunks(2).enumerate() {
            if kanji.len() != 2 {
                return Err(QrError::InvalidCharacter { position: i * 2, byte: kanji[0] });
            }
            let cp = u16::from(kanji[0]) * 256 + u16::from(kanji[1]);
            let bytes = if cp < 0xe040 { cp - 0x8140 } else { cp - 0xc140 };
            let number = (bytes >> 8) * 0xc0 + (bytes & 0xff);
            self.push_number(13, number);
        }
        Ok(())
    }
}

impl Bits {
    /// Encodes data with a type-level QR encoding mode.
    ///
    /// This is the type-safe counterpart to calling one of
    /// [`push_numeric_data`](Self::push_numeric_data),
    /// [`push_alphanumeric_data`](Self::push_alphanumeric_data),
    /// [`push_byte_data`](Self::push_byte_data), or
    /// [`push_kanji_data`](Self::push_kanji_data) directly.
    ///
    /// # Errors
    ///
    /// Returns [`QrError::InvalidCharacter`] when `data` is not valid for `M`.
    /// Returns the same length or version errors as the mode-specific push
    /// method after validation succeeds.
    pub fn push_mode_data<M: EncodingMode>(&mut self, data: &[u8]) -> QrResult<()> {
        if let Some((position, byte)) = M::invalid_character(data) {
            return Err(QrError::InvalidCharacter { position, byte });
        }

        match M::MODE {
            Mode::Numeric => self.push_numeric_data(data),
            Mode::Alphanumeric => self.push_alphanumeric_data(data),
            Mode::Byte => self.push_byte_data(data),
            Mode::Kanji => self.push_kanji_data(data),
        }
    }
}

#[cfg(test)]
mod typed_mode_tests {
    use crate::bits::Bits;
    use crate::mode::{AlphanumericMode, ByteMode, KanjiMode, NumericMode};
    use crate::types::{QrError, Version};

    #[test]
    fn push_mode_data_matches_numeric_specific_encoder() {
        let mut typed = Bits::new(Version::Normal(1));
        let mut direct = Bits::new(Version::Normal(1));

        assert_eq!(typed.push_mode_data::<NumericMode>(b"01234567"), Ok(()));
        assert_eq!(direct.push_numeric_data(b"01234567"), Ok(()));
        assert_eq!(typed.into_bytes(), direct.into_bytes());
    }

    #[test]
    fn push_mode_data_matches_other_specific_encoders() {
        let mut alphanumeric = Bits::new(Version::Normal(1));
        let mut byte = Bits::new(Version::Normal(1));
        let mut kanji = Bits::new(Version::Normal(1));

        assert_eq!(alphanumeric.push_mode_data::<AlphanumericMode>(b"AC-42"), Ok(()));
        assert_eq!(byte.push_mode_data::<ByteMode>(b"\x12\x34"), Ok(()));
        assert_eq!(kanji.push_mode_data::<KanjiMode>(b"\x93\x5f\xe4\xaa"), Ok(()));
    }

    #[test]
    fn push_mode_data_rejects_invalid_mode_input_before_writing() {
        let mut bits = Bits::new(Version::Normal(1));

        assert_eq!(
            bits.push_mode_data::<NumericMode>(b"12a"),
            Err(QrError::InvalidCharacter { position: 2, byte: b'a' })
        );
        assert!(bits.into_bytes().is_empty());
    }
}

#[cfg(test)]
mod kanji_tests {
    use crate::bits::Bits;
    use crate::types::{QrError, Version};

    #[test]
    fn test_iso_18004_example() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_kanji_data(b"\x93\x5f\xe4\xaa"), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b1000_0000, 0b0010_0110, 0b11001111, 0b1_1101010, 0b101010_00]);
    }

    #[test]
    fn test_micro_qr_unsupported() {
        let mut bits = Bits::new(Version::Micro(2));
        assert_eq!(bits.push_kanji_data(b"?"), Err(QrError::UnsupportedCharacterSet));
    }

    #[test]
    fn test_data_too_long() {
        let mut bits = Bits::new(Version::Micro(3));
        assert_eq!(bits.push_kanji_data(b"\x93_\x93_\x93_\x93_\x93_\x93_\x93_\x93_"), Err(QrError::DataTooLong));
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ FNC1 mode

impl Bits {
    /// Encodes an indicator that the following data are formatted according to
    /// the UCC/EAN Application Identifiers standard.
    ///
    ///     #![allow(unused_must_use)]
    ///
    ///     use qrcode_core::bits::Bits;
    ///     use qrcode_core::types::Version;
    ///
    ///     let mut bits = Bits::new(Version::Normal(1));
    ///     bits.push_fnc1_first_position();
    ///     bits.push_numeric_data(b"01049123451234591597033130128");
    ///     bits.push_alphanumeric_data(b"%10ABC123");
    ///
    /// In QR code, the character `%` is used as the data field separator (0x1D).
    ///
    /// # Errors
    ///
    /// If the mode is not supported in the provided version, this method
    /// returns `Err(QrError::UnsupportedCharacterSet)`.
    pub fn push_fnc1_first_position(&mut self) -> QrResult<()> {
        self.push_mode_indicator(ExtendedMode::Fnc1First)
    }

    /// Encodes an indicator that the following data are formatted in accordance
    /// with specific industry or application specifications previously agreed
    /// with AIM International.
    ///
    ///     #![allow(unused_must_use)]
    ///
    ///     use qrcode_core::bits::Bits;
    ///     use qrcode_core::types::Version;
    ///
    ///     let mut bits = Bits::new(Version::Normal(1));
    ///     bits.push_fnc1_second_position(37);
    ///     bits.push_alphanumeric_data(b"AA1234BBB112");
    ///     bits.push_byte_data(b"text text text text\r");
    ///
    /// If the application indicator is a single Latin alphabet (a–z / A–Z),
    /// please pass in its ASCII value + 100:
    ///
    /// ```ignore
    /// bits.push_fnc1_second_position(b'A' + 100);
    /// ```
    ///
    /// # Errors
    ///
    /// If the mode is not supported in the provided version, this method
    /// returns `Err(QrError::UnsupportedCharacterSet)`.
    pub fn push_fnc1_second_position(&mut self, application_indicator: u8) -> QrResult<()> {
        self.push_mode_indicator(ExtendedMode::Fnc1Second)?;
        self.push_number(8, u16::from(application_indicator));
        Ok(())
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Structured Append

impl Bits {
    /// Pushes a Structured Append header (ISO/IEC 18004 §7.4) to the front of
    /// the bit stream.
    ///
    /// Structured Append splits one logical message across 2..=16 QR symbols.
    /// Every symbol in the sequence carries this 20-bit header as the very
    /// first thing in its bit stream, *before* the data mode indicator:
    ///
    /// - 4-bit mode indicator `0011`,
    /// - an 8-bit symbol-sequence indicator whose **high nibble** is this
    ///   symbol's `position` (1-based, `1..=total`) and whose **low nibble** is
    ///   the `total` symbol count (`2..=16`),
    /// - an 8-bit `parity` byte (the XOR of every byte of the original,
    ///   un-split message — identical in every symbol).
    ///
    /// A `position`/`total` of 16 wraps to nibble `0` (the only encoding of 16
    /// in four bits); a spec-aware reader reads nibble `0` as 16.
    ///
    /// Structured Append is **not** valid for Micro QR; this method returns
    /// `Err(QrError::UnsupportedCharacterSet)` for a Micro QR version.
    ///
    /// # Errors
    ///
    /// Returns [`QrError::UnsupportedCharacterSet`] on a Micro QR version, and
    /// [`QrError::InvalidStructuredAppend`] if `total` is not `2..=16` or
    /// `position` is not `1..=total`.
    ///
    /// ```
    /// use qrcode_core::bits::Bits;
    /// use qrcode_core::types::Version;
    ///
    /// let mut bits = Bits::new(Version::Normal(1));
    /// bits.push_structured_append_header(1, 3, 0x5a);
    /// // First symbol of a 3-symbol sequence; parity 0x5a.
    /// ```
    pub fn push_structured_append_header(&mut self, position: u8, total: u8, parity: u8) -> QrResult<()> {
        if self.version.is_micro() {
            return Err(QrError::UnsupportedCharacterSet);
        }
        if !(2..=16).contains(&total) || !(1..=total).contains(&position) {
            return Err(QrError::InvalidStructuredAppend {
                value: if !(2..=16).contains(&total) { total } else { position },
            });
        }
        // 8-bit symbol-sequence indicator: high nibble = position, low = total.
        // Masking lets the value 16 wrap to nibble 0.
        let sequence = (u16::from(position & 0x0f) << 4) | u16::from(total & 0x0f);
        self.reserve(20);
        self.push_mode_indicator(ExtendedMode::StructuredAppend)?;
        self.push_number(8, sequence);
        self.push_number(8, u16::from(parity));
        Ok(())
    }
}

#[cfg(test)]
mod structured_append_tests {
    use crate::bits::Bits;
    use crate::types::{EcLevel, QrError, Version};

    #[test]
    fn test_header_bit_layout() {
        // First symbol of a 3-symbol sequence, parity 0x5a.
        // Bits: 0011 | 0001 0011 (pos 1 | total 3) | 0101 1010 (parity) = 20 bits.
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_structured_append_header(1, 3, 0x5a), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0x31, 0x35, 0xA0]);
    }

    #[test]
    fn test_header_bit_layout_second_of_two() {
        // Second symbol of a 2-symbol sequence, parity 0xff.
        // sequence indicator = (2 << 4) | 2 = 0x22.
        // Bits: 0011 | 0010 0010 | 1111 1111 → 0x32 0x2f 0xf0.
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_structured_append_header(2, 2, 0xff), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0x32, 0x2F, 0xF0]);
    }

    #[test]
    fn test_header_value_16_wraps_to_zero_nibble() {
        // 16th symbol of a 16-symbol sequence, parity 0 → both nibbles wrap to 0.
        // Bits: 0011 | 0000 0000 | 0000 0000 → 0x30 0x00 0x00.
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_structured_append_header(16, 16, 0x00), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0x30, 0x00, 0x00]);
    }

    #[test]
    fn test_micro_rejected() {
        let mut bits = Bits::new(Version::Micro(2));
        assert_eq!(bits.push_structured_append_header(1, 2, 0), Err(QrError::UnsupportedCharacterSet));
    }

    #[test]
    fn test_invalid_total() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_structured_append_header(1, 1, 0), Err(QrError::InvalidStructuredAppend { value: 1 }));
        assert_eq!(bits.push_structured_append_header(1, 17, 0), Err(QrError::InvalidStructuredAppend { value: 17 }));
    }

    #[test]
    fn test_invalid_position() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_structured_append_header(0, 3, 0), Err(QrError::InvalidStructuredAppend { value: 0 }));
        assert_eq!(bits.push_structured_append_header(4, 3, 0), Err(QrError::InvalidStructuredAppend { value: 4 }));
    }

    #[test]
    fn test_header_then_data_round_trips() {
        // Header + a byte-mode segment + terminator must yield a valid symbol.
        let mut bits = Bits::new(Version::Normal(1));
        bits.push_structured_append_header(1, 2, 0).unwrap();
        bits.push_byte_data(b"ab").unwrap();
        assert!(bits.push_terminator(EcLevel::M).is_ok());
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Finish

// This table is copied from ISO/IEC 18004:2006 §6.4.10, Table 7.
static DATA_LENGTHS: [[usize; 4]; 44] = [
    // Normal versions
    [152, 128, 104, 72],
    [272, 224, 176, 128],
    [440, 352, 272, 208],
    [640, 512, 384, 288],
    [864, 688, 496, 368],
    [1088, 864, 608, 480],
    [1248, 992, 704, 528],
    [1552, 1232, 880, 688],
    [1856, 1456, 1056, 800],
    [2192, 1728, 1232, 976],
    [2592, 2032, 1440, 1120],
    [2960, 2320, 1648, 1264],
    [3424, 2672, 1952, 1440],
    [3688, 2920, 2088, 1576],
    [4184, 3320, 2360, 1784],
    [4712, 3624, 2600, 2024],
    [5176, 4056, 2936, 2264],
    [5768, 4504, 3176, 2504],
    [6360, 5016, 3560, 2728],
    [6888, 5352, 3880, 3080],
    [7456, 5712, 4096, 3248],
    [8048, 6256, 4544, 3536],
    [8752, 6880, 4912, 3712],
    [9392, 7312, 5312, 4112],
    [10208, 8000, 5744, 4304],
    [10960, 8496, 6032, 4768],
    [11744, 9024, 6464, 5024],
    [12248, 9544, 6968, 5288],
    [13048, 10136, 7288, 5608],
    [13880, 10984, 7880, 5960],
    [14744, 11640, 8264, 6344],
    [15640, 12328, 8920, 6760],
    [16568, 13048, 9368, 7208],
    [17528, 13800, 9848, 7688],
    [18448, 14496, 10288, 7888],
    [19472, 15312, 10832, 8432],
    [20528, 15936, 11408, 8768],
    [21616, 16816, 12016, 9136],
    [22496, 17728, 12656, 9776],
    [23648, 18672, 13328, 10208],
    // Micro versions
    [20, 0, 0, 0],
    [40, 32, 0, 0],
    [84, 68, 0, 0],
    [128, 112, 80, 0],
];

impl Bits {
    /// Pushes the ending bits to indicate no more data.
    ///
    /// # Errors
    ///
    /// Returns `Err(QrError::DataTooLong)` on overflow.
    ///
    /// Returns `Err(QrError::InvalidVersion)` if it is not valid to use the
    /// `ec_level` for the given version (e.g. `Version::Micro(1)` with
    /// `EcLevel::H`).
    pub fn push_terminator(&mut self, ec_level: EcLevel) -> QrResult<()> {
        let terminator_size = match self.version {
            Version::Micro(a) => a.as_usize() * 2 + 1,
            Version::Normal(_) => 4,
        };

        let cur_length = self.len();
        let data_length = self.max_len(ec_level)?;
        if cur_length > data_length {
            return Err(QrError::DataTooLong);
        }

        let terminator_size = min(terminator_size, data_length - cur_length);
        if terminator_size > 0 {
            self.push_number(terminator_size, 0);
        }

        if self.len() < data_length {
            const PADDING_BYTES: &[u8] = &[0b1110_1100, 0b0001_0001];

            self.bit_offset = 0;
            let data_bytes_length = data_length / 8;
            let padding_bytes_count = data_bytes_length.saturating_sub(self.data.len());
            let padding = PADDING_BYTES.iter().copied().cycle().take(padding_bytes_count);
            self.data.extend(padding);
        }

        if self.len() < data_length {
            self.data.push(0);
        }

        Ok(())
    }
}

#[cfg(test)]
mod finish_tests {
    use crate::bits::Bits;
    use crate::types::{EcLevel, QrError, Version};

    #[test]
    fn test_hello_world() {
        let mut bits = Bits::new(Version::Normal(1));
        assert_eq!(bits.push_alphanumeric_data(b"HELLO WORLD"), Ok(()));
        assert_eq!(bits.push_terminator(EcLevel::Q), Ok(()));
        assert_eq!(
            bits.into_bytes(),
            vec![
                0b00100000, 0b01011011, 0b00001011, 0b01111000, 0b11010001, 0b01110010, 0b11011100, 0b01001101,
                0b01000011, 0b01000000, 0b11101100, 0b00010001, 0b11101100,
            ]
        );
    }

    #[test]
    fn test_too_long() {
        let mut bits = Bits::new(Version::Micro(1));
        assert_eq!(bits.push_numeric_data(b"9999999"), Ok(()));
        assert_eq!(bits.push_terminator(EcLevel::L), Err(QrError::DataTooLong));
    }

    #[test]
    fn test_no_terminator() {
        let mut bits = Bits::new(Version::Micro(1));
        assert_eq!(bits.push_numeric_data(b"99999"), Ok(()));
        assert_eq!(bits.push_terminator(EcLevel::L), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b101_11111, 0b00111_110, 0b0011_0000]);
    }

    #[test]
    fn test_no_padding() {
        let mut bits = Bits::new(Version::Micro(1));
        assert_eq!(bits.push_numeric_data(b"9999"), Ok(()));
        assert_eq!(bits.push_terminator(EcLevel::L), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b100_11111, 0b00111_100, 0b1_000_0000]);
    }

    #[test]
    fn test_micro_version_1_half_byte_padding() {
        let mut bits = Bits::new(Version::Micro(1));
        assert_eq!(bits.push_numeric_data(b"999"), Ok(()));
        assert_eq!(bits.push_terminator(EcLevel::L), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b011_11111, 0b00111_000, 0b0000_0000]);
    }

    #[test]
    fn test_micro_version_1_full_byte_padding() {
        let mut bits = Bits::new(Version::Micro(1));
        assert_eq!(bits.push_numeric_data(b""), Ok(()));
        assert_eq!(bits.push_terminator(EcLevel::L), Ok(()));
        assert_eq!(bits.into_bytes(), vec![0b000_000_00, 0b11101100, 0]);
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Front end.

impl Bits {
    /// Push a segmented data to the bits, and then terminate it.
    ///
    /// # Errors
    ///
    /// Returns `Err(QrError::DataTooLong)` on overflow.
    ///
    /// Returns `Err(QrError::InvalidData)` if the segment refers to incorrectly
    /// encoded byte sequences.
    pub fn push_segments<I>(&mut self, data: &[u8], segments_iter: I) -> QrResult<()>
    where
        I: Iterator<Item = Segment>,
    {
        for segment in segments_iter {
            let slice = &data[segment.begin..segment.end];
            match segment.mode {
                Mode::Numeric => self.push_numeric_data(slice),
                Mode::Alphanumeric => self.push_alphanumeric_data(slice),
                Mode::Byte => self.push_byte_data(slice),
                Mode::Kanji => self.push_kanji_data(slice),
            }?;
        }
        Ok(())
    }

    /// Pushes the data the bits, using the optimal encoding.
    ///
    /// # Errors
    ///
    /// Returns `Err(QrError::DataTooLong)` on overflow.
    pub fn push_optimal_data(&mut self, data: &[u8]) -> QrResult<()> {
        let segments = Parser::new(data).optimize(self.version);
        self.push_segments(data, segments)
    }
}

#[cfg(test)]
mod encode_tests {
    use crate::bits::Bits;
    use crate::types::{EcLevel, QrError, QrResult, Version};

    fn encode(data: &[u8], version: Version, ec_level: EcLevel) -> QrResult<Vec<u8>> {
        let mut bits = Bits::new(version);
        bits.push_optimal_data(data)?;
        bits.push_terminator(ec_level)?;
        Ok(bits.into_bytes())
    }

    #[test]
    fn test_alphanumeric() {
        let res = encode(b"HELLO WORLD", Version::Normal(1), EcLevel::Q);
        assert_eq!(
            res,
            Ok(vec![
                0b00100000, 0b01011011, 0b00001011, 0b01111000, 0b11010001, 0b01110010, 0b11011100, 0b01001101,
                0b01000011, 0b01000000, 0b11101100, 0b00010001, 0b11101100,
            ])
        );
    }

    #[test]
    fn test_auto_mode_switch() {
        let res = encode(b"123A", Version::Micro(2), EcLevel::L);
        assert_eq!(res, Ok(vec![0b0_0011_000, 0b1111011_1, 0b001_00101, 0b0_00000_00, 0b11101100]));
    }

    #[test]
    fn test_too_long() {
        let res = encode(b">>>>>>>>", Version::Normal(1), EcLevel::H);
        assert_eq!(res, Err(QrError::DataTooLong));
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Auto version minimization

/// Returns the data capacity (in bits) for the given version and error
/// correction level — the maximum number of data bits a symbol of that version
/// can hold.
///
/// # Errors
///
/// Returns [`QrError::InvalidVersion`] for an incompatible version / ec-level
/// combination (e.g. a Micro QR version with [`EcLevel::H`]).
pub fn data_capacity_bits(version: Version, ec_level: EcLevel) -> QrResult<usize> {
    version.fetch(ec_level, &DATA_LENGTHS)
}

/// Automatically determines the minimum version to store the data, and encode
/// the result.
///
/// This method will not consider any Micro QR code versions.
///
/// # Errors
///
/// Returns `Err(QrError::DataTooLong)` if the data is too long to fit even the
/// highest QR code version.
pub fn encode_auto(data: &[u8], ec_level: EcLevel) -> QrResult<Bits> {
    let segments = Parser::new(data).collect::<Vec<Segment>>();
    for version in &[Version::Normal(9), Version::Normal(26), Version::Normal(40)] {
        let opt_segments = Optimizer::new(segments.iter().copied(), *version).collect::<Vec<_>>();
        let total_len = total_encoded_len(&opt_segments, *version);
        let data_capacity = version.fetch(ec_level, &DATA_LENGTHS).expect("invalid DATA_LENGTHS");
        if total_len <= data_capacity {
            let min_version = find_min_version(total_len, ec_level);
            let mut bits = Bits::new(min_version);
            bits.reserve(total_len);
            bits.push_segments(data, opt_segments.into_iter())?;
            bits.push_terminator(ec_level)?;
            return Ok(bits);
        }
    }
    Err(QrError::DataTooLong)
}

/// Automatically determines the minimum Micro QR version to store the data,
/// and encode the result.
///
/// This method only considers Micro QR code versions (1–4).
///
/// # Errors
///
/// Returns `Err(QrError::DataTooLong)` if the data is too long to fit even the
/// highest Micro QR version.
///
/// Returns `Err(QrError::InvalidVersion)` if the `ec_level` is not supported
/// by any Micro QR version (e.g. `EcLevel::H`).
pub fn encode_auto_micro(data: &[u8], ec_level: EcLevel) -> QrResult<Bits> {
    let segments = Parser::new(data).collect::<Vec<Segment>>();
    for micro_version in 1..=4 {
        let version = Version::Micro(micro_version);
        let data_capacity = match version.fetch(ec_level, &DATA_LENGTHS) {
            Ok(cap) if cap > 0 => cap,
            _ => continue,
        };
        let opt_segments = Optimizer::new(segments.iter().copied(), version).collect::<Vec<_>>();
        let total_len = total_encoded_len(&opt_segments, version);
        if total_len <= data_capacity {
            let mut bits = Bits::new(version);
            bits.reserve(total_len);
            bits.push_segments(data, opt_segments.into_iter())?;
            bits.push_terminator(ec_level)?;
            return Ok(bits);
        }
    }
    Err(QrError::DataTooLong)
}

/// Finds the smallest version (QR code only) that can store N bits of data
/// in the given error correction level.
pub fn find_min_version(length: usize, ec_level: EcLevel) -> Version {
    let mut base = 0_usize;
    let mut size = 39;
    while size > 1 {
        let half = size / 2;
        let mid = base + half;
        // mid is always in [0, size).
        // mid >= 0: by definition
        // mid < size: mid = size / 2 + size / 4 + size / 8 ...
        base = if DATA_LENGTHS[mid][ec_level as usize] > length { base } else { mid };
        size -= half;
    }
    // base is always in [0, mid) because base <= mid.
    base = if DATA_LENGTHS[base][ec_level as usize] >= length { base } else { base + 1 };
    Version::Normal((base + 1).as_i16())
}

#[cfg(test)]
mod encode_auto_tests {
    use crate::bits::{encode_auto, find_min_version};
    use crate::types::{EcLevel, Version};

    #[test]
    fn test_find_min_version() {
        assert_eq!(find_min_version(60, EcLevel::L), Version::Normal(1));
        assert_eq!(find_min_version(200, EcLevel::L), Version::Normal(2));
        assert_eq!(find_min_version(200, EcLevel::H), Version::Normal(3));
        assert_eq!(find_min_version(20000, EcLevel::L), Version::Normal(37));
        assert_eq!(find_min_version(640, EcLevel::L), Version::Normal(4));
        assert_eq!(find_min_version(641, EcLevel::L), Version::Normal(5));
        assert_eq!(find_min_version(999999, EcLevel::H), Version::Normal(40));
    }

    #[test]
    fn test_alpha_q() {
        let bits = encode_auto(b"HELLO WORLD", EcLevel::Q).unwrap();
        assert_eq!(bits.version(), Version::Normal(1));
    }

    #[test]
    fn test_alpha_h() {
        let bits = encode_auto(b"HELLO WORLD", EcLevel::H).unwrap();
        assert_eq!(bits.version(), Version::Normal(2));
    }

    #[test]
    fn test_mixed() {
        let bits = encode_auto(b"This is a mixed data test. 1234567890", EcLevel::H).unwrap();
        assert_eq!(bits.version(), Version::Normal(4));
    }
}

//}}}
//------------------------------------------------------------------------------