qrcode-rs 0.5.0

QR code encoder in Rust,Generate QR Code matrices and images in RAW, PNG and SVG formats.
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
//! QRCode encoder
//!
//! This crate provides a QR code and Micro QR code encoder for binary data.
//!
#![cfg_attr(feature = "image", doc = "```rust")]
#![cfg_attr(not(feature = "image"), doc = "```ignore")]
//! use qrcode_rs::QrCode;
//! use image::Luma;
//!
//! // Encode some data into bits.
//! let code = QrCode::new(b"01234567").unwrap();
//!
//! // Render the bits into an image.
//! let image = code.render::<Luma<u8>>().build();
//!
//! // Save the image.
//! # if cfg!(unix) {
//! image.save("/tmp/qrcode.png").unwrap();
//! # }
//!
//! // You can also render it into a string.
//! let string = code.render()
//!     .light_color(' ')
//!     .dark_color('#')
//!     .build();
//! println!("{}", string);
//! ```

#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(clippy::uninlined_format_args, clippy::manual_range_contains, clippy::semicolon_if_nothing_returned)]
#![allow(
    clippy::must_use_candidate, // This is just annoying.
)]

pub mod bits;
pub mod canvas;
mod cast;
pub mod ec;
pub mod optimize;
pub mod render;
pub mod types;
pub use crate::types::{Color, EcLevel, Mode, QrError, QrResult, Version};

use crate::cast::As;
use crate::render::{Pixel, Renderer};
use std::iter::FusedIterator;
use std::ops::Index;

/// The encoded QR code symbol.
#[derive(Clone)]
pub struct QrCode {
    content: Vec<Color>,
    version: Version,
    ec_level: EcLevel,
    width: usize,
}

impl QrCode {
    /// Constructs a new QR code which automatically encodes the given data.
    ///
    /// This method uses the "medium" error correction level and automatically
    /// chooses the smallest QR code.
    ///
    ///     use qrcode_rs::QrCode;
    ///
    ///     let code = QrCode::new(b"Some data").unwrap();
    ///
    /// # Errors
    ///
    /// Returns error if the QR code cannot be constructed, e.g. when the data
    /// is too long.
    pub fn new<D: AsRef<[u8]>>(data: D) -> QrResult<Self> {
        Self::with_error_correction_level(data, EcLevel::M)
    }

    /// Constructs a new QR code which automatically encodes the given data at a
    /// specific error correction level.
    ///
    /// This method automatically chooses the smallest QR code.
    ///
    ///     use qrcode_rs::{QrCode, EcLevel};
    ///
    ///     let code = QrCode::with_error_correction_level(b"Some data", EcLevel::H).unwrap();
    ///
    /// # Errors
    ///
    /// Returns error if the QR code cannot be constructed, e.g. when the data
    /// is too long.
    pub fn with_error_correction_level<D: AsRef<[u8]>>(data: D, ec_level: EcLevel) -> QrResult<Self> {
        let bits = bits::encode_auto(data.as_ref(), ec_level)?;
        Self::with_bits(bits, ec_level)
    }

    /// Constructs a new Micro QR code which automatically encodes the given
    /// data.
    ///
    /// This method uses the "medium" error correction level and automatically
    /// chooses the smallest Micro QR code.
    ///
    ///     use qrcode_rs::QrCode;
    ///
    ///     let code = QrCode::new_micro(b"123").unwrap();
    ///
    /// # Errors
    ///
    /// Returns error if the data cannot be encoded as a Micro QR code, e.g.
    /// when the data is too long.
    pub fn new_micro<D: AsRef<[u8]>>(data: D) -> QrResult<Self> {
        Self::micro_with_error_correction_level(data, EcLevel::M)
    }

    /// Constructs a new Micro QR code which automatically encodes the given
    /// data at a specific error correction level.
    ///
    /// This method automatically chooses the smallest Micro QR code.
    ///
    ///     use qrcode_rs::{QrCode, EcLevel};
    ///
    ///     let code = QrCode::micro_with_error_correction_level(b"123", EcLevel::L).unwrap();
    ///
    /// # Errors
    ///
    /// Returns error if the data cannot be encoded as a Micro QR code, e.g.
    /// when the data is too long, or when the error correction level is not
    /// supported by any Micro QR version.
    pub fn micro_with_error_correction_level<D: AsRef<[u8]>>(data: D, ec_level: EcLevel) -> QrResult<Self> {
        let bits = bits::encode_auto_micro(data.as_ref(), ec_level)?;
        Self::with_bits(bits, ec_level)
    }

    /// Constructs a new QR code for the given version and error correction
    /// level.
    ///
    ///     use qrcode_rs::{QrCode, Version, EcLevel};
    ///
    ///     let code = QrCode::with_version(b"Some data", Version::Normal(5), EcLevel::M).unwrap();
    ///
    /// This method can also be used to generate Micro QR code.
    ///
    ///     use qrcode_rs::{QrCode, Version, EcLevel};
    ///
    ///     let micro_code = QrCode::with_version(b"123", Version::Micro(1), EcLevel::L).unwrap();
    ///
    /// # Errors
    ///
    /// Returns error if the QR code cannot be constructed, e.g. when the data
    /// is too long, or when the version and error correction level are
    /// incompatible.
    pub fn with_version<D: AsRef<[u8]>>(data: D, version: Version, ec_level: EcLevel) -> QrResult<Self> {
        let mut bits = bits::Bits::new(version);
        bits.push_optimal_data(data.as_ref())?;
        bits.push_terminator(ec_level)?;
        Self::with_bits(bits, ec_level)
    }

    /// Constructs a new QR code with encoded bits.
    ///
    /// Use this method only if there are very special need to manipulate the
    /// raw bits before encoding. Some examples are:
    ///
    /// * Encode data using specific character set with ECI
    /// * Use the FNC1 modes
    /// * Avoid the optimal segmentation algorithm
    ///
    /// See the `Bits` structure for detail.
    ///
    ///     #![allow(unused_must_use)]
    ///
    ///     use qrcode_rs::{QrCode, Version, EcLevel};
    ///     use qrcode_rs::bits::Bits;
    ///
    ///     let mut bits = Bits::new(Version::Normal(1));
    ///     bits.push_eci_designator(9);
    ///     bits.push_byte_data(b"\xca\xfe\xe4\xe9\xea\xe1\xf2 QR");
    ///     bits.push_terminator(EcLevel::L);
    ///     let qrcode = QrCode::with_bits(bits, EcLevel::L);
    ///
    /// # Errors
    ///
    /// Returns error if the QR code cannot be constructed, e.g. when the bits
    /// are too long, or when the version and error correction level are
    /// incompatible.
    pub fn with_bits(bits: bits::Bits, ec_level: EcLevel) -> QrResult<Self> {
        let version = bits.version();
        let data = bits.into_bytes();
        let (encoded_data, ec_data) = ec::construct_codewords(&data, version, ec_level)?;
        let mut canvas = canvas::Canvas::new(version, ec_level);
        canvas.draw_all_functional_patterns();
        canvas.draw_data(&encoded_data, &ec_data);
        let canvas = canvas.apply_best_mask();
        Ok(Self { content: canvas.into_colors(), version, ec_level, width: version.width().as_usize() })
    }

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

    /// Gets the error correction level of this QR code.
    pub const fn error_correction_level(&self) -> EcLevel {
        self.ec_level
    }

    /// Gets the number of modules per side, i.e. the width of this QR code.
    ///
    /// The width here does not contain the quiet zone paddings.
    pub const fn width(&self) -> usize {
        self.width
    }

    /// Gets the maximum number of allowed erratic modules can be introduced
    /// before the data becomes corrupted. Note that errors should not be
    /// introduced to functional modules.
    pub fn max_allowed_errors(&self) -> usize {
        ec::max_allowed_errors(self.version, self.ec_level).expect("invalid version or ec_level")
    }

    /// Returns metadata about this QR code (version, error-correction level,
    /// dimensions, module count, error tolerance, and data capacity).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let code = QrCode::new(b"hello").unwrap();
    /// let info = code.info();
    /// assert_eq!(info.width(), code.width());
    /// assert_eq!(info.module_count(), code.width() * code.width());
    /// assert!(info.data_capacity_bytes() > 0);
    /// ```
    #[must_use]
    pub fn info(&self) -> Info {
        Info {
            version: self.version,
            ec_level: self.ec_level,
            width: self.width,
            module_count: self.width * self.width,
            max_allowed_errors: self.max_allowed_errors(),
            data_capacity_bytes: bits::data_capacity_bits(self.version, self.ec_level).map(|b| b / 8).unwrap_or(0),
        }
    }

    /// Checks whether a module at coordinate (x, y) is a functional module or
    /// not.
    pub fn is_functional(&self, x: usize, y: usize) -> bool {
        let x = x.try_into().expect("coordinate is too large for QR code");
        let y = y.try_into().expect("coordinate is too large for QR code");
        canvas::is_functional(self.version, self.version.width(), x, y)
    }

    /// Converts the QR code into a human-readable string. This is mainly for
    /// debugging only.
    pub fn to_debug_str(&self, on_char: char, off_char: char) -> String {
        self.render().quiet_zone(false).dark_color(on_char).light_color(off_char).build()
    }

    /// Converts the QR code to a vector of colors.
    pub fn to_colors(&self) -> Vec<Color> {
        self.content.clone()
    }

    /// Converts the QR code to a vector of colors.
    pub fn into_colors(self) -> Vec<Color> {
        self.content
    }

    /// Renders the QR code into an image. The result is an image builder, which
    /// you may do some additional configuration before copying it into a
    /// concrete image.
    ///  Note: the`image` crate itself also provides method to rotate the image,
    /// or overlay a logo on top of the QR code.
    /// # Examples
    ///
    #[cfg_attr(feature = "image", doc = " ```rust")]
    #[cfg_attr(not(feature = "image"), doc = " ```ignore")]
    /// # use qrcode_rs::QrCode;
    /// # use image::Rgb;
    ///
    /// let image = QrCode::new(b"hello").unwrap()
    ///                     .render()
    ///                     .dark_color(Rgb([0, 0, 128]))
    ///                     .light_color(Rgb([224, 224, 224])) // adjust colors
    ///                     .quiet_zone(false)          // disable quiet zone (white border)
    ///                     .min_dimensions(300, 300)   // sets minimum image size
    ///                     .build();
    /// ```
    ///
    pub fn render<P: Pixel>(&self) -> Renderer<'_, P> {
        let quiet_zone = if self.version.is_micro() { 2 } else { 4 };
        Renderer::new(&self.content, self.width, quiet_zone)
    }
}

impl QrCode {
    /// Creates a [`QrCodeBuilder`] for configuring and constructing a QR code.
    ///
    /// This is an ergonomic alternative to the `with_*` constructors. The
    /// builder uses the same encoding paths, so its output is identical to the
    /// equivalent constructor.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::{QrCode, EcLevel};
    ///
    /// let code = QrCode::builder(b"https://example.com")
    ///     .ec_level(EcLevel::H)
    ///     .build()
    ///     .unwrap();
    /// # let _ = code;
    /// ```
    pub fn builder<D: AsRef<[u8]>>(data: D) -> QrCodeBuilder<D> {
        QrCodeBuilder::new(data)
    }

    /// Returns an iterator yielding one [`Row`] of modules at a time.
    ///
    /// Each row iterates over the module [`Color`]s from left to right. The
    /// quiet zone is *not* included.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let code = QrCode::new(b"hi").unwrap();
    /// for row in code.rows() {
    ///     for color in row {
    ///         # let _ = color;
    ///     }
    /// }
    /// ```
    pub fn rows(&self) -> Rows<'_> {
        Rows { code: self, y: 0 }
    }

    /// Returns an iterator over the `(x, y)` coordinates of every dark module,
    /// convenient for custom rendering. The quiet zone is *not* included.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let code = QrCode::new(b"hi").unwrap();
    /// let dark_count = code.dark_modules().count();
    /// # let _ = dark_count;
    /// ```
    pub fn dark_modules(&self) -> DarkModules<'_> {
        DarkModules { code: self, idx: 0 }
    }

    /// Encodes a URL, using high error correction (robust to print damage).
    ///
    /// # Errors
    ///
    /// Returns an error only if the URL is too long to encode.
    pub fn for_url<D: AsRef<[u8]>>(url: D) -> QrResult<Self> {
        Self::with_error_correction_level(url, EcLevel::H)
    }

    /// Encodes plain text at the default (medium) error correction level.
    ///
    /// # Errors
    ///
    /// Returns an error only if the text is too long to encode.
    pub fn for_text<D: AsRef<[u8]>>(text: D) -> QrResult<Self> {
        Self::new(text)
    }

    /// Encodes a WiFi configuration that most phone cameras will offer to join.
    ///
    /// `auth` is one of `WPA`, `WEP` or `nopass`. Special characters in the
    /// SSID/password are backslash-escaped per the WiFi QR specification.
    ///
    /// # Errors
    ///
    /// Returns an error if the resulting payload is too long to encode.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let code = QrCode::for_wifi("MyNetwork", "p\\a;ss", "WPA").unwrap();
    /// # let _ = code;
    /// ```
    pub fn for_wifi(ssid: &str, password: &str, auth: &str) -> QrResult<Self> {
        let mut payload = String::from("WIFI:T:");
        payload.push_str(auth);
        payload.push_str(";S:");
        push_escaped_wifi(&mut payload, ssid);
        payload.push_str(";P:");
        push_escaped_wifi(&mut payload, password);
        payload.push_str(";;");
        Self::new(payload)
    }

    /// Encodes a minimal vCard 3.0 contact card.
    ///
    /// # Errors
    ///
    /// Returns an error if the resulting payload is too long to encode.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let code = QrCode::for_vcard("John Doe", "+1234567890", "john@example.com").unwrap();
    /// # let _ = code;
    /// ```
    pub fn for_vcard(name: &str, phone: &str, email: &str) -> QrResult<Self> {
        let vcard = format!("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:{name}\r\nTEL:{phone}\r\nEMAIL:{email}\r\nEND:VCARD\r\n");
        Self::new(vcard)
    }

    /// Encodes a GS1 data carrier (FNC1 in first position), e.g. a GTIN /
    /// application-identifier payload such as
    /// `"010491234512345915970331301234561842"`. Uses medium error correction
    /// and the smallest fitting version.
    ///
    /// # Errors
    ///
    /// Returns an error if the data is too long to encode.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let code = QrCode::for_gs1("010491234512345915970331301234561842").unwrap();
    /// # let _ = code;
    /// ```
    pub fn for_gs1<D: AsRef<[u8]>>(data: D) -> QrResult<Self> {
        let data = data.as_ref();
        for v in 1..=40 {
            let version = Version::Normal(v);
            let mut bits = bits::Bits::new(version);
            if bits.push_fnc1_first_position().is_err()
                || bits.push_optimal_data(data).is_err()
                || bits.push_terminator(EcLevel::M).is_err()
            {
                continue;
            }
            return Self::with_bits(bits, EcLevel::M);
        }
        Err(QrError::DataTooLong)
    }

    /// Generates accessible alt text describing a QR code that encodes `data`.
    ///
    /// URLs are described as "linking to …"; other payloads as "containing: …".
    /// Use the result as the `alt` of an `<img>` or the `aria-label` of an inline
    /// SVG so assistive technology can describe the code without decoding it.
    ///
    /// This is an associated function (it does not require a constructed
    /// [`QrCode`]), so the input data does not need to be retained on the code.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// assert_eq!(QrCode::alt_text("https://example.com"), "QR code linking to https://example.com");
    /// assert_eq!(QrCode::alt_text("hello"), "QR code containing: hello");
    /// ```
    #[must_use]
    pub fn alt_text<D: AsRef<[u8]>>(data: D) -> String {
        let text = String::from_utf8_lossy(data.as_ref());
        if text.starts_with("http://") || text.starts_with("https://") {
            format!("QR code linking to {text}")
        } else {
            format!("QR code containing: {text}")
        }
    }

    /// Generates alt text with a custom formatter that receives the raw bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let alt = QrCode::alt_text_custom("hello", |data| {
    ///     format!("A QR code with {} bytes", data.len())
    /// });
    /// assert_eq!(alt, "A QR code with 5 bytes");
    /// ```
    #[must_use]
    pub fn alt_text_custom<D: AsRef<[u8]>, F: FnOnce(&[u8]) -> String>(data: D, f: F) -> String {
        f(data.as_ref())
    }

    /// Encodes `data` forced into a single `mode` at a pinned version. Used by
    /// [`QrCodeBuilder::build`] when both a version and an encoding-mode hint
    /// are set.
    fn with_mode<D: AsRef<[u8]>>(data: D, version: Version, ec_level: EcLevel, mode: Mode) -> QrResult<Self> {
        let mut bits = bits::Bits::new(version);
        match mode {
            Mode::Numeric => bits.push_numeric_data(data.as_ref())?,
            Mode::Alphanumeric => bits.push_alphanumeric_data(data.as_ref())?,
            Mode::Byte => bits.push_byte_data(data.as_ref())?,
            Mode::Kanji => bits.push_kanji_data(data.as_ref())?,
        }
        bits.push_terminator(ec_level)?;
        Self::with_bits(bits, ec_level)
    }

    /// Encodes `data` forced into a single `mode`, auto-selecting the smallest
    /// fitting version. Used by [`QrCodeBuilder::build`] when an encoding-mode
    /// hint is set without a pinned version. Returns the underlying error
    /// (e.g. [`QrError::InvalidCharacter`]) if the data is incompatible with the
    /// forced mode.
    fn with_mode_auto<D: AsRef<[u8]>>(data: D, ec_level: EcLevel, mode: Mode) -> QrResult<Self> {
        let data = data.as_ref();
        let mut last_err = QrError::DataTooLong;
        for v in 1..=40 {
            let version = Version::Normal(v);
            let mut bits = bits::Bits::new(version);
            let pushed = match mode {
                Mode::Numeric => bits.push_numeric_data(data),
                Mode::Alphanumeric => bits.push_alphanumeric_data(data),
                Mode::Byte => bits.push_byte_data(data),
                Mode::Kanji => bits.push_kanji_data(data),
            };
            if let Err(e) = pushed {
                last_err = e;
                continue;
            }
            if let Err(e) = bits.push_terminator(ec_level) {
                last_err = e;
                continue;
            }
            return Self::with_bits(bits, ec_level);
        }
        Err(last_err)
    }
}

/// Backslash-escapes the characters that are special in a WiFi QR payload.
fn push_escaped_wifi(out: &mut String, s: &str) {
    for c in s.chars() {
        if matches!(c, ';' | ',' | '"' | '\\' | ':') {
            out.push('\\');
        }
        out.push(c);
    }
}

impl Index<(usize, usize)> for QrCode {
    type Output = Color;

    fn index(&self, (x, y): (usize, usize)) -> &Color {
        let index = y * self.width + x;
        &self.content[index]
    }
}

//------------------------------------------------------------------------------
//{{{ QrCodeBuilder

/// A builder for [`QrCode`], offering ergonomic, chainable configuration.
///
/// Construct one with [`QrCode::builder`]. The builder delegates to the
/// existing constructors, so its output is identical to calling them directly.
#[derive(Clone, Debug)]
pub struct QrCodeBuilder<D: AsRef<[u8]>> {
    data: D,
    ec_level: EcLevel,
    version: Option<Version>,
    micro: bool,
    mode_hint: Option<Mode>,
}

impl<D: AsRef<[u8]>> QrCodeBuilder<D> {
    fn new(data: D) -> Self {
        Self { data, ec_level: EcLevel::M, version: None, micro: false, mode_hint: None }
    }

    /// Sets the error correction level (default [`EcLevel::M`]).
    #[must_use]
    pub fn ec_level(mut self, ec_level: EcLevel) -> Self {
        self.ec_level = ec_level;
        self
    }

    /// Pins a specific QR [`Version`]. When set, `build()` behaves like
    /// [`QrCode::with_version`]. If [`micro`](Self::micro) is also set, the
    /// explicit version takes precedence.
    #[must_use]
    pub fn version(mut self, version: Version) -> Self {
        self.version = Some(version);
        self
    }

    /// Requests a Micro QR code (the smallest fitting Micro version), behaving
    /// like [`QrCode::micro_with_error_correction_level`] when no explicit
    /// [`version`](Self::version) is set.
    #[must_use]
    pub fn micro(mut self, yes: bool) -> Self {
        self.micro = yes;
        self
    }

    /// Hints the encoding [`Mode`] (e.g. [`Mode::Byte`]), bypassing automatic
    /// mode optimization. When a [`version`](Self::version) is also set it is
    /// used directly; otherwise the smallest fitting version for that mode is
    /// auto-selected.
    ///
    /// The data must be encodable in the chosen mode: [`Mode::Kanji`] validates
    /// its Shift-JIS pairs and [`Mode::Byte`] accepts anything, but
    /// [`Mode::Numeric`] / [`Mode::Alphanumeric`] assume their input already
    /// matches (as automatic optimization would never select them otherwise).
    #[must_use]
    pub fn encoding_mode(mut self, mode: Mode) -> Self {
        self.mode_hint = Some(mode);
        self
    }

    /// Forces a specific encoding [`Mode`], bypassing automatic optimization.
    /// This is an alias for [`encoding_mode`](Self::encoding_mode), provided for
    /// familiarity with the QR-code vocabulary.
    #[must_use]
    pub fn force_mode(self, mode: Mode) -> Self {
        self.encoding_mode(mode)
    }

    /// Builds the [`QrCode`].
    ///
    /// # Errors
    ///
    /// Propagates any [`QrError`](crate::QrError) from the underlying encoder
    /// (e.g. data too long, or an incompatible version / error-correction
    /// combination).
    pub fn build(self) -> QrResult<QrCode> {
        if let Some(version) = self.version {
            if let Some(mode) = self.mode_hint {
                return QrCode::with_mode(self.data, version, self.ec_level, mode);
            }
            return QrCode::with_version(self.data, version, self.ec_level);
        }
        if let Some(mode) = self.mode_hint {
            return QrCode::with_mode_auto(self.data, self.ec_level, mode);
        }
        if self.micro {
            return QrCode::micro_with_error_correction_level(self.data, self.ec_level);
        }
        QrCode::with_error_correction_level(self.data, self.ec_level)
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Info

/// Metadata about a constructed [`QrCode`], returned by [`QrCode::info`].
///
/// Fields that require retaining the input data or the chosen mask (e.g.
/// `encoding_modes`, `mask_pattern`, `remaining_capacity`) are intentionally
/// omitted to keep `QrCode` zero-overhead; they may be added in a later version.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Info {
    version: Version,
    ec_level: EcLevel,
    width: usize,
    module_count: usize,
    max_allowed_errors: usize,
    data_capacity_bytes: usize,
}

impl Info {
    /// The QR [`Version`].
    #[must_use]
    pub const fn version(&self) -> Version {
        self.version
    }

    /// The error correction level.
    #[must_use]
    pub const fn ec_level(&self) -> EcLevel {
        self.ec_level
    }

    /// Modules per side (excluding the quiet zone).
    #[must_use]
    pub const fn width(&self) -> usize {
        self.width
    }

    /// Total number of modules (`width * width`).
    #[must_use]
    pub const fn module_count(&self) -> usize {
        self.module_count
    }

    /// Maximum number of erroneous modules that can still be recovered.
    #[must_use]
    pub const fn max_allowed_errors(&self) -> usize {
        self.max_allowed_errors
    }

    /// Data capacity of this symbol in bytes.
    #[must_use]
    pub const fn data_capacity_bytes(&self) -> usize {
        self.data_capacity_bytes
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Module iterators

/// Iterator over the rows of a [`QrCode`], created by [`QrCode::rows`].
pub struct Rows<'a> {
    code: &'a QrCode,
    y: usize,
}

impl<'a> Iterator for Rows<'a> {
    type Item = Row<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let w = self.code.width;
        if self.y < w {
            let row = Row { code: self.code, y: self.y, x: 0 };
            self.y += 1;
            Some(row)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let rem = self.code.width - self.y;
        (rem, Some(rem))
    }
}

impl<'a> ExactSizeIterator for Rows<'a> {
    fn len(&self) -> usize {
        self.code.width - self.y
    }
}

impl<'a> FusedIterator for Rows<'a> {}

/// A single row of modules, yielded by [`Rows`]. Iterates over [`Color`]s from
/// left to right (quiet zone excluded).
pub struct Row<'a> {
    code: &'a QrCode,
    y: usize,
    x: usize,
}

impl<'a> Row<'a> {
    /// The number of modules in this row.
    #[must_use]
    pub fn len(&self) -> usize {
        self.code.width
    }

    /// Whether the row is empty (always `false` for a valid QR code).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.code.width == 0
    }
}

impl<'a> Iterator for Row<'a> {
    type Item = Color;

    fn next(&mut self) -> Option<Color> {
        let w = self.code.width;
        if self.x < w {
            let color = self.code.content[self.y * w + self.x];
            self.x += 1;
            Some(color)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let rem = self.code.width - self.x;
        (rem, Some(rem))
    }
}

impl<'a> ExactSizeIterator for Row<'a> {
    fn len(&self) -> usize {
        self.code.width - self.x
    }
}

impl<'a> FusedIterator for Row<'a> {}

/// Iterator over the `(x, y)` coordinates of every dark module in a [`QrCode`],
/// created by [`QrCode::dark_modules`].
pub struct DarkModules<'a> {
    code: &'a QrCode,
    idx: usize,
}

impl<'a> Iterator for DarkModules<'a> {
    type Item = (usize, usize);

    fn next(&mut self) -> Option<(usize, usize)> {
        let w = self.code.width;
        let content = &self.code.content;
        while self.idx < content.len() {
            let i = self.idx;
            self.idx += 1;
            if content[i] == Color::Dark {
                return Some((i % w, i / w));
            }
        }
        None
    }
}

impl<'a> FusedIterator for DarkModules<'a> {}

//}}}

#[cfg(test)]
mod tests {
    use crate::{EcLevel, QrCode, Version};

    #[test]
    fn test_annex_i_qr() {
        // This uses the ISO Annex I as test vector.
        let code = QrCode::with_version(b"01234567", Version::Normal(1), EcLevel::M).unwrap();
        assert_eq!(
            &*code.to_debug_str('#', '.'),
            "\
             #######..#.##.#######\n\
             #.....#..####.#.....#\n\
             #.###.#.#.....#.###.#\n\
             #.###.#.##....#.###.#\n\
             #.###.#.#.###.#.###.#\n\
             #.....#.#...#.#.....#\n\
             #######.#.#.#.#######\n\
             ........#..##........\n\
             #.#####..#..#.#####..\n\
             ...#.#.##.#.#..#.##..\n\
             ..#...##.#.#.#..#####\n\
             ....#....#.....####..\n\
             ...######..#.#..#....\n\
             ........#.#####..##..\n\
             #######..##.#.##.....\n\
             #.....#.#.#####...#.#\n\
             #.###.#.#...#..#.##..\n\
             #.###.#.##..#..#.....\n\
             #.###.#.#.##.#..#.#..\n\
             #.....#........##.##.\n\
             #######.####.#..#.#.."
        );
    }

    #[test]
    fn test_annex_i_micro_qr() {
        let code = QrCode::with_version(b"01234567", Version::Micro(2), EcLevel::L).unwrap();
        assert_eq!(
            &*code.to_debug_str('#', '.'),
            "\
             #######.#.#.#\n\
             #.....#.###.#\n\
             #.###.#..##.#\n\
             #.###.#..####\n\
             #.###.#.###..\n\
             #.....#.#...#\n\
             #######..####\n\
             .........##..\n\
             ##.#....#...#\n\
             .##.#.#.#.#.#\n\
             ###..#######.\n\
             ...#.#....##.\n\
             ###.#..##.###"
        );
    }
}

#[cfg(test)]
mod api_tests {
    use crate::{Color, EcLevel, Mode, QrCode, Version};

    fn colors(code: &QrCode) -> Vec<Color> {
        code.to_colors()
    }

    #[test]
    fn builder_matches_with_error_correction_level() {
        let direct = QrCode::with_error_correction_level(b"Some data", EcLevel::H).unwrap();
        let built = QrCode::builder(b"Some data").ec_level(EcLevel::H).build().unwrap();
        assert_eq!(colors(&direct), colors(&built));
        assert_eq!(direct.version(), built.version());
        assert_eq!(direct.error_correction_level(), built.error_correction_level());
    }

    #[test]
    fn builder_matches_with_version() {
        let direct = QrCode::with_version(b"Some data", Version::Normal(1), EcLevel::M).unwrap();
        let built = QrCode::builder(b"Some data").version(Version::Normal(1)).build().unwrap();
        assert_eq!(colors(&direct), colors(&built));
    }

    #[test]
    fn builder_micro_matches() {
        let direct = QrCode::micro_with_error_correction_level(b"123", EcLevel::L).unwrap();
        let built = QrCode::builder(b"123").ec_level(EcLevel::L).micro(true).build().unwrap();
        assert_eq!(colors(&direct), colors(&built));
        assert!(built.version().is_micro());
    }

    #[test]
    fn builder_version_wins_over_micro() {
        let built = QrCode::builder(b"01234567").version(Version::Micro(2)).micro(true).build().unwrap();
        assert_eq!(built.version(), Version::Micro(2));
    }

    #[test]
    fn builder_forces_byte_mode() {
        // Forcing Byte mode on digits must differ from the optimal (Numeric) mode.
        let optimal = QrCode::builder(b"01234567").version(Version::Normal(2)).build().unwrap();
        let byte = QrCode::builder(b"01234567").version(Version::Normal(2)).encoding_mode(Mode::Byte).build().unwrap();
        assert_ne!(colors(&optimal), colors(&byte));
    }

    #[test]
    fn rows_iterate_full_grid() {
        let code = QrCode::new(b"hello").unwrap();
        let w = code.width();
        let rows: Vec<Vec<Color>> = code.rows().map(|r| r.collect()).collect();
        assert_eq!(rows.len(), w);
        assert!(rows.iter().all(|r| r.len() == w));
        for y in 0..w {
            for x in 0..w {
                assert_eq!(rows[y][x], code[(x, y)]);
            }
        }
    }

    #[test]
    fn rows_exact_size() {
        let code = QrCode::new(b"hello").unwrap();
        let mut rows = code.rows();
        let total = rows.len();
        let mut counted = 0;
        while rows.next().is_some() {
            counted += 1;
            assert_eq!(rows.len(), total - counted);
        }
    }

    #[test]
    fn dark_modules_match_indexed_dark_cells() {
        let code = QrCode::new(b"hello").unwrap();
        let w = code.width();
        let expected: Vec<(usize, usize)> =
            (0..w).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| code[(x, y)] == Color::Dark).collect();
        let actual: Vec<(usize, usize)> = code.dark_modules().collect();
        // dark_modules scans in row-major order, matching the construction above.
        assert_eq!(expected, actual);
    }

    #[test]
    fn for_url_uses_high_ec() {
        let code = QrCode::for_url(b"https://example.com").unwrap();
        assert_eq!(code.error_correction_level(), EcLevel::H);
    }

    #[test]
    fn wifi_escape_helper() {
        let mut out = String::new();
        super::push_escaped_wifi(&mut out, "a;b,c\"d\\e:f");
        assert_eq!(out, "a\\;b\\,c\\\"d\\\\e\\:f");
    }

    #[test]
    fn for_wifi_encodes_with_special_chars() {
        let code = QrCode::for_wifi("My;Net", "a,b", "WPA").unwrap();
        assert!(code.width() > 0);
    }

    #[test]
    fn for_vcard_encodes() {
        let code = QrCode::for_vcard("John Doe", "+1234567890", "john@example.com").unwrap();
        assert!(code.width() > 0);
    }

    #[test]
    fn for_gs1_encodes() {
        let code = QrCode::for_gs1("010491234512345915970331301234561842").unwrap();
        assert!(code.width() > 0);
        // GS1 uses FNC1 first position; smallest fitting version, medium EC.
        assert!(!code.version().is_micro());
        assert_eq!(code.error_correction_level(), crate::EcLevel::M);
    }

    #[test]
    fn info_reports_metadata() {
        let code = QrCode::with_version(b"01234567", Version::Normal(1), crate::EcLevel::M).unwrap();
        let info = code.info();
        assert_eq!(info.version(), Version::Normal(1));
        assert_eq!(info.ec_level(), crate::EcLevel::M);
        assert_eq!(info.width(), code.width());
        assert_eq!(info.module_count(), code.width() * code.width());
        assert!(info.data_capacity_bytes() > 0);
        // higher EC level => fewer data bytes for the same version
        let code_h = QrCode::with_version(b"01234567", Version::Normal(1), crate::EcLevel::H).unwrap();
        assert!(info.data_capacity_bytes() > code_h.info().data_capacity_bytes());
    }

    #[test]
    fn force_mode_without_version_auto_selects() {
        // Forcing Byte on digits must differ from auto (Numeric) without pinning a version.
        let auto = QrCode::new(b"0123456789").unwrap();
        let forced_byte = QrCode::builder(b"0123456789").force_mode(Mode::Byte).build().unwrap();
        assert_ne!(colors(&auto), colors(&forced_byte));
        // Forcing Numeric on digits matches auto (which also picks Numeric).
        let forced_num = QrCode::builder(b"0123456789").force_mode(Mode::Numeric).build().unwrap();
        assert_eq!(colors(&auto), colors(&forced_num));
        // Odd-length Kanji input surfaces InvalidCharacter via the length check.
        let err = QrCode::builder(b"\x93").force_mode(Mode::Kanji).build();
        assert!(matches!(err, Err(crate::QrError::InvalidCharacter { .. })));
    }
}

#[cfg(all(test, feature = "image"))]
mod image_tests {
    use crate::{EcLevel, QrCode, Version};
    use image::{Luma, Rgb, load_from_memory};

    #[test]
    fn test_annex_i_qr_as_image() {
        let code = QrCode::new(b"01234567").unwrap();
        let image = code.render::<Luma<u8>>().build();
        let expected =
            load_from_memory(include_bytes!("../docs/images/test_annex_i_qr_as_image.png")).unwrap().to_luma8();
        assert_eq!(image.dimensions(), expected.dimensions());
        assert_eq!(image.into_raw(), expected.into_raw());
    }

    #[test]
    fn test_annex_i_micro_qr_as_image() {
        let code = QrCode::with_version(b"01234567", Version::Micro(2), EcLevel::L).unwrap();
        let image = code
            .render()
            .min_dimensions(200, 200)
            .dark_color(Rgb([128, 0, 0]))
            .light_color(Rgb([255, 255, 128]))
            .build();
        let expected =
            load_from_memory(include_bytes!("../docs/images/test_annex_i_micro_qr_as_image.png")).unwrap().to_rgb8();
        assert_eq!(image.dimensions(), expected.dimensions());
        assert_eq!(image.into_raw(), expected.into_raw());
    }
}

#[cfg(all(test, feature = "svg"))]
mod svg_tests {
    use crate::render::svg::Color as SvgColor;
    use crate::{EcLevel, QrCode, Version};

    #[test]
    fn test_annex_i_qr_as_svg() {
        let code = QrCode::new(b"01234567").unwrap();
        let image = code.render::<SvgColor>().build();
        let expected = include_str!("../docs/images/test_annex_i_qr_as_svg.svg");
        assert_eq!(&image, expected);
    }

    #[test]
    fn test_annex_i_micro_qr_as_svg() {
        let code = QrCode::with_version(b"01234567", Version::Micro(2), EcLevel::L).unwrap();
        let image = code
            .render()
            .min_dimensions(200, 200)
            .dark_color(SvgColor("#800000"))
            .light_color(SvgColor("#ffff80"))
            .build();
        let expected = include_str!("../docs/images/test_annex_i_micro_qr_as_svg.svg");
        assert_eq!(&image, expected);
    }
}

#[cfg(all(test, feature = "eps"))]
mod eps_tests {
    use crate::render::eps::Color as EpsColor;
    use crate::{EcLevel, QrCode, Version};

    #[test]
    fn test_annex_i_qr_as_eps() {
        let code = QrCode::new(b"01234567").unwrap();
        let image = code.render::<EpsColor>().build();
        let expected = include_str!("../docs/images/test_annex_i_qr_as_eps.eps");
        assert_eq!(&image, expected);
    }

    #[test]
    fn test_annex_i_micro_qr_as_eps() {
        let code = QrCode::with_version(b"01234567", Version::Micro(2), EcLevel::L).unwrap();
        let image = code
            .render()
            .min_dimensions(200, 200)
            .dark_color(EpsColor([0.5, 0.0, 0.0]))
            .light_color(EpsColor([1.0, 1.0, 0.5]))
            .build();
        let expected = include_str!("../docs/images/test_annex_i_micro_qr_as_eps.eps");
        assert_eq!(&image, expected);
    }
}

#[cfg(all(test, feature = "pic"))]
mod pic_tests {
    use crate::render::pic::Color as PicColor;
    use crate::{EcLevel, QrCode, Version};

    #[test]
    fn test_annex_i_qr_as_pic() {
        let code = QrCode::new(b"01234567").unwrap();
        let image = code.render::<PicColor>().build();
        let expected = include_str!("../docs/images/test_annex_i_qr_as_pic.pic");
        assert_eq!(&image, expected);
    }

    #[test]
    fn test_annex_i_micro_qr_as_pic() {
        let code = QrCode::with_version(b"01234567", Version::Micro(2), EcLevel::L).unwrap();
        let image = code.render::<PicColor>().min_dimensions(1, 1).build();
        let expected = include_str!("../docs/images/test_annex_i_micro_qr_as_pic.pic");
        assert_eq!(&image, expected);
    }
}