qrcode-rs 2.0.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
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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
//! 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))]
#![cfg_attr(not(feature = "std"), no_std)]
#![deny(missing_docs)]
#![deny(clippy::uninlined_format_args, clippy::manual_range_contains, clippy::semicolon_if_nothing_returned)]
#![allow(
    clippy::must_use_candidate, // This is just annoying.
)]

extern crate alloc;

pub mod render;
pub mod structured_append;

// The encoding primitive layer lives in `qrcode-core` and is re-exported here
// so the public API (`qrcode_rs::bits::Bits`, `qrcode_rs::Version`, …) is unchanged.
pub use qrcode_core::ConstVersion;
pub use qrcode_core::{
    AlphanumericMode, ByteMode, DynEncoder, DynRenderer, EncodeConfig, EncodedOutput, EncoderFactory, EncodingMode,
    KanjiMode, ModuleGrid, NumericMode, PluginError, PluginRegistry, PostProcessor, QrPlugin, RenderConfig,
    RenderOutput, RendererFactory, StaticVersion,
};
pub use qrcode_core::{bits, canvas, ec, optimize, plugin, traits, types};
pub use qrcode_decode as decode;
pub use qrcode_parse as parse;
// `cast` stays crate-private (not part of the public API); re-import it so
// `crate::cast::As` keeps resolving across the facade and render modules.
pub use crate::types::{Color, EcLevel, Mode, QrError, QrResult, Version};
pub use qrcode_core::QrCodeRef;
use qrcode_core::cast;
pub use qrcode_core::traits::{
    Builder, Encoder, ModuleSource, ModuleStorage, ModuleView, QrSymbol, Renderer as CoreRenderer,
};

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

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

/// The encoded QR code symbol.
///
/// `QrCode` is `Send + Sync`, so it can be shared or moved across threads
/// (e.g. for parallel rendering of many codes). This is verified at compile
/// time below.
#[derive(Clone)]
pub struct QrCode {
    content: Vec<Color>,
    version: Version,
    ec_level: EcLevel,
    width: usize,
}

/// Borrowed plugin view for a QR code.
///
/// This is a convenience wrapper around [`QrCode::render_with`] for code that
/// wants to bind a symbol and registry once, then render through one or more
/// named plugin renderers.
pub struct QrCodePlugins<'a> {
    code: &'a QrCode,
    registry: &'a PluginRegistry,
}

impl QrCodePlugins<'_> {
    /// Returns the QR code bound to this plugin view.
    #[must_use]
    pub fn code(&self) -> &QrCode {
        self.code
    }

    /// Returns the plugin registry bound to this plugin view.
    #[must_use]
    pub fn registry(&self) -> &PluginRegistry {
        self.registry
    }

    /// Renders the bound QR code through a named plugin renderer.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::RendererNotFound`] when no renderer is registered
    /// with `renderer_name`, or another [`PluginError`] from grid construction,
    /// postprocessing, or rendering.
    pub fn render(&self, renderer_name: &str, config: &RenderConfig) -> Result<RenderOutput, PluginError> {
        self.code.render_with(self.registry, renderer_name, config)
    }
}

// Compile-time guarantee that QrCode stays Send + Sync as fields evolve.
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<QrCode>();
};

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> {
        AutoEncoder::default().encode(data.as_ref())
    }

    /// 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> {
        AutoEncoder::new(ec_level).encode(data.as_ref())
    }

    /// 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> {
        MicroEncoder::default().encode(data.as_ref())
    }

    /// 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> {
        MicroEncoder::new(ec_level).encode(data.as_ref())
    }

    /// 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> {
        VersionEncoder::new(version, ec_level).encode(data.as_ref())
    }

    /// Constructs a new QR code with a compile-time checked normal QR version.
    ///
    /// `N` must be in `1..=40`. Invalid values fail during const evaluation
    /// when this fixed-version path is monomorphized.
    ///
    /// ```rust
    /// use qrcode_rs::{EcLevel, QrCode, Version};
    ///
    /// let code = QrCode::with_const_version::<5, _>(b"Some data", EcLevel::M).unwrap();
    /// assert_eq!(code.version(), Version::Normal(5));
    /// ```
    ///
    /// ```compile_fail
    /// use qrcode_rs::{EcLevel, QrCode};
    ///
    /// let _ = QrCode::with_const_version::<41, _>(b"Some data", EcLevel::M);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns error if the QR code cannot be constructed for version `N`, e.g.
    /// when the data is too long for that version and error correction level.
    pub fn with_const_version<const N: i16, D: AsRef<[u8]>>(data: D, ec_level: EcLevel) -> QrResult<Self> {
        ConstVersionEncoder::<N>::new(ec_level).encode(data.as_ref())
    }

    fn encode_auto(data: &[u8], ec_level: EcLevel) -> QrResult<Self> {
        let bits = bits::encode_auto(data, ec_level)?;
        Self::with_bits(bits, ec_level)
    }

    fn encode_auto_micro(data: &[u8], ec_level: EcLevel) -> QrResult<Self> {
        let bits = bits::encode_auto_micro(data, ec_level)?;
        Self::with_bits(bits, ec_level)
    }

    fn encode_with_version(data: &[u8], version: Version, ec_level: EcLevel) -> QrResult<Self> {
        let mut bits = bits::Bits::new(version);
        bits.push_optimal_data(data)?;
        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();
        #[cfg(feature = "log")]
        log::debug!("qrcode_rs: encoding at version {version:?}, ec {ec_level:?}");
        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();
        let width = version.width().as_usize();
        #[cfg(feature = "log")]
        log::info!("qrcode_rs: encoded version {version:?} ec {ec_level:?} ({} modules)", width * width);
        Ok(Self { content: canvas.into_colors(), version, ec_level, width })
    }

    /// Encodes many inputs at once at the given error-correction level, stopping
    /// at the first input that fails to encode.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::{QrCode, EcLevel};
    ///
    /// let codes = QrCode::batch(&["alpha", "beta", "gamma"], EcLevel::M).unwrap();
    /// assert_eq!(codes.len(), 3);
    /// ```
    pub fn batch<I, D>(inputs: I, ec_level: EcLevel) -> QrResult<Vec<Self>>
    where
        I: IntoIterator<Item = D>,
        D: AsRef<[u8]>,
    {
        Self::stream_with_error_correction_level(inputs, ec_level).collect()
    }

    /// Lazily encodes inputs into QR codes with the default error-correction level.
    ///
    /// Unlike [`batch`](Self::batch), this returns an iterator and does not
    /// collect every generated code into memory.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::{EcLevel, QrCode};
    ///
    /// let widths = QrCode::stream(["alpha", "beta"])
    ///     .map(|code| code.map(|code| (code.error_correction_level(), code.width())))
    ///     .collect::<Result<Vec<_>, _>>()
    ///     .unwrap();
    ///
    /// assert_eq!(widths, vec![(EcLevel::M, 21), (EcLevel::M, 21)]);
    /// ```
    pub fn stream<I, D>(inputs: I) -> QrCodeStream<I::IntoIter>
    where
        I: IntoIterator<Item = D>,
        D: AsRef<[u8]>,
    {
        Self::stream_with_error_correction_level(inputs, EcLevel::M)
    }

    /// Lazily encodes inputs into QR codes at `ec_level`.
    ///
    /// The iterator yields one [`QrResult<QrCode>`] per input, so callers can
    /// stop at the first error with `collect::<Result<Vec<_>, _>>()` or handle
    /// errors per item while keeping memory usage bounded by the active item.
    pub fn stream_with_error_correction_level<I, D>(inputs: I, ec_level: EcLevel) -> QrCodeStream<I::IntoIter>
    where
        I: IntoIterator<Item = D>,
        D: AsRef<[u8]>,
    {
        QrCodeStream { inputs: inputs.into_iter(), ec_level }
    }

    /// 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),
        }
    }

    /// Returns diagnostic stats for this code: dark-module ratio and the split
    /// between functional and data modules. Combine with [`QrCode::info`] for
    /// version / capacity. Computed on demand (scans the grid).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let code = QrCode::new(b"hello").unwrap();
    /// let a = code.analyze();
    /// assert!(a.dark_ratio() > 0.0 && a.dark_ratio() < 1.0);
    /// assert_eq!(a.functional_modules() + a.data_modules(), code.width() * code.width());
    /// ```
    #[must_use]
    pub fn analyze(&self) -> Analysis {
        let total = self.width * self.width;
        let dark = self.content.iter().filter(|c| **c == Color::Dark).count();
        let functional =
            (0..self.width).map(|y| (0..self.width).filter(|x| self.is_functional(*x, y)).count()).sum::<usize>();
        Analysis {
            dark_ratio: if total == 0 { 0.0 } else { dark as f64 / total as f64 },
            functional_modules: functional,
            data_modules: total - functional,
        }
    }

    /// 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()
    }

    /// Returns the module colors as a borrowed slice — no allocation. Use this
    /// in preference to [`to_colors`](Self::to_colors) when you only need to
    /// read the modules.
    ///
    /// The slice is row-major, with `width() * width()` entries and no quiet
    /// zone.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let code = QrCode::new(b"hi").unwrap();
    /// let colors = code.colors();
    /// assert_eq!(colors.len(), code.width() * code.width());
    /// ```
    pub fn colors(&self) -> &[Color] {
        &self.content
    }

    /// Returns a borrowed, read-only module-grid view.
    ///
    /// This is the facade-friendly [`ModuleSource`] adapter for APIs that accept
    /// a borrowed QR module source without needing ownership of the full
    /// [`QrCode`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::{ModuleSource, QrCode};
    ///
    /// let code = QrCode::new(b"hi").unwrap();
    /// let view = code.module_view();
    /// assert_eq!(view.width(), code.width());
    /// assert_eq!(view.modules(), code.colors());
    /// ```
    #[must_use]
    pub fn module_view(&self) -> ModuleView<'_> {
        ModuleView::new(&self.content, self.width).expect("QrCode stores a non-empty square module grid")
    }

    /// Returns a borrowed QR symbol view with module data and metadata.
    ///
    /// Unlike [`to_colors`](Self::to_colors), this does not allocate or clone
    /// the module grid. It is useful for renderers and analyzers that accept a
    /// [`QrSymbol`] and need version/error-correction metadata in addition to
    /// read-only module access.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::{ModuleSource, QrCode, QrSymbol};
    ///
    /// let code = QrCode::new(b"hi").unwrap();
    /// let borrowed = code.as_ref();
    /// assert_eq!(borrowed.version(), code.version());
    /// assert_eq!(borrowed.modules(), code.colors());
    /// ```
    #[must_use]
    pub fn as_ref(&self) -> QrCodeRef<'_> {
        QrCodeRef::new(&self.content, self.width, self.version, self.ec_level)
            .expect("QrCode stores a non-empty square module grid")
    }

    /// 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> {
        Renderer::from_symbol(self)
    }

    /// Returns the render builder for this QR code.
    ///
    /// This is an explicit builder-style alias for [`render`](Self::render),
    /// useful when code wants the construction and rendering paths to read the
    /// same way (`QrCode::builder(...).build()?.render_builder::<P>()...`).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let text = QrCode::new(b"hello").unwrap()
    ///     .render_builder::<char>()
    ///     .dark_color('#')
    ///     .quiet_zone(false)
    ///     .module_dimensions(1, 1)
    ///     .build();
    ///
    /// assert!(text.contains('#'));
    /// ```
    pub fn render_builder<P: Pixel>(&self) -> Renderer<'_, P> {
        self.render()
    }

    /// Renders the QR code on Tokio's blocking thread pool.
    ///
    /// This opt-in async helper is available with the `async` feature. It clones
    /// the compact module grid and performs the synchronous render work inside
    /// [`tokio::task::spawn_blocking`], so callers running inside a Tokio
    /// runtime do not execute CPU-heavy rendering on the async worker thread.
    ///
    /// # Errors
    ///
    /// Returns [`tokio::task::JoinError`] if the blocking task is cancelled or
    /// panics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::QrCode;
    ///
    /// let code = QrCode::new(b"hello").unwrap();
    /// let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
    /// let text = runtime.block_on(code.render_async::<char>()).unwrap();
    /// assert!(!text.is_empty());
    /// ```
    #[cfg(feature = "async")]
    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
    pub async fn render_async<P>(&self) -> Result<P::Image, tokio::task::JoinError>
    where
        P: Pixel + Send + 'static,
        P::Image: Send + 'static,
    {
        let code = self.clone();
        tokio::task::spawn_blocking(move || code.render::<P>().build()).await
    }

    /// Encodes raw input through a named plugin encoder.
    ///
    /// This is the encoder-side counterpart to [`QrCode::render_with`]: it
    /// looks up `encoder_name` in `registry`, builds the dynamic encoder with
    /// `config`, and returns the encoder's type-erased output.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::EncoderNotFound`] when no encoder is registered
    /// with `encoder_name`, or another [`PluginError`] returned by the encoder.
    pub fn encode_with(
        registry: &PluginRegistry,
        encoder_name: &str,
        input: &[u8],
        config: &EncodeConfig,
    ) -> Result<EncodedOutput, PluginError> {
        registry.build_encoder(encoder_name, config)?.encode(input)
    }

    /// Renders the QR code through a named plugin renderer.
    ///
    /// The method looks up `renderer_name` in `registry`, copies this QR code's
    /// module grid into a mutable [`ModuleGrid`], applies all registered
    /// [`PostProcessor`] values in registration order, then renders the
    /// transformed grid through the selected dynamic renderer.
    ///
    /// # Errors
    ///
    /// Returns [`PluginError::RendererNotFound`] when no renderer is registered
    /// with `renderer_name`, or another [`PluginError`] from grid construction,
    /// postprocessing, or rendering.
    pub fn render_with(
        &self,
        registry: &PluginRegistry,
        renderer_name: &str,
        config: &RenderConfig,
    ) -> Result<RenderOutput, PluginError> {
        let mut modules = ModuleGrid::new(self.content.clone(), self.width, self.width)?;
        registry.process_modules(&mut modules)?;
        registry.build_renderer(renderer_name, config)?.render(&modules)
    }

    /// Binds this QR code to a plugin registry for fluent plugin rendering.
    ///
    /// The returned view borrows both values and delegates to
    /// [`QrCode::render_with`], so it has the same deterministic, explicit
    /// registry behavior without introducing global plugin state.
    pub fn with_plugins<'a>(&'a self, registry: &'a PluginRegistry) -> QrCodePlugins<'a> {
        QrCodePlugins { code: self, registry }
    }
}

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> {
        Self::new(parse::wifi::encode_wifi(ssid, password, auth))
    }

    /// 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> {
        Self::new(parse::vcard::encode_vcard(name, phone, email))
    }

    /// 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)
    }

    /// Splits `payload` across `symbols` QR codes (2..=16) using Structured
    /// Append (ISO/IEC 18004 §7.4), each at error-correction level `ec`. Every
    /// symbol is the smallest version that fits its chunk plus the 20-bit
    /// Structured Append header.
    ///
    /// This is a thin convenience over
    /// [`crate::structured_append::StructuredAppend`]; see that type for the
    /// split and parity details, and [`crate::structured_append::reassemble`]
    /// for recombining decoded symbols.
    ///
    /// # Errors
    ///
    /// Returns [`QrError::InvalidStructuredAppend`] if `symbols` is not in
    /// `2..=16`, or [`QrError::DataTooLong`] if a chunk cannot fit even version
    /// 40 at `ec`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qrcode_rs::{EcLevel, QrCode};
    ///
    /// let codes = QrCode::structured_append(b"split across multiple symbols", 3, EcLevel::M)?;
    /// assert_eq!(codes.len(), 3);
    /// # Ok::<(), qrcode_rs::QrError>(())
    /// ```
    pub fn structured_append<D: AsRef<[u8]>>(payload: D, symbols: u8, ec: EcLevel) -> QrResult<Vec<Self>> {
        let sa = structured_append::StructuredAppend::new(symbols, payload.as_ref())?;
        sa.encode(ec)
    }

    /// 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)
    }
}

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]
    }
}

impl ModuleStorage for QrCode {
    fn get(&self, x: usize, y: usize) -> Color {
        self[(x, y)]
    }

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

    fn width(&self) -> usize {
        self.width
    }

    fn height(&self) -> usize {
        self.width
    }

    fn modules(&self) -> &[Color] {
        self.colors()
    }
}

impl QrSymbol for QrCode {
    fn version(&self) -> Version {
        self.version
    }

    fn error_correction_level(&self) -> EcLevel {
        self.ec_level
    }
}

//------------------------------------------------------------------------------
//{{{ Encoder adapters

/// Encoder adapter for automatically sized normal QR codes.
///
/// This is the trait-friendly counterpart to
/// [`QrCode::with_error_correction_level`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AutoEncoder {
    ec_level: EcLevel,
}

impl AutoEncoder {
    /// Creates an encoder with the given error-correction level.
    #[must_use]
    pub const fn new(ec_level: EcLevel) -> Self {
        Self { ec_level }
    }

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

impl Default for AutoEncoder {
    fn default() -> Self {
        Self { ec_level: EcLevel::M }
    }
}

impl Encoder for AutoEncoder {
    type Output = QrCode;
    type Error = QrError;

    fn encode(&self, input: &[u8]) -> QrResult<QrCode> {
        QrCode::encode_auto(input, self.ec_level)
    }
}

/// Encoder adapter for automatically sized Micro QR codes.
///
/// This is the trait-friendly counterpart to
/// [`QrCode::micro_with_error_correction_level`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MicroEncoder {
    ec_level: EcLevel,
}

impl MicroEncoder {
    /// Creates a Micro QR encoder with the given error-correction level.
    #[must_use]
    pub const fn new(ec_level: EcLevel) -> Self {
        Self { ec_level }
    }

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

impl Default for MicroEncoder {
    fn default() -> Self {
        Self { ec_level: EcLevel::M }
    }
}

impl Encoder for MicroEncoder {
    type Output = QrCode;
    type Error = QrError;

    fn encode(&self, input: &[u8]) -> QrResult<QrCode> {
        QrCode::encode_auto_micro(input, self.ec_level)
    }
}

/// Encoder adapter for a pinned [`Version`] and [`EcLevel`].
///
/// This is the trait-friendly counterpart to [`QrCode::with_version`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VersionEncoder {
    version: Version,
    ec_level: EcLevel,
}

impl VersionEncoder {
    /// Creates an encoder for a specific version and error-correction level.
    #[must_use]
    pub const fn new(version: Version, ec_level: EcLevel) -> Self {
        Self { version, ec_level }
    }

    /// Returns the configured version.
    #[must_use]
    pub const fn version(&self) -> Version {
        self.version
    }

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

impl Encoder for VersionEncoder {
    type Output = QrCode;
    type Error = QrError;

    fn encode(&self, input: &[u8]) -> QrResult<QrCode> {
        QrCode::encode_with_version(input, self.version, self.ec_level)
    }
}

/// Encoder adapter for a compile-time checked normal QR version and [`EcLevel`].
///
/// This is the trait-friendly counterpart to
/// [`QrCode::with_const_version`]. `N` must be in `1..=40`.
///
/// ```rust
/// use qrcode_rs::{ConstVersionEncoder, EcLevel, Encoder, Version};
///
/// let code = ConstVersionEncoder::<5>::new(EcLevel::M).encode(b"Some data").unwrap();
/// assert_eq!(code.version(), Version::Normal(5));
/// ```
///
/// ```compile_fail
/// use qrcode_rs::{ConstVersionEncoder, EcLevel};
///
/// const INVALID: ConstVersionEncoder<0> = ConstVersionEncoder::<0>::new(EcLevel::M);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ConstVersionEncoder<const N: i16> {
    ec_level: EcLevel,
}

impl<const N: i16> ConstVersionEncoder<N> {
    /// Creates an encoder for fixed normal QR version `N`.
    #[must_use]
    pub const fn new(ec_level: EcLevel) -> Self {
        let _ = ConstVersion::<N>::VALUE;
        Self { ec_level }
    }

    /// Returns the compile-time checked dynamic version value.
    #[must_use]
    pub const fn version(&self) -> Version {
        ConstVersion::<N>::VALUE
    }

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

impl<const N: i16> Encoder for ConstVersionEncoder<N> {
    type Output = QrCode;
    type Error = QrError;

    fn encode(&self, input: &[u8]) -> QrResult<QrCode> {
        QrCode::encode_with_version(input, ConstVersion::<N>::VALUE, self.ec_level)
    }
}

//}}}

//------------------------------------------------------------------------------
//{{{ 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
    }

    /// Hints the encoding mode with a type-level [`EncodingMode`] marker.
    ///
    /// Unlike [`encoding_mode`](Self::encoding_mode), this validates `data`
    /// immediately and returns [`QrError::InvalidCharacter`] when the selected
    /// mode cannot represent it.
    ///
    /// ```rust
    /// use qrcode_rs::{NumericMode, QrCode, QrError, Version};
    ///
    /// let code = QrCode::builder(b"01234567")
    ///     .version(Version::Normal(1))
    ///     .encoding_mode_typed::<NumericMode>()
    ///     .unwrap()
    ///     .build()
    ///     .unwrap();
    /// assert_eq!(code.version(), Version::Normal(1));
    ///
    /// let err = QrCode::builder(b"12a")
    ///     .encoding_mode_typed::<NumericMode>()
    ///     .unwrap_err();
    /// assert_eq!(err, QrError::InvalidCharacter { position: 2, byte: b'a' });
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`QrError::InvalidCharacter`] with the first invalid byte when
    /// `data` is not valid for `M`.
    pub fn encoding_mode_typed<M: EncodingMode>(mut self) -> QrResult<Self> {
        if let Some((position, byte)) = M::invalid_character(self.data.as_ref()) {
            return Err(QrError::InvalidCharacter { position, byte });
        }
        self.mode_hint = Some(M::MODE);
        Ok(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)
    }

    /// Forces a type-level encoding mode after validating the input.
    ///
    /// This is an alias for [`encoding_mode_typed`](Self::encoding_mode_typed).
    ///
    /// # Errors
    ///
    /// Returns [`QrError::InvalidCharacter`] with the first invalid byte when
    /// `data` is not valid for `M`.
    pub fn force_mode_typed<M: EncodingMode>(self) -> QrResult<Self> {
        self.encoding_mode_typed::<M>()
    }

    /// Builds the [`QrCode`].
    ///
    /// # Errors
    ///
    /// Propagates any [`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)
    }
}

impl<D: AsRef<[u8]>> Builder for QrCodeBuilder<D> {
    type Output = QrCode;
    type Error = QrError;

    fn build(self) -> QrResult<QrCode> {
        QrCodeBuilder::build(self)
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ QrCodeStream

/// Lazy iterator returned by [`QrCode::stream`] and
/// [`QrCode::stream_with_error_correction_level`].
#[derive(Clone, Debug)]
pub struct QrCodeStream<I> {
    inputs: I,
    ec_level: EcLevel,
}

impl<I> Iterator for QrCodeStream<I>
where
    I: Iterator,
    I::Item: AsRef<[u8]>,
{
    type Item = QrResult<QrCode>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inputs.next().map(|input| QrCode::with_error_correction_level(input, self.ec_level))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inputs.size_hint()
    }
}

impl<I> FusedIterator for QrCodeStream<I>
where
    I: FusedIterator,
    I::Item: AsRef<[u8]>,
{
}

impl<I> ExactSizeIterator for QrCodeStream<I>
where
    I: ExactSizeIterator,
    I::Item: AsRef<[u8]>,
{
    fn len(&self) -> usize {
        self.inputs.len()
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ 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)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
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
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Serde (QrCodeData)

/// A serializable view of a [`QrCode`] (matrix + metadata), enabled by the
/// `serde` feature. Round-trips via [`QrCode::to_serializable`] and
/// [`QrCode::from_serializable`].
#[cfg(feature = "serde")]
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct QrCodeData {
    /// The [`Version`].
    pub version: Version,
    /// The error-correction level.
    pub ec_level: EcLevel,
    /// Modules per side (excluding the quiet zone).
    pub width: usize,
    /// Module colors, row-major (`width * width` entries).
    pub content: Vec<Color>,
}

#[cfg(feature = "serde")]
impl QrCode {
    /// Serializes this QR code into a [`QrCodeData`] (requires the `serde` feature).
    #[must_use]
    pub fn to_serializable(&self) -> QrCodeData {
        QrCodeData { version: self.version, ec_level: self.ec_level, width: self.width, content: self.content.clone() }
    }

    /// Reconstructs a [`QrCode`] from [`QrCodeData`] (requires the `serde` feature).
    ///
    /// `data` is trusted: `content.len()` must equal `width * width` (checked in
    /// debug builds). Pair with [`QrCode::to_serializable`].
    #[must_use]
    pub fn from_serializable(data: QrCodeData) -> Self {
        debug_assert_eq!(data.content.len(), data.width * data.width, "malformed QrCodeData");
        Self { content: data.content, version: data.version, ec_level: data.ec_level, width: data.width }
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ Analysis

/// Diagnostic stats for a constructed [`QrCode`], returned by [`QrCode::analyze`].
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Analysis {
    dark_ratio: f64,
    functional_modules: usize,
    data_modules: usize,
}

impl Analysis {
    /// Fraction of modules that are dark, in `0.0..=1.0`.
    #[must_use]
    pub const fn dark_ratio(&self) -> f64 {
        self.dark_ratio
    }

    /// Number of functional modules (finder / alignment / timing / format / version).
    #[must_use]
    pub const fn functional_modules(&self) -> usize {
        self.functional_modules
    }

    /// Number of data + error-correction modules (`width² − functional`).
    #[must_use]
    pub const fn data_modules(&self) -> usize {
        self.data_modules
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ QrTemplate

/// A reusable render-time style: dark/light hex colors, module size, and quiet
/// zone. Apply to a [`Renderer`] with [`Renderer::template`] when the pixel type
/// is a [`StyledPixel`](crate::render::StyledPixel).
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct QrTemplate {
    /// Dark module color as a CSS hex string (e.g. `"#1a1a2e"`).
    pub dark_color: String,
    /// Light module color as a CSS hex string (e.g. `"#e0e0e0"`).
    pub light_color: String,
    /// Optional module dimensions `(width, height)` in output units/pixels.
    pub module_size: Option<(u32, u32)>,
    /// Whether to include the quiet zone.
    pub quiet_zone: bool,
}

impl QrTemplate {
    /// Black on white, default size, with quiet zone — the standard look.
    #[must_use]
    pub fn minimal() -> Self {
        Self { dark_color: "#000000".into(), light_color: "#ffffff".into(), module_size: None, quiet_zone: true }
    }

    /// Light modules on a dark background.
    #[must_use]
    pub fn dark_mode() -> Self {
        Self { dark_color: "#e0e0e0".into(), light_color: "#1a1a2e".into(), module_size: None, quiet_zone: true }
    }

    /// Pure black/white, maximum contrast (accessibility).
    #[must_use]
    pub fn high_contrast() -> Self {
        Self { dark_color: "#000000".into(), light_color: "#ffffff".into(), module_size: None, quiet_zone: true }
    }

    /// Corporate navy on white.
    #[must_use]
    pub fn corporate() -> Self {
        Self { dark_color: "#003366".into(), light_color: "#ffffff".into(), module_size: None, quiet_zone: true }
    }
}

impl qrcode_render::RenderTemplate for QrTemplate {
    fn dark_color(&self) -> &str {
        &self.dark_color
    }

    fn light_color(&self) -> &str {
        &self.light_color
    }

    fn module_size(&self) -> Option<(u32, u32)> {
        self.module_size
    }

    fn quiet_zone(&self) -> bool {
        self.quiet_zone
    }
}

//}}}
//------------------------------------------------------------------------------
//{{{ 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::{
        AutoEncoder, Builder as CoreBuilder, Color, ConstVersion, ConstVersionEncoder, DynEncoder, DynRenderer,
        EcLevel, EncodeConfig, EncodedOutput, EncoderFactory, MicroEncoder, Mode, ModuleView, NumericMode,
        PluginRegistry, PostProcessor, QrCode, QrError, QrSymbol, RenderConfig, RenderOutput, RendererFactory, Version,
        VersionEncoder,
    };
    use alloc::{
        boxed::Box,
        string::{String, ToString},
        vec,
        vec::Vec,
    };
    use qrcode_core::traits::{
        Encoder as CoreEncoder, ModuleSource as CoreModuleSource, ModuleStorage as CoreModuleStorage,
        Renderer as CoreRenderer,
    };

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

    struct TextPluginRenderer;

    impl DynRenderer for TextPluginRenderer {
        fn render(&self, code: &dyn CoreModuleSource) -> Result<RenderOutput, crate::PluginError> {
            let mut output = String::new();
            for y in 0..code.height() {
                for x in 0..code.width() {
                    output.push(if code.get(x, y) == Color::Dark { '#' } else { '.' });
                }
            }
            Ok(RenderOutput::Text(output))
        }
    }

    struct TextPluginFactory;

    impl RendererFactory for TextPluginFactory {
        fn build(&self, _config: &RenderConfig) -> Box<dyn DynRenderer> {
            Box::new(TextPluginRenderer)
        }
    }

    struct LengthPluginEncoder;

    impl DynEncoder for LengthPluginEncoder {
        fn encode(&self, input: &[u8]) -> Result<EncodedOutput, crate::PluginError> {
            Ok(EncodedOutput::Bytes(input.len().to_string().into_bytes()))
        }
    }

    struct LengthPluginFactory;

    impl EncoderFactory for LengthPluginFactory {
        fn build(&self, _config: &EncodeConfig) -> Box<dyn DynEncoder> {
            Box::new(LengthPluginEncoder)
        }
    }

    struct DarkenFirstModule;

    impl PostProcessor for DarkenFirstModule {
        fn process(&self, modules: &mut dyn CoreModuleStorage) -> Result<(), crate::PluginError> {
            modules.set(0, 0, Color::Dark);
            Ok(())
        }
    }

    #[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 stream_lazily_encodes_with_default_error_correction_level() {
        let codes = QrCode::stream(["alpha", "beta"]).collect::<Result<Vec<_>, _>>().unwrap();

        assert_eq!(codes.iter().map(QrCode::error_correction_level).collect::<Vec<_>>(), [EcLevel::M, EcLevel::M]);
    }

    #[test]
    fn stream_with_error_correction_level_matches_batch() {
        let inputs = ["alpha", "beta", "gamma"];
        let streamed =
            QrCode::stream_with_error_correction_level(inputs, EcLevel::H).collect::<Result<Vec<_>, _>>().unwrap();
        let batched = QrCode::batch(inputs, EcLevel::H).unwrap();

        assert_eq!(streamed.iter().map(colors).collect::<Vec<_>>(), batched.iter().map(colors).collect::<Vec<_>>());
    }

    #[test]
    fn stream_exposes_exact_remaining_len() {
        let mut stream = QrCode::stream(["alpha", "beta", "gamma"]);

        assert_eq!(stream.len(), 3);
        assert!(stream.next().unwrap().is_ok());
        assert_eq!(stream.len(), 2);
    }

    #[test]
    fn core_builder_trait_builds_qrcode_builder() {
        let code = CoreBuilder::build(QrCode::builder(b"Some data").ec_level(EcLevel::H)).unwrap();

        assert_eq!(code.error_correction_level(), EcLevel::H);
    }

    #[test]
    fn auto_encoder_matches_constructor() {
        let direct = QrCode::with_error_correction_level(b"Some data", EcLevel::H).unwrap();
        let encoded = AutoEncoder::new(EcLevel::H).encode(b"Some data").unwrap();
        assert_eq!(colors(&direct), colors(&encoded));
    }

    #[test]
    fn micro_encoder_matches_constructor() {
        let direct = QrCode::micro_with_error_correction_level(b"123", EcLevel::L).unwrap();
        let encoded = MicroEncoder::new(EcLevel::L).encode(b"123").unwrap();
        assert_eq!(colors(&direct), colors(&encoded));
    }

    #[test]
    fn version_encoder_matches_constructor() {
        let direct = QrCode::with_version(b"Some data", Version::Normal(1), EcLevel::M).unwrap();
        let encoded = VersionEncoder::new(Version::Normal(1), EcLevel::M).encode(b"Some data").unwrap();
        assert_eq!(colors(&direct), colors(&encoded));
    }

    #[test]
    fn const_version_encoder_matches_dynamic_version() {
        const V5: Version = ConstVersion::<5>::VALUE;
        let direct = QrCode::with_version(b"Some data", Version::Normal(5), EcLevel::M).unwrap();
        let const_ctor = QrCode::with_const_version::<5, _>(b"Some data", EcLevel::M).unwrap();
        let encoded = ConstVersionEncoder::<5>::new(EcLevel::M).encode(b"Some data").unwrap();

        assert_eq!(V5, Version::Normal(5));
        assert_eq!(ConstVersion::<5>::new().version(), Version::Normal(5));
        assert_eq!(ConstVersionEncoder::<5>::new(EcLevel::M).version(), Version::Normal(5));
        assert_eq!(colors(&direct), colors(&const_ctor));
        assert_eq!(colors(&direct), colors(&encoded));
    }

    #[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 render_with_uses_registered_renderer_and_postprocessors() {
        let code = QrCode::new(b"plugin").unwrap();
        let mut registry = PluginRegistry::new();
        registry.register_renderer("text", Box::new(TextPluginFactory));
        registry.register_postprocessor(Box::new(DarkenFirstModule));

        let output = code.render_with(&registry, "text", &RenderConfig::new()).unwrap();
        let RenderOutput::Text(text) = output else {
            panic!("expected text output");
        };

        assert_eq!(text.len(), code.width() * code.width());
        assert!(text.starts_with('#'));
    }

    #[test]
    fn with_plugins_renders_through_bound_registry() {
        let code = QrCode::new(b"plugin").unwrap();
        let mut registry = PluginRegistry::new();
        registry.register_renderer("text", Box::new(TextPluginFactory));
        registry.register_postprocessor(Box::new(DarkenFirstModule));

        let bound = code.with_plugins(&registry);
        let output = bound.render("text", &RenderConfig::new()).unwrap();

        assert_eq!(bound.code().width(), code.width());
        assert!(bound.registry().renderer("text").is_some());
        assert_eq!(output, code.render_with(&registry, "text", &RenderConfig::new()).unwrap());
    }

    #[test]
    fn render_with_reports_missing_renderer() {
        let code = QrCode::new(b"plugin").unwrap();
        let registry = PluginRegistry::new();

        assert!(matches!(
            code.render_with(&registry, "missing", &RenderConfig::new()),
            Err(crate::PluginError::RendererNotFound(name)) if name == "missing"
        ));
    }

    #[test]
    fn render_with_uses_builtin_plain_text_plugin() {
        let code = QrCode::new(b"plugin").unwrap();
        let mut registry = PluginRegistry::new();
        registry.register_plugin(&crate::render::plugin::PlainTextRendererPlugin);
        let config =
            RenderConfig::new().with_option("dark", "X").with_option("light", ".").with_option("quiet_zone", "0");

        let output = code
            .render_with(&registry, crate::render::plugin::PlainTextRendererPlugin::RENDERER_NAME, &config)
            .unwrap();
        let expected =
            code.render::<char>().dark_color('X').light_color('.').quiet_zone(false).module_dimensions(1, 1).build();

        assert_eq!(output, RenderOutput::Text(expected));
    }

    #[test]
    fn render_with_uses_builtin_invert_modules_plugin() {
        let code = QrCode::new(b"plugin").unwrap();
        let mut registry = PluginRegistry::new();
        registry.register_plugin(&crate::render::plugin::PlainTextRendererPlugin);
        registry.register_plugin(&crate::render::plugin::InvertModulesPlugin);
        let config =
            RenderConfig::new().with_option("dark", "X").with_option("light", ".").with_option("quiet_zone", "0");

        let output = code
            .render_with(&registry, crate::render::plugin::PlainTextRendererPlugin::RENDERER_NAME, &config)
            .unwrap();
        let direct =
            code.render::<char>().dark_color('.').light_color('X').quiet_zone(false).module_dimensions(1, 1).build();

        assert_eq!(output, RenderOutput::Text(direct));
    }

    #[test]
    fn encode_with_uses_registered_encoder() {
        let mut registry = PluginRegistry::new();
        registry.register_encoder("length", Box::new(LengthPluginFactory));

        let output = QrCode::encode_with(&registry, "length", b"abcd", &EncodeConfig::new()).unwrap();

        assert_eq!(output, EncodedOutput::Bytes(b"4".to_vec()));
    }

    #[test]
    fn encode_with_reports_missing_encoder() {
        let registry = PluginRegistry::new();

        assert!(matches!(
            QrCode::encode_with(&registry, "missing", b"abcd", &EncodeConfig::new()),
            Err(crate::PluginError::EncoderNotFound(name)) if name == "missing"
        ));
    }

    #[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 builder_typed_encoding_mode_matches_dynamic_mode() {
        let typed = QrCode::builder(b"01234567")
            .version(Version::Normal(2))
            .encoding_mode_typed::<NumericMode>()
            .unwrap()
            .build()
            .unwrap();
        let dynamic =
            QrCode::builder(b"01234567").version(Version::Normal(2)).encoding_mode(Mode::Numeric).build().unwrap();

        assert_eq!(colors(&typed), colors(&dynamic));
    }

    #[test]
    fn builder_typed_encoding_mode_rejects_invalid_input() {
        let err = QrCode::builder(b"12a").encoding_mode_typed::<NumericMode>().unwrap_err();

        assert_eq!(err, QrError::InvalidCharacter { position: 2, byte: b'a' });
    }

    #[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 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 structured_append_encodes_n_symbols() {
        let codes = QrCode::structured_append(b"hello structured append world", 3, EcLevel::M).unwrap();
        assert_eq!(codes.len(), 3);
        assert!(codes.iter().all(|c| !c.version().is_micro()));
    }

    #[test]
    fn structured_append_rejects_invalid_symbol_count() {
        assert_eq!(
            QrCode::structured_append(b"x", 1, EcLevel::M).err(),
            Some(crate::QrError::InvalidStructuredAppend { value: 1 })
        );
        assert_eq!(
            QrCode::structured_append(b"x", 17, EcLevel::M).err(),
            Some(crate::QrError::InvalidStructuredAppend { value: 17 })
        );
    }

    #[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 colors_borrows_without_clone() {
        let code = QrCode::new(b"hello").unwrap();
        let borrowed = code.colors();
        assert_eq!(borrowed.len(), code.width() * code.width());
        // matches the cloning accessor
        assert_eq!(borrowed, code.to_colors().as_slice());
    }

    #[test]
    fn module_storage_reads_and_writes_grid() {
        let mut code = QrCode::new(b"hello").unwrap();
        let width = code.width();
        let before = CoreModuleStorage::get(&code, 0, 0);
        CoreModuleStorage::set(&mut code, 0, 0, !before);
        assert_eq!(CoreModuleStorage::width(&code), width);
        assert_eq!(CoreModuleStorage::height(&code), width);
        assert_eq!(CoreModuleStorage::modules(&code).len(), width * width);
        assert_eq!(CoreModuleStorage::get(&code, 0, 0), !before);
    }

    #[test]
    fn module_source_exposes_read_only_grid() {
        let code = QrCode::new(b"hello").unwrap();
        let width = code.width();
        assert_eq!(CoreModuleSource::width(&code), width);
        assert_eq!(CoreModuleSource::height(&code), width);
        assert_eq!(CoreModuleSource::modules(&code), code.colors());
        assert_eq!(CoreModuleSource::get(&code, 0, 0), code[(0, 0)]);
    }

    #[test]
    fn qr_symbol_exposes_metadata() {
        let code = QrCode::with_version(b"hello", Version::Normal(1), EcLevel::H).unwrap();

        assert_eq!(QrSymbol::version(&code), Version::Normal(1));
        assert_eq!(QrSymbol::error_correction_level(&code), EcLevel::H);
        assert_eq!(QrSymbol::quiet_zone(&code), 4);
    }

    #[test]
    fn qr_symbol_uses_micro_quiet_zone() {
        let code = QrCode::with_version(b"123", Version::Micro(1), EcLevel::L).unwrap();

        assert_eq!(QrSymbol::quiet_zone(&code), 2);
    }

    #[test]
    fn module_view_exposes_borrowed_source() {
        let code = QrCode::new(b"hello").unwrap();
        let view = code.module_view();

        assert_eq!(view.width(), code.width());
        assert_eq!(view.height(), code.width());
        assert_eq!(view.modules(), code.colors());
        assert_eq!(view.get(0, 0), code[(0, 0)]);
    }

    #[test]
    fn qr_code_ref_exposes_borrowed_symbol() {
        let code = QrCode::with_version(b"hello", Version::Normal(1), EcLevel::H).unwrap();
        let borrowed = code.as_ref();

        assert_eq!(borrowed.width(), code.width());
        assert_eq!(borrowed.height(), code.width());
        assert_eq!(borrowed.modules(), code.colors());
        assert_eq!(borrowed.get(0, 0), code[(0, 0)]);
        assert_eq!(borrowed.version(), code.version());
        assert_eq!(borrowed.error_correction_level(), code.error_correction_level());
        assert_eq!(borrowed.quiet_zone(), 4);
    }

    #[test]
    fn render_error_is_available_from_facade() {
        let err = crate::render::RenderError::InvalidModuleSource { width: 3, height: 2, len: 4 };

        assert_eq!(err.to_string(), "invalid module source dimensions: width=3, height=2, len=4");
    }

    #[test]
    fn renderer_trait_path_matches_builder_output() {
        let code = QrCode::new(b"hello").unwrap();
        let builder_output = code.render::<char>().build();
        let renderer = code.render::<char>();
        let trait_output = CoreRenderer::render(&renderer, &code).unwrap();
        assert_eq!(trait_output, builder_output);
    }

    #[test]
    fn render_builder_matches_render_output() {
        let code = QrCode::new(b"render builder").unwrap();

        assert_eq!(code.render_builder::<char>().build(), code.render::<char>().build());
    }

    #[cfg(feature = "async")]
    #[test]
    fn render_async_matches_render_output() {
        let code = QrCode::new(b"render async").unwrap();
        let expected = code.render::<char>().build();
        let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
        let rendered = runtime.block_on(code.render_async::<char>()).unwrap();

        assert_eq!(rendered, expected);
    }

    #[test]
    fn renderer_from_symbol_matches_qrcode_render() {
        let code = QrCode::new(b"hello").unwrap();

        let from_symbol = crate::render::Renderer::<char>::from_symbol(&code)
            .quiet_zone(false)
            .dark_color('X')
            .light_color('.')
            .build();
        let from_qrcode = code.render::<char>().quiet_zone(false).dark_color('X').light_color('.').build();
        assert_eq!(from_symbol, from_qrcode);
    }

    #[test]
    fn renderer_from_borrowed_symbol_matches_owned_symbol() {
        let code = QrCode::with_version(b"123", Version::Micro(1), EcLevel::L).unwrap();
        let borrowed = code.as_ref();

        let from_borrowed =
            crate::render::Renderer::<char>::from_symbol(&borrowed).dark_color('X').light_color('.').build();
        let from_owned = crate::render::Renderer::<char>::from_symbol(&code).dark_color('X').light_color('.').build();

        assert_eq!(borrowed.quiet_zone(), 2);
        assert_eq!(from_borrowed, from_owned);
    }

    #[test]
    fn renderer_trait_accepts_read_only_module_source() {
        let code = QrCode::new(b"hello").unwrap();
        let mut inverted = code.to_colors();
        for color in &mut inverted {
            *color = !*color;
        }
        let view = ModuleView::new(&inverted, code.width()).unwrap();
        let mut renderer = code.render::<char>();
        renderer.quiet_zone(false).dark_color('X').light_color('.');

        let trait_output = CoreRenderer::render(&renderer, &view).unwrap();
        let expected = crate::render::Renderer::<char>::from_source(&view, 4)
            .quiet_zone(false)
            .dark_color('X')
            .light_color('.')
            .build();
        let original = code.render::<char>().quiet_zone(false).dark_color('X').light_color('.').build();
        assert_eq!(trait_output, expected);
        assert_ne!(trait_output, original);
    }

    #[test]
    fn batch_encodes_many_and_short_circuits() {
        let codes = QrCode::batch(vec![b"hi"; 1000], crate::EcLevel::M).unwrap();
        assert_eq!(codes.len(), 1000);
        // short-circuit: a 5000-byte input cannot fit even v40-L.
        let huge: Vec<u8> = (0..5000).map(|i| (i % 256) as u8).collect();
        let mixed: Vec<&[u8]> = vec![&b"ok"[..], &huge[..], &b"also ok"[..]];
        assert!(QrCode::batch(mixed, crate::EcLevel::L).is_err());
    }

    #[cfg(feature = "eps")]
    #[test]
    fn template_applies_colors() {
        let code = QrCode::new(b"template").unwrap();
        let minimal = code.render::<crate::render::eps::Color>().template(&crate::QrTemplate::minimal()).build();
        let dark = code.render::<crate::render::eps::Color>().template(&crate::QrTemplate::dark_mode()).build();
        // minimal => black foreground ("0 0 0 setrgbcolor"); dark_mode changes it.
        assert!(minimal.contains("0 0 0 setrgbcolor"), "minimal should use a black foreground");
        assert!(!dark.contains("0 0 0 setrgbcolor"), "dark_mode should change the foreground");
        assert_ne!(minimal, dark);
    }

    #[test]
    fn analyze_reports_diagnostics() {
        let code = QrCode::with_version(b"01234567", Version::Normal(1), crate::EcLevel::M).unwrap();
        let a = code.analyze();
        let total = code.width() * code.width();
        assert!(a.functional_modules() > 0, "should have functional modules");
        assert!(a.data_modules() > 0, "should have data modules");
        assert_eq!(a.functional_modules() + a.data_modules(), total);
        assert!(a.dark_ratio() > 0.0 && a.dark_ratio() < 1.0);
        let dark = code.colors().iter().filter(|c| **c == Color::Dark).count();
        assert!((a.dark_ratio() - dark as f64 / total as f64).abs() < 1e-9);
    }

    #[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);
    }
}