forgesworn-qr 0.3.14

QR code encoder and image decoder with no runtime dependencies, plus SVG and terminal rendering.
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
//! Reading a module grid: format and version information, bit placement,
//! unmasking, de-interleaving, Reed-Solomon, and the segments (SPEC.md decoder
//! steps 6 and 7).
//!
//! Native/default builds follow SPEC.md for a platform without character-set
//! decoders: ECI 26, 1, 3, 27, 170 and 23 are handled here. Packaged WASM uses
//! the `host-text` feature to ask its host during segment parsing. `bytes`
//! never depends on a character set.

use crate::tables::{ALIGNMENT_CENTRES, EC_BLOCKS};
use std::sync::OnceLock;

/// The error correction level of a symbol.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Ecc {
    L,
    M,
    Q,
    H,
}

impl Ecc {
    /// L, M, Q, H in the order of Table 9.
    pub const ORDER: [Ecc; 4] = [Ecc::L, Ecc::M, Ecc::Q, Ecc::H];

    pub fn letter(self) -> char {
        match self {
            Ecc::L => 'L',
            Ecc::M => 'M',
            Ecc::Q => 'Q',
            Ecc::H => 'H',
        }
    }

    pub(crate) fn index(self) -> usize {
        self as usize
    }
}

/// The header of a structured-append symbol.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StructuredAppend {
    /// This symbol's place in the set, counting from 0.
    pub index: u32,
    /// How many symbols the set has, 1 to 16.
    pub total: u32,
    /// The parity byte: the XOR of every byte of the whole message.
    pub parity: u32,
}

/// An FNC1 indicator. In alphanumeric segments `%` then reads as the group
/// separator U+001D and `%%` as `%`, in `text` and `bytes` alike.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Fnc1 {
    /// The GS1 format.
    First,
    /// An industry application: one letter or two digits.
    Second(String),
}

/// What a symbol says, once read.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Payload {
    pub text: String,
    /// Byte-mode data as stored, numeric and alphanumeric as ASCII, kanji as
    /// Shift_JIS pairs and hanzi as GB2312 pairs.
    pub bytes: Vec<u8>,
    pub version: usize,
    pub ecc: Ecc,
    pub mask: u8,
    /// ECI assignment numbers in the order they appeared; empty if none.
    pub eci: Vec<u32>,
    /// Codewords Reed-Solomon had to correct.
    pub corrected: usize,
    /// Present when the symbol is one of a structured-append set; `text` and
    /// `bytes` then hold this symbol's part only.
    pub structured_append: Option<StructuredAppend>,
    /// Present when the symbol carries an FNC1 indicator.
    pub fnc1: Option<Fnc1>,
}

// GF(256) with 0x11D.

const fn exp_table() -> [u8; 512] {
    let mut exp = [0u8; 512];
    let mut x: u32 = 1;
    let mut i = 0;
    while i < 255 {
        exp[i] = x as u8;
        x <<= 1;
        if x & 0x100 != 0 {
            x ^= 0x11d;
        }
        i += 1;
    }
    while i < 512 {
        exp[i] = exp[i - 255];
        i += 1;
    }
    exp
}

const fn log_table() -> [u8; 256] {
    let exp = exp_table();
    let mut log = [0u8; 256];
    let mut i = 0;
    while i < 255 {
        log[exp[i] as usize] = i as u8;
        i += 1;
    }
    log
}

pub(crate) const EXP: [u8; 512] = exp_table();
const LOG: [u8; 256] = log_table();

// QR's error-correction blocks use at most 30 syndrome roots. Each row
// multiplies every byte by EXP[j], so the syndrome loop needs one lookup.
const fn syndrome_table() -> [[u8; 256]; 30] {
    let mut table = [[0u8; 256]; 30];
    let mut j = 0;
    while j < 30 {
        let mut value = 1;
        while value < 256 {
            table[j][value] = EXP[LOG[value] as usize + j];
            value += 1;
        }
        j += 1;
    }
    table
}

static SYNDROME_MUL: [[u8; 256]; 30] = syndrome_table();

pub(crate) fn gf_mul(a: u8, b: u8) -> u8 {
    if a == 0 || b == 0 {
        0
    } else {
        EXP[LOG[a as usize] as usize + LOG[b as usize] as usize]
    }
}

/// `a / b`; `b` is never zero where this is used.
fn gf_div(a: u8, b: u8) -> u8 {
    debug_assert!(b != 0);
    if a == 0 {
        0
    } else {
        EXP[(LOG[a as usize] as usize + 255 - LOG[b as usize] as usize) % 255]
    }
}

/// `poly` is lowest power first.
fn evaluate(poly: &[u8], x: u8) -> u8 {
    let mut y = 0u8;
    for &c in poly.iter().rev() {
        y = gf_mul(y, x) ^ c;
    }
    y
}

/// Evaluates one syndrome, with the generic field operation beyond QR's roots.
#[inline]
fn syndrome(block: &[u8], j: usize) -> u8 {
    let mut s = 0u8;
    let x = EXP[j];
    if j == 0 {
        for &b in block { s ^= b; }
    } else if j < SYNDROME_MUL.len() {
        let row = &SYNDROME_MUL[j];
        for &b in block { s = row[s as usize] ^ b; }
    } else {
        for &b in block { s = gf_mul(s, x) ^ b; }
    }
    s
}

/// Corrects `block` (data codewords then `ec_count` check codewords) in
/// place. Returns the number of codewords corrected, or `None` when the block
/// has more errors than the code can correct.
pub fn correct(block: &mut [u8], ec_count: usize) -> Option<usize> {
    let n = block.len();
    let mut syndromes: Vec<u8> = Vec::with_capacity(ec_count);
    let mut clean = true;
    for j in 0..ec_count {
        let s = syndrome(block, j);
        syndromes.push(s);
        if s != 0 {
            clean = false;
        }
    }
    if clean {
        return Some(0);
    }

    // Berlekamp-Massey: the error locator.
    let mut locator: Vec<u8> = vec![1];
    let mut previous: Vec<u8> = vec![1];
    let mut errors = 0usize;
    let mut shift = 1usize;
    let mut last_discrepancy = 1u8;
    for k in 0..ec_count {
        let mut d = syndromes[k];
        for i in 1..=errors {
            d ^= gf_mul(locator.get(i).copied().unwrap_or(0), syndromes[k - i]);
        }
        if d == 0 {
            shift += 1;
            continue;
        }
        let factor = gf_div(d, last_discrepancy);
        let mut next = locator.clone();
        for (i, &p) in previous.iter().enumerate() {
            let at = i + shift;
            while next.len() <= at {
                next.push(0);
            }
            next[at] ^= gf_mul(factor, p);
        }
        if 2 * errors <= k {
            previous = locator;
            errors = k + 1 - errors;
            last_discrepancy = d;
            shift = 1;
        } else {
            shift += 1;
        }
        locator = next;
    }
    while locator.len() > 1 && locator[locator.len() - 1] == 0 {
        locator.pop();
    }
    if errors * 2 > ec_count || locator.len() - 1 != errors {
        return None;
    }

    // Chien search: a root at alpha^-p marks an error at power p, index n - 1 - p.
    let mut powers: Vec<usize> = Vec::new();
    for p in 0..n {
        if evaluate(&locator, EXP[(255 - p % 255) % 255]) == 0 {
            powers.push(p);
        }
    }
    if powers.len() != errors {
        return None;
    }

    // Forney: omega = S * locator mod x^ec_count; e = X * omega(1/X) / locator'(1/X) for first root alpha^0.
    let mut omega = vec![0u8; ec_count];
    for i in 0..ec_count {
        let mut j = 0;
        while j < locator.len() && i + j < ec_count {
            omega[i + j] ^= gf_mul(syndromes[i], locator[j]);
            j += 1;
        }
    }
    let mut derivative: Vec<u8> = Vec::new();
    for i in 1..locator.len() {
        derivative.push(if i % 2 == 1 { locator[i] } else { 0 });
    }
    for &p in &powers {
        let x = EXP[p % 255];
        let x_inverse = EXP[(255 - p % 255) % 255];
        let denominator = evaluate(&derivative, x_inverse);
        if denominator == 0 {
            return None;
        }
        block[n - 1 - p] ^= gf_mul(x, gf_div(evaluate(&omega, x_inverse), denominator));
    }
    Some(errors)
}

// Format and version information.

pub(crate) const FORMAT_COORDS: [(usize, usize); 15] = [
    (8, 0),
    (8, 1),
    (8, 2),
    (8, 3),
    (8, 4),
    (8, 5),
    (8, 7),
    (8, 8),
    (7, 8),
    (5, 8),
    (4, 8),
    (3, 8),
    (2, 8),
    (1, 8),
    (0, 8),
];

pub(crate) const fn format_bits_of(ecc_bits: u32, mask: u32) -> u32 {
    let data = (ecc_bits << 3) | mask;
    let mut rem = data;
    let mut i = 0;
    while i < 10 {
        rem = (rem << 1) ^ ((rem >> 9) * 0x537);
        i += 1;
    }
    ((data << 10) | rem) ^ 0x5412
}

pub(crate) const fn version_bits_of(version: u32) -> u32 {
    let mut rem = version;
    let mut i = 0;
    while i < 12 {
        rem = (rem << 1) ^ ((rem >> 11) * 0x1f25);
        i += 1;
    }
    (version << 12) | rem
}

/// Every (level, mask) with its 15 format bits, in the order L, M, Q, H and masks 0 to 7.
const fn formats() -> [(u32, Ecc, u8); 32] {
    let mut out = [(0u32, Ecc::L, 0u8); 32];
    let mut e = 0;
    while e < 4 {
        let (ecc, bits) = match e {
            0 => (Ecc::L, 1),
            1 => (Ecc::M, 0),
            2 => (Ecc::Q, 3),
            _ => (Ecc::H, 2),
        };
        let mut m = 0;
        while m < 8 {
            out[e * 8 + m] = (format_bits_of(bits, m as u32), ecc, m as u8);
            m += 1;
        }
        e += 1;
    }
    out
}

pub(crate) const FORMATS: [(u32, Ecc, u8); 32] = formats();

const fn versions() -> [u32; 34] {
    let mut out = [0u32; 34];
    let mut i = 0;
    while i < 34 {
        out[i] = version_bits_of(i as u32 + 7);
        i += 1;
    }
    out
}

const VERSIONS: [u32; 34] = versions();

/// The entry whose bits are nearest (within three bit errors) to either read:
/// the first read, then the first entry, wins a tie.
fn nearest(table: &[u32], reads: &[u32]) -> Option<usize> {
    let mut best = None;
    let mut distance = 4; // both codes correct up to three bit errors
    for &read in reads {
        for (i, &bits) in table.iter().enumerate() {
            let d = (bits ^ read).count_ones();
            if d < distance {
                distance = d;
                best = Some(i);
            }
        }
    }
    best
}

/// The reserved (function pattern) modules of a version: finders and
/// separators, timing, alignment, format and version information, and the dark module.
pub(crate) fn reserved(version: usize) -> Vec<bool> {
    let s = 17 + 4 * version;
    let mut reserved = vec![false; s * s];
    for (left, top) in [(0i32, 0i32), (s as i32 - 7, 0), (0, s as i32 - 7)] {
        // The finder and its separator, clipped to the grid.
        for dy in -1..=7 {
            for dx in -1..=7 {
                let (x, y) = (left + dx, top + dy);
                if x >= 0 && y >= 0 && x < s as i32 && y < s as i32 {
                    reserved[y as usize * s + x as usize] = true;
                }
            }
        }
    }
    reserved[(s - 8) * s + 8] = true;
    // Alignment centres that fall inside a finder are skipped.
    let centres = ALIGNMENT_CENTRES[version - 1];
    for &cy in centres {
        for &cx in centres {
            let (cx, cy) = (cx as usize, cy as usize);
            if reserved[cy * s + cx] {
                continue;
            }
            for dy in 0..5 {
                for dx in 0..5 {
                    reserved[(cy + dy - 2) * s + cx + dx - 2] = true;
                }
            }
        }
    }
    for i in 8..s - 8 {
        reserved[6 * s + i] = true;
        reserved[i * s + 6] = true;
    }
    for (i, &(x, y)) in FORMAT_COORDS.iter().enumerate() {
        reserved[y * s + x] = true;
        if i < 8 {
            reserved[8 * s + s - 1 - i] = true;
        } else {
            reserved[(s - 7 + (i - 8)) * s + 8] = true;
        }
    }
    if version >= 7 {
        for i in 0..6 {
            for j in 0..3 {
                reserved[(s - 11 + j) * s + i] = true;
                reserved[i * s + s - 11 + j] = true;
            }
        }
    }
    reserved
}

static PLACEMENTS: [OnceLock<Vec<u16>>; 41] = [const { OnceLock::new() }; 41];

/// The modules of a version that carry the bit stream, in the order the
/// standard places it: two columns at a time from the right, snaking up and
/// down, skipping the function patterns. Each is `y * 256 + x`. Worked out
/// once a version and kept.
pub(crate) fn placement(version: usize) -> &'static [u16] {
    PLACEMENTS[version].get_or_init(|| {
        let size = 17 + 4 * version;
        let reserved = reserved(version);
        let mut found: Vec<u16> = Vec::new();
        let mut upward = true;
        let mut right = size as i32 - 1;
        while right >= 1 {
            if right == 6 {
                right = 5;
            }
            for step in 0..size {
                let y = if upward { size - 1 - step } else { step };
                for i in 0..2 {
                    let x = (right - i) as usize;
                    if !reserved[y * size + x] {
                        found.push(((y << 8) | x) as u16);
                    }
                }
            }
            upward = !upward;
            right -= 2;
        }
        found
    })
}

pub(crate) fn mask_bit(mask: u8, x: usize, y: usize) -> bool {
    match mask {
        0 => (x + y) % 2 == 0,
        1 => y % 2 == 0,
        2 => x % 3 == 0,
        3 => (x + y) % 3 == 0,
        4 => (y / 2 + x / 3) % 2 == 0,
        5 => (x * y) % 2 + (x * y) % 3 == 0,
        6 => ((x * y) % 2 + (x * y) % 3) % 2 == 0,
        _ => (((x + y) % 2) + ((x * y) % 3)) % 2 == 0,
    }
}

fn blocks_for(version: usize, ecc: Ecc) -> [usize; 4] {
    EC_BLOCKS[version - 1][ecc.index()].map(|v| v as usize)
}

/// The version a symbol of `size` modules declares: from the size below
/// version 7, else from its version blocks, or `None` when neither copy decodes.
pub fn read_version<R: Fn(usize, usize) -> bool>(read: &R, size: usize) -> Option<usize> {
    if size < 45 {
        return Some((size - 17) / 4);
    }
    let mut bottom_left = 0u32;
    let mut top_right = 0u32;
    for k in (0..=17).rev() {
        let i = k / 3;
        let j = k % 3;
        bottom_left = (bottom_left << 1) | read(i, size - 11 + j) as u32;
        top_right = (top_right << 1) | read(size - 11 + j, i) as u32;
    }
    nearest(&VERSIONS, &[bottom_left, top_right]).map(|i| i + 7)
}

/// A version independently supported by both version-information copies.
/// Unlike `read_version`, this does not accept a single readable copy.
pub(crate) fn agreed_version<R: Fn(usize, usize) -> bool>(read: &R, size: usize) -> Option<usize> {
    if size < 45 { return None; }
    let mut bottom_left = 0u32;
    let mut top_right = 0u32;
    for k in (0..=17).rev() {
        let i = k / 3;
        let j = k % 3;
        bottom_left = (bottom_left << 1) | read(i, size - 11 + j) as u32;
        top_right = (top_right << 1) | read(size - 11 + j, i) as u32;
    }
    let a = nearest(&VERSIONS, &[bottom_left])?;
    let b = nearest(&VERSIONS, &[top_right])?;
    (a == b).then_some(a + 7)
}

/// Header evidence for a deferred curvature recovery.
pub(crate) fn curvature_header<R: Fn(usize, usize) -> bool>(read: &R, size: usize) -> Option<(Ecc, u8, u32)> {
    curvature_header_with_conflict(read, size, false).map(|(ecc, mask, distance, _)| (ecc, mask, distance))
}

pub(crate) fn curvature_header_with_conflict<R: Fn(usize, usize) -> bool>(read: &R, size: usize, allow_conflict: bool) -> Option<(Ecc, u8, u32, bool)> {
    if size < 45 { return None; }
    let mut va = 0u32;
    let mut vb = 0u32;
    for k in (0..=17).rev() {
        let i = k / 3;
        let j = k % 3;
        va = (va << 1) | read(i, size - 11 + j) as u32;
        vb = (vb << 1) | read(size - 11 + j, i) as u32;
    }
    let version = (size - 17) / 4;
    let expected = version_bits_of(version as u32);
    if va != expected && vb != expected { return None; }
    if nearest(&VERSIONS, &[va]).is_some_and(|i| i + 7 != version)
        || nearest(&VERSIONS, &[vb]).is_some_and(|i| i + 7 != version) { return None; }
    let mut a = 0u32;
    let mut b = 0u32;
    for i in (0..15).rev() {
        let (x, y) = FORMAT_COORDS[i];
        a = (a << 1) | read(x, y) as u32;
        let (x, y) = if i < 8 { (size - 1 - i, 8) } else { (8, size - 7 + i - 8) };
        b = (b << 1) | read(x, y) as u32;
    }
    let words = FORMATS.map(|f| f.0);
    let first = nearest(&words, &[a]);
    let second = nearest(&words, &[b]);
    if let (Some(first), Some(second)) = (first, second) {
        if first != second {
            if !allow_conflict { return None; }
            let da = (words[first] ^ a).count_ones();
            let db = (words[second] ^ b).count_ones();
            let distance = da.min(db);
            if distance > 2 || da.max(db) != 3 { return None; }
            let (_, ecc, mask) = FORMATS[if da < db { first } else { second }];
            return Some((ecc, mask, distance, true));
        }
    }
    let (bits, ecc, mask) = FORMATS[first.or(second)?];
    Some((ecc, mask, (bits ^ a).count_ones().min((bits ^ b).count_ones()), false))
}

/// Exact version anchor with a contradictory distance-three version peer and
/// two independently decoded, agreeing format copies, for late recovery only.
pub(crate) fn version_peer_header<R: Fn(usize, usize) -> bool>(read: &R, size: usize) -> Option<(Ecc, u8, u32)> {
    if !(45..=177).contains(&size) || (size - 17) % 4 != 0 { return None; }
    let mut va = 0u32;
    let mut vb = 0u32;
    for k in (0..=17).rev() {
        let i = k / 3;
        let j = k % 3;
        va = (va << 1) | read(i, size - 11 + j) as u32;
        vb = (vb << 1) | read(size - 11 + j, i) as u32;
    }
    let version = (size - 17) / 4;
    let expected = version_bits_of(version as u32);
    if va != expected && vb != expected { return None; }
    let word = if va == expected { vb } else { va };
    let peer = nearest(&VERSIONS, &[word])?;
    if peer + 7 == version || (VERSIONS[peer] ^ word).count_ones() != 3 { return None; }
    let mut a = 0u32;
    let mut b = 0u32;
    for i in (0..15).rev() {
        let (x, y) = FORMAT_COORDS[i];
        a = (a << 1) | read(x, y) as u32;
        let (x, y) = if i < 8 { (size - 1 - i, 8) } else { (8, size - 7 + i - 8) };
        b = (b << 1) | read(x, y) as u32;
    }
    let words = FORMATS.map(|f| f.0);
    let first = nearest(&words, &[a])?;
    let second = nearest(&words, &[b])?;
    if first != second { return None; }
    let (bits, ecc, mask) = FORMATS[first];
    Some((ecc, mask, (bits ^ a).count_ones().min((bits ^ b).count_ones())))
}

/// The errors a block of this symbol may have had corrected: half of its check
/// codewords once the p of Table 9 is withheld to catch a misdecode. Only
/// versions 1 to 3 withhold any.
pub fn correctable(version: usize, ecc: Ecc) -> usize {
    let p = match (version, ecc) {
        (1, Ecc::L) => 3,
        (1, Ecc::M) => 2,
        (1, _) => 1,
        (2, Ecc::L) => 2,
        (3, Ecc::L) => 1,
        _ => 0,
    };
    (blocks_for(version, ecc)[0] - p) >> 1
}

/// Decodes a symbol from its modules (`read(x, y)` is true for dark). `size`
/// must be 17 + 4v. From version 7 a version block that decodes decides, and a
/// size that disagrees fails; if neither decodes, the size decides. Returns
/// `None` when the symbol cannot be read.
pub fn read_symbol<R: Fn(usize, usize) -> bool>(read: R, size: usize) -> Option<Payload> {
    if !(21..=177).contains(&size) || (size - 17) % 4 != 0 {
        return None;
    }
    // When neither version copy decodes, the size says which version it is.
    let version = read_version(&read, size).unwrap_or((size - 17) / 4);
    if 17 + 4 * version != size {
        return None;
    }

    let mut first = 0u32;
    let mut second = 0u32;
    for i in (0..15).rev() {
        let (x, y) = FORMAT_COORDS[i];
        first = (first << 1) | read(x, y) as u32;
        let (sx, sy) = if i < 8 { (size - 1 - i, 8) } else { (8, size - 7 + (i - 8)) };
        second = (second << 1) | read(sx, sy) as u32;
    }
    let format = nearest(&FORMATS.map(|f| f.0), &[first, second])?;
    let (_, ecc, mask) = FORMATS[format];

    let [ec_per_block, g1, d1, g2] = blocks_for(version, ecc);
    let block_count = g1 + g2;
    let data_count = g1 * d1 + g2 * (d1 + 1);
    let places = placement(version);
    let word = |index: usize| {
        let mut value = 0u8;
        for bit in index * 8..((index + 1) * 8).min(places.len()) {
            let x = (places[bit] & 255) as usize;
            let y = (places[bit] >> 8) as usize;
            if read(x, y) != mask_bit(mask, x, y) {
                value |= 0x80 >> (bit & 7);
            }
        }
        value
    };
    // Read interleaved blocks on demand: a failed block rejects the symbol,
    // so later blocks need neither sampling nor allocating.
    let mut data: Vec<u8> = Vec::with_capacity(data_count);
    let mut corrected = 0;
    let limit = correctable(version, ecc);
    for b in 0..block_count {
        let length = if b < g1 { d1 } else { d1 + 1 };
        let mut block = vec![0u8; length + ec_per_block];
        for i in 0..d1 { block[i] = word(i * block_count + b); }
        if b >= g1 { block[d1] = word(d1 * block_count + b - g1); }
        for i in 0..ec_per_block { block[length + i] = word(data_count + i * block_count + b); }
        let fixed = correct(&mut block, ec_per_block)?;
        if fixed > limit {
            return None;
        }
        corrected += fixed;
        data.extend_from_slice(&block[..length]);
    }

    // Zero in every data codeword is what a texture matching the mask pattern
    // corrects to, and it parses as a terminator: no symbol holds it.
    if data.iter().all(|&w| w == 0) {
        return None;
    }

    let parsed = parse(&data, version)?;
    Some(Payload {
        text: parsed.text,
        bytes: parsed.bytes,
        version,
        ecc,
        mask,
        eci: parsed.eci,
        corrected,
        structured_append: parsed.structured_append,
        fnc1: parsed.fnc1,
    })
}

struct Bits<'a> {
    data: &'a [u8],
    position: usize,
}

impl Bits<'_> {
    fn available(&self) -> usize {
        self.data.len() * 8 - self.position
    }

    /// `count` bits, most significant first, or `None` past the end.
    fn read(&mut self, count: usize) -> Option<u32> {
        if count > self.available() {
            return None;
        }
        let mut value = 0u32;
        for _ in 0..count {
            value = (value << 1) | ((self.data[self.position >> 3] >> (7 - (self.position & 7))) & 1) as u32;
            self.position += 1;
        }
        Some(value)
    }
}

struct Run {
    eci: Option<u32>,
    bytes: Vec<u8>,
    /// Text already decided, for a kanji or hanzi character.
    fixed: Option<String>,
}

pub(crate) const ALPHANUMERIC: &[u8; 45] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
const KANJI_COUNT_BITS: [usize; 3] = [8, 10, 12];

struct Parsed {
    text: String,
    bytes: Vec<u8>,
    eci: Vec<u32>,
    structured_append: Option<StructuredAppend>,
    fnc1: Option<Fnc1>,
}

fn count_band(version: usize) -> usize {
    if version <= 9 {
        0
    } else if version <= 26 {
        1
    } else {
        2
    }
}

/// ISO 18004 7.4.8.3: 0-99 are two digits, ASCII + 100 gives a letter.
fn application_indicator(value: u32) -> Option<String> {
    if value <= 99 {
        return Some(format!("{value:02}"));
    }
    if (165..=190).contains(&value) || (197..=222).contains(&value) {
        return Some(((value - 100) as u8 as char).to_string());
    }
    None
}

fn parse(data: &[u8], version: usize) -> Option<Parsed> {
    let mut bits = Bits { data, position: 0 };
    let band = count_band(version);
    let mut runs: Vec<Run> = vec![Run { eci: None, bytes: Vec::new(), fixed: None }];
    let mut eci: Vec<u32> = Vec::new();
    let mut out: Vec<u8> = Vec::new();
    let mut structured_append: Option<StructuredAppend> = None;
    let mut fnc1: Option<Fnc1> = None;
    fn emit(runs: &mut [Run], out: &mut Vec<u8>, byte: u8) {
        runs.last_mut().unwrap().bytes.push(byte);
        out.push(byte);
    }
    // Running out of data mid-segment is no read.
    while bits.available() >= 4 {
        let mode = bits.read(4)?;
        if mode == 0 {
            break;
        }
        match mode {
            1 => {
                let mut count = bits.read([10, 12, 14][band])?;
                while count >= 3 {
                    let v = bits.read(10)?;
                    if v > 999 {
                        return None;
                    }
                    for c in format!("{v:03}").bytes() {
                        emit(&mut runs, &mut out, c);
                    }
                    count -= 3;
                }
                if count > 0 {
                    let v = bits.read(if count == 2 { 7 } else { 4 })?;
                    if v >= if count == 2 { 100 } else { 10 } {
                        return None;
                    }
                    for c in format!("{:0width$}", v, width = count as usize).bytes() {
                        emit(&mut runs, &mut out, c);
                    }
                }
            }
            2 => {
                let mut count = bits.read([9, 11, 13][band])?;
                let mut segment: Vec<u8> = Vec::new();
                while count >= 2 {
                    let v = bits.read(11)?;
                    if v >= 45 * 45 {
                        return None;
                    }
                    segment.push(ALPHANUMERIC[(v / 45) as usize]);
                    segment.push(ALPHANUMERIC[(v % 45) as usize]);
                    count -= 2;
                }
                if count == 1 {
                    let v = bits.read(6)?;
                    if v >= 45 {
                        return None;
                    }
                    segment.push(ALPHANUMERIC[v as usize]);
                }
                // Under FNC1, within one segment: %% is %, and a lone % is the group separator.
                let mut i = 0;
                while i < segment.len() {
                    if fnc1.is_some() && segment[i] == 0x25 {
                        if segment.get(i + 1) == Some(&0x25) {
                            i += 1;
                        } else {
                            emit(&mut runs, &mut out, 0x1d);
                            i += 1;
                            continue;
                        }
                    }
                    emit(&mut runs, &mut out, segment[i]);
                    i += 1;
                }
            }
            4 => {
                let count = bits.read([8, 16, 16][band])?;
                for _ in 0..count {
                    let b = bits.read(8)? as u8;
                    emit(&mut runs, &mut out, b);
                }
            }
            8 => {
                // Kanji: kept as its Shift_JIS bytes; each character's text is the platform's
                // Shift_JIS, or a single U+FFFD without host support (SPEC.md).
                let count = bits.read(KANJI_COUNT_BITS[band])?;
                for _ in 0..count {
                    let v = bits.read(13)?;
                    let mut sjis = ((v / 0xc0) << 8) | (v % 0xc0);
                    sjis += if sjis < 0x1f00 { 0x8140 } else { 0xc140 };
                    out.push((sjis >> 8) as u8);
                    out.push((sjis & 0xff) as u8);
                    let current = runs.last().unwrap().eci;
                    runs.push(Run { eci: current, bytes: Vec::new(), fixed: Some(kanji_text(sjis)) });
                    runs.push(Run { eci: current, bytes: Vec::new(), fixed: None });
                }
            }
            13 => {
                // Hanzi (GB/T 18284): subset 1 is GB2312, kept as its bytes; any other subset, or a
                // value outside the GB2312 rows or on a cell the editions disagree on, rejects the symbol.
                //
                // The reference ports also refuse a pair their GB 18030 decoder makes nothing of (an
                // empty GB2312 cell). This port has no such decoder and cannot tell, so with
                // `HANZI` false it refuses every hanzi symbol sooner than read one they would not.
                if !HANZI {
                    return None;
                }
                if bits.read(4)? != 1 {
                    return None;
                }
                let count = bits.read(KANJI_COUNT_BITS[band])?;
                for _ in 0..count {
                    let v = bits.read(13)?;
                    let row = v / 0x60;
                    let lead = row + if row < 0x0a { 0xa1 } else { 0xa6 };
                    let low = (v % 0x60) + 0xa1;
                    let text = hanzi_text(lead, low)?;
                    out.push(lead as u8);
                    out.push(low as u8);
                    let current = runs.last().unwrap().eci;
                    runs.push(Run { eci: current, bytes: Vec::new(), fixed: Some(text) });
                    runs.push(Run { eci: current, bytes: Vec::new(), fixed: None });
                }
            }
            7 => {
                let first = bits.read(8)?;
                let value = if first & 0x80 == 0 {
                    first
                } else if first & 0xc0 == 0x80 {
                    ((first & 0x3f) << 8) | bits.read(8)?
                } else if first & 0xe0 == 0xc0 {
                    ((first & 0x1f) << 16) | bits.read(16)?
                } else {
                    return None;
                };
                eci.push(value);
                runs.push(Run { eci: Some(value), bytes: Vec::new(), fixed: None });
            }
            3 => {
                let sequence = bits.read(8)?;
                let parity = bits.read(8)?;
                if structured_append.is_none() {
                    structured_append = Some(StructuredAppend { index: sequence >> 4, total: (sequence & 15) + 1, parity });
                }
            }
            5 => {
                if fnc1.is_none() {
                    fnc1 = Some(Fnc1::First);
                }
            }
            9 => {
                let indicator = application_indicator(bits.read(8)?)?;
                if fnc1.is_none() {
                    fnc1 = Some(Fnc1::Second(indicator));
                }
            }
            _ => return None,
        }
    }
    let mut text = String::new();
    for run in &runs {
        text.push_str(&decode_run(run));
    }
    Some(Parsed { text, bytes: out, eci, structured_append, fnc1 })
}

// Native/default builds have no character-set tables beyond Windows 1252.
// The packaged WASM feature asks its host while parsing each individual run.
#[cfg(all(target_arch = "wasm32", feature = "host-text"))]
#[link(wasm_import_module = "qr_text")]
extern "C" {
    #[link_name = "decode"]
    fn import_text(kind: u32, value: u32, input: *const u8, length: usize, output: *mut u8, capacity: usize) -> i32;
}

fn host_text(kind: u32, value: u32, bytes: &[u8]) -> Option<String> {
    #[cfg(all(target_arch = "wasm32", feature = "host-text"))]
    {
        // Every input byte can become at most one Unicode scalar (four UTF-8
        // bytes). Kanji/hanzi pass a packed pair instead and need four bytes.
        let capacity = bytes.len().checked_mul(4)?.checked_add(4)?;
        let mut output = vec![0u8; capacity];
        let count = unsafe { import_text(kind, value, bytes.as_ptr(), bytes.len(), output.as_mut_ptr(), capacity) };
        if count < 0 || count as usize > capacity { return None; }
        output.truncate(count as usize);
        String::from_utf8(output).ok()
    }
    #[cfg(not(all(target_arch = "wasm32", feature = "host-text")))]
    {
        let _ = (kind, value, bytes);
        None
    }
}

/// Whether hanzi-mode symbols are read at all. Off: without a GB 18030 decoder
/// an empty GB2312 cell cannot be told from a character, and the reference
/// ports refuse a symbol that holds one. A host that can check the pairs may
/// turn this on once the port gives it the means.
const HANZI: bool = cfg!(all(target_arch = "wasm32", feature = "host-text"));

/// A kanji-mode character through the host, or U+FFFD without Shift_JIS.
fn kanji_text(sjis: u32) -> String {
    host_text(1, sjis, &[]).unwrap_or_else(|| "\u{fffd}".to_string())
}

/// Whether a hanzi pair names a character on a platform with a GB 18030
/// decoder: the pair must lie in the GB2312 rows and cells, and not be one of
/// the twelve cells that editions disagree on. With no decoder here, a valid
/// pair reads as a single U+FFFD, as for kanji. `None` rejects the symbol.
fn hanzi_text(lead: u32, low: u32) -> Option<String> {
    if !(0xa1..=0xfe).contains(&low) || !(0xa1..=0xf7).contains(&lead) || (lead > 0xa9 && lead < 0xb0) {
        return None;
    }
    if edition_dependent(lead, low) {
        return None;
    }
    if HANZI { return host_text(2, (lead << 8) | low, &[]); }
    Some("\u{fffd}".to_string())
}

/// Twelve cells GB2312 leaves empty that GBK and older GB 18030 tables make
/// private-use and newer GB 18030 tables make characters.
fn edition_dependent(lead: u32, low: u32) -> bool {
    if lead == 0xa6 {
        return (0xd9..=0xdf).contains(&low) || low == 0xec || low == 0xed || low == 0xf3;
    }
    lead == 0xa8 && (low == 0xbc || low == 0xbf)
}

/// Length of the well-formed UTF-8 sequence at `i`, or 0 if it is not one.
fn sequence(bytes: &[u8], i: usize) -> usize {
    let b = bytes[i];
    if b < 0x80 {
        return 1;
    }
    let length = if (0xc2..=0xdf).contains(&b) {
        2
    } else if (0xe0..=0xef).contains(&b) {
        3
    } else if (0xf0..=0xf4).contains(&b) {
        4
    } else {
        0
    };
    if length == 0 || i + length > bytes.len() {
        return 0;
    }
    let second = bytes[i + 1];
    let low = if b == 0xe0 {
        0xa0
    } else if b == 0xf0 {
        0x90
    } else {
        0x80
    };
    let high = if b == 0xed {
        0x9f
    } else if b == 0xf4 {
        0x8f
    } else {
        0xbf
    };
    if second < low || second > high {
        return 0;
    }
    for k in 2..length {
        if bytes[i + k] & 0xc0 != 0x80 {
            return 0;
        }
    }
    length
}

/// True when `bytes` is entirely well-formed UTF-8.
pub fn is_utf8(bytes: &[u8]) -> bool {
    let mut i = 0;
    while i < bytes.len() {
        let n = sequence(bytes, i);
        if n == 0 {
            return false;
        }
        i += n;
    }
    true
}

/// Decodes UTF-8, replacing each ill-formed byte with U+FFFD.
pub fn from_utf8(bytes: &[u8]) -> String {
    let mut out = String::new();
    let mut i = 0;
    while i < bytes.len() {
        let n = sequence(bytes, i);
        if n == 0 {
            out.push('\u{fffd}');
            i += 1;
            continue;
        }
        let b = bytes[i] as u32;
        let mut cp = if n == 1 { b } else { b & (0xff >> (n + 1)) };
        for k in 1..n {
            cp = (cp << 6) | (bytes[i + k] as u32 & 0x3f);
        }
        out.push(char::from_u32(cp).unwrap_or('\u{fffd}'));
        i += n;
    }
    out
}

fn latin1(bytes: &[u8]) -> String {
    bytes.iter().map(|&b| b as char).collect()
}

/// Windows 1252 at bytes 0x80 to 0x9F, 0 where the code page leaves the byte undefined.
const WINDOWS_1252: [u32; 32] = [
    0x20ac, 0, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0, 0x017d, 0, 0, 0x2018, 0x2019, 0x201c,
    0x201d, 0x2022, 0x2013, 0x2014, 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0, 0x017e, 0x0178,
];

/// Text for a run under an ECI the hand-written sets cover (27, 170 and 23),
/// or a host-supported set. Without host support, the other sets are absent.
fn from_eci(eci: u32, bytes: &[u8]) -> Option<String> {
    match eci {
        27 | 170 => Some(bytes.iter().map(|&b| if b < 0x80 { b as char } else { '\u{fffd}' }).collect()),
        23 => Some(
            bytes
                .iter()
                .map(|&b| {
                    if !(0x80..=0x9f).contains(&b) {
                        b as char
                    } else {
                        let cp = WINDOWS_1252[b as usize - 0x80];
                        char::from_u32(if cp == 0 { 0xfffd } else { cp }).unwrap()
                    }
                })
                .collect(),
        ),
        _ => host_text(0, eci, bytes),
    }
}

/// Text for bytes under an ECI this port cannot read: never a guess at another
/// character set. Under a single-byte set (ISO 8859, the Windows code pages),
/// which is ASCII below 0x80, those bytes are kept; every other byte, and every
/// byte under any other ECI, is U+FFFD.
fn unread(eci: u32, bytes: &[u8]) -> String {
    let ascii = matches!(eci, 4..=13 | 15..=18 | 21 | 22 | 24);
    bytes.iter().map(|&b| if ascii && b < 0x80 { b as char } else { '\u{fffd}' }).collect()
}

/// ECI 26 is UTF-8; 3 and 1 are Latin-1; 27, 170 and 23 by hand. Every other
/// ECI is a set this port lacks, and is not guessed at (`unread`). With no
/// ECI, valid UTF-8 is UTF-8, else Latin-1; the Shift_JIS rule for that case
/// needs a Shift_JIS decoder and, with none, ends in Latin-1 all the same.
fn decode_run(run: &Run) -> String {
    if let Some(text) = &run.fixed {
        return text.clone();
    }
    let bytes = &run.bytes;
    if run.eci == Some(3) || run.eci == Some(1) {
        return latin1(bytes);
    }
    if run.eci == Some(26) {
        return from_utf8(bytes);
    }
    if let Some(eci) = run.eci {
        if !bytes.is_empty() {
            return from_eci(eci, bytes).unwrap_or_else(|| unread(eci, bytes));
        }
    }
    if is_utf8(bytes) {
        return from_utf8(bytes);
    }
    host_text(3, 0, bytes).unwrap_or_else(|| latin1(bytes))
}

/// A symbol read from a module grid, with whether the grid was read transposed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Decoded {
    pub payload: Payload,
    pub mirrored: bool,
}

/// Reads a symbol from its module grid, `size` by `size`, row by row, nonzero
/// for dark, with no quiet zone. Mirrored grids read too. `None` when the
/// symbol cannot be read, or when `modules` holds fewer than `size * size`
/// (the TypeScript throws a RangeError there).
pub fn decode_modules(modules: &[u8], size: usize) -> Option<Decoded> {
    // Bound the product before checking the caller's module buffer.
    if !(21..=177).contains(&size) || (size - 17) % 4 != 0 {
        return None;
    }
    if modules.len() < size * size {
        return None;
    }
    if let Some(payload) = read_symbol(|x, y| modules[y * size + x] != 0, size) {
        return Some(Decoded { payload, mirrored: false });
    }
    read_symbol(|x, y| modules[x * size + y] != 0, size).map(|payload| Decoded { payload, mirrored: true })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn module_grid_sizes_are_bounded_before_buffer_arithmetic() {
        for size in [0, 20, 22, 176, 178, usize::MAX / 2 + 1, usize::MAX] {
            assert!(decode_modules(&[], size).is_none(), "size {size}");
        }
        for version in [1, 40] {
            let qr = crate::encode::encode("A", &crate::encode::Options {
                version: Some(version), mask: Some(0), ..Default::default()
            }).unwrap();
            assert!(decode_modules(&qr.modules[..qr.modules.len() - 1], qr.size).is_none());
            let decoded = decode_modules(&qr.modules, qr.size).unwrap();
            assert_eq!(decoded.payload.bytes, b"A");
            assert_eq!(decoded.payload.version, version);
        }
    }

    #[test]
    fn syndrome_table_matches_field_multiplication() {
        for j in 0..SYNDROME_MUL.len() {
            for value in 0..=u8::MAX {
                assert_eq!(SYNDROME_MUL[j][value as usize], gf_mul(value, EXP[j]));
            }
        }
    }

    #[test]
    fn syndrome_folds_match_the_reference_for_qr_and_larger_blocks() {
        let mut seed = 0x6841_ba53u32;
        for len in [0, 1, 2, 7, 31, 255] {
            let block: Vec<u8> = (0..len).map(|_| {
                seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
                (seed >> 24) as u8
            }).collect();
            for j in 0..EXP.len() {
                let expected = block.iter().fold(0, |s, &b| gf_mul(s, EXP[j]) ^ b);
                let actual = syndrome(&block, j);
                assert_eq!(actual, expected, "length {len}, syndrome {j}");
            }
        }
    }

    /// Builds data codewords from (value, bit count) pairs, zero padded to a whole byte.
    fn words(fields: &[(u32, usize)]) -> Vec<u8> {
        let mut bits: Vec<u8> = Vec::new();
        for &(value, count) in fields {
            for i in (0..count).rev() {
                bits.push(((value >> i) & 1) as u8);
            }
        }
        while bits.len() % 8 != 0 {
            bits.push(0);
        }
        bits.chunks(8).map(|c| c.iter().fold(0u8, |a, &b| (a << 1) | b)).collect()
    }

    fn alnum(c: char) -> u32 {
        ALPHANUMERIC.iter().position(|&b| b as char == c).unwrap() as u32
    }

    #[test]
    fn structured_append_is_reported() {
        // Mode 3, index 2 of 5, parity 0xA5, then the byte segment "A".
        let data = words(&[(3, 4), (0x24, 8), (0xa5, 8), (4, 4), (1, 8), (b'A' as u32, 8), (0, 4)]);
        let parsed = parse(&data, 1).unwrap();
        assert_eq!(parsed.structured_append, Some(StructuredAppend { index: 2, total: 5, parity: 0xa5 }));
        assert_eq!(parsed.text, "A");
        assert_eq!(parsed.bytes, b"A");
    }

    #[test]
    fn fnc1_first_position_rewrites_percent() {
        // FNC1 first position, then alphanumeric "A%B%%C": A, a group separator, B, a percent sign, C.
        let data = words(&[(5, 4), (2, 4), (6, 9), (alnum('A') * 45 + alnum('%'), 11), (alnum('B') * 45 + alnum('%'), 11), (alnum('%') * 45 + alnum('C'), 11), (0, 4)]);
        let parsed = parse(&data, 1).unwrap();
        assert_eq!(parsed.fnc1, Some(Fnc1::First));
        assert_eq!(parsed.bytes, b"A\x1dB%C");
        assert_eq!(parsed.text, "A\u{1d}B%C");
    }

    #[test]
    fn fnc1_second_position_carries_its_indicator() {
        let data = words(&[(9, 4), (165, 8), (4, 4), (1, 8), (b'x' as u32, 8), (0, 4)]);
        let parsed = parse(&data, 1).unwrap();
        assert_eq!(parsed.fnc1, Some(Fnc1::Second("A".to_string())));
        let bad = words(&[(9, 4), (150, 8), (0, 4)]);
        assert!(parse(&bad, 1).is_none());
    }

    #[test]
    fn utf8_by_hand_replaces_each_ill_formed_byte() {
        assert_eq!(from_utf8(&[0x41, 0xe2, 0x82, 0x41]), "A\u{fffd}\u{fffd}A");
        assert_eq!(from_utf8("\u{20ac}".as_bytes()), "\u{20ac}");
        assert!(!is_utf8(&[0xc0, 0x80]));
    }
}

#[cfg(test)]
mod agreed_version_tests {
    use super::{agreed_version, read_version, version_bits_of};

    fn read_copies(size: usize, a: u32, b: u32) -> impl Fn(usize, usize) -> bool {
        move |x, y| {
            if x < 6 && (size - 11..size - 8).contains(&y) {
                (a >> (x * 3 + y - (size - 11))) & 1 != 0
            } else if y < 6 && (size - 11..size - 8).contains(&x) {
                (b >> (y * 3 + x - (size - 11))) & 1 != 0
            } else { false }
        }
    }

    #[test]
    fn copies_must_independently_decode_to_the_same_version() {
        let forty = version_bits_of(40);
        let thirty_nine = version_bits_of(39);
        let matching = read_copies(165, forty ^ 0b111, forty ^ 0b111000);
        assert_eq!(agreed_version(&matching, 165), Some(40));
        assert_eq!(read_version(&matching, 165), Some(40));
        let disagree = read_copies(165, forty, thirty_nine);
        assert_eq!(agreed_version(&disagree, 165), None);
        assert_eq!(read_version(&disagree, 165), Some(40));
        let unreadable = read_copies(165, forty, forty ^ 0b1111);
        assert_eq!(agreed_version(&unreadable, 165), None);
        assert_eq!(read_version(&unreadable, 165), Some(40));
        assert_eq!(agreed_version(&matching, 41), None);
    }
}

#[cfg(test)]
mod curvature_header_tests {
    use super::{curvature_header, read_version, version_bits_of, Ecc, FORMATS, FORMAT_COORDS};

    fn header(va: u32, vb: u32, fa: u32, fb: u32) -> Vec<u8> {
        let size = 65usize;
        let mut grid = vec![0u8; size * size];
        for k in 0..18 {
            let (i, j) = (k / 3, size - 11 + k % 3);
            grid[j * size + i] = ((va >> k) & 1) as u8;
            grid[i * size + j] = ((vb >> k) & 1) as u8;
        }
        for (i, &(x, y)) in FORMAT_COORDS.iter().enumerate() {
            grid[y * size + x] = ((fa >> i) & 1) as u8;
            let (x, y) = if i < 8 { (size - 1 - i, 8) } else { (8, size - 7 + i - 8) };
            grid[y * size + x] = ((fb >> i) & 1) as u8;
        }
        grid
    }

    #[test]
    fn conflict_mode_requires_exact_version_and_a_uniquely_stronger_copy() {
        let v12 = version_bits_of(12);
        let v13 = version_bits_of(13);
        let m3 = FORMATS.iter().find(|f| f.1 == Ecc::M && f.2 == 3).unwrap().0;
        let q7 = FORMATS.iter().find(|f| f.1 == Ecc::Q && f.2 == 7).unwrap().0;
        let check = |va, vb, fa, fb, allow| {
            let grid = header(va, vb, fa, fb);
            super::curvature_header_with_conflict(&|x, y| grid[y * 65 + x] == 1, 65, allow)
        };
        assert_eq!(check(v12, v12, m3, q7 ^ 7, true), Some((Ecc::M, 3, 0, true)));
        assert_eq!(check(v12, v12, m3 ^ 1, q7 ^ 7, true), Some((Ecc::M, 3, 1, true)));
        assert_eq!(check(v12, v12, m3 ^ 3, q7 ^ 7, true), Some((Ecc::M, 3, 2, true)));
        assert_eq!(check(v12, v12, m3 ^ 7, q7 ^ 7, true), None);
        // Reverse the copies: the same stronger word must win in either position.
        assert_eq!(check(v12, v12, q7 ^ 7, m3, true), Some((Ecc::M, 3, 0, true)));
        assert_eq!(check(v12, v12, q7 ^ 7, m3 ^ 1, true), Some((Ecc::M, 3, 1, true)));
        assert_eq!(check(v12, v12, q7 ^ 7, m3 ^ 3, true), Some((Ecc::M, 3, 2, true)));
        assert_eq!(check(v12, v12, q7 ^ 7, m3 ^ 7, true), None);
        assert_eq!(check(v12, v12, m3 ^ 7, m3 ^ 1, true), Some((Ecc::M, 3, 1, false)));
        assert_eq!(check(v12, v12, q7 ^ 7, m3 ^ 1, false), None);
        assert_eq!(check(v12, v12, m3 ^ 1, m3 ^ 7, true), Some((Ecc::M, 3, 1, false)));
        assert_eq!(check(v12, v12, m3 ^ 1, m3 ^ 7, false), Some((Ecc::M, 3, 1, false)));
        assert_eq!(super::curvature_header_with_conflict(&|_, _| false, 41, true), None);
        assert_eq!(check(v12 ^ 1, v12 ^ 2, m3, q7 ^ 7, true), None);
        assert_eq!(check(v12, v13 ^ 1, m3, q7 ^ 7, true), None);
        assert_eq!(check(v12, v12, m3, q7 ^ 7, false), None);
    }

    #[test]
    fn version_peer_requires_exact_anchor_and_two_agreeing_formats() {
        let v12 = version_bits_of(12);
        let v13 = version_bits_of(13);
        let m3 = FORMATS.iter().find(|f| f.1 == Ecc::M && f.2 == 3).unwrap().0;
        let q7 = FORMATS.iter().find(|f| f.1 == Ecc::Q && f.2 == 7).unwrap().0;
        let check = |va, vb, fa, fb| {
            let grid = header(va, vb, fa, fb);
            super::version_peer_header(&|x, y| grid[y * 65 + x] == 1, 65)
        };
        assert_eq!(check(v12, v13 ^ 7, m3 ^ 1, m3 ^ 7), Some((Ecc::M, 3, 1)));
        assert_eq!(check(v13 ^ 7, v12, m3 ^ 7, m3 ^ 1), Some((Ecc::M, 3, 1)));
        assert_eq!(check(v12, v13, m3, m3), None);
        assert_eq!(check(v12, v13 ^ 1, m3, m3), None);
        assert_eq!(check(v12, v13 ^ 3, m3, m3), None);
        assert_eq!(check(v12, v13 ^ 15, m3, m3), None);
        assert_eq!(check(v12 ^ 1, v13 ^ 7, m3, m3), None);
        assert_eq!(check(v12, v12 ^ 7, m3, m3), None);
        assert_eq!(check(v12, v13 ^ 7, m3, q7), None);
        assert_eq!(check(v12, v13 ^ 7, m3, 0), None);
        assert_eq!(super::version_peer_header(&|_, _| false, 41), None);
        assert_eq!(super::version_peer_header(&|_, _| panic!("invalid size must not sample"), 46), None);
        assert_eq!(super::version_peer_header(&|_, _| panic!("invalid size must not sample"), 178), None);
    }

    #[test]
    fn exact_version_and_nonconflicting_independent_headers_are_required() {
        let v12 = version_bits_of(12);
        let v13 = version_bits_of(13);
        let m3 = FORMATS.iter().find(|f| f.1 == Ecc::M && f.2 == 3).unwrap().0;
        let q7 = FORMATS.iter().find(|f| f.1 == Ecc::Q && f.2 == 7).unwrap().0;
        let check = |va, vb, fa, fb| {
            let grid = header(va, vb, fa, fb);
            curvature_header(&|x, y| grid[y * 65 + x] == 1, 65)
        };
        assert_eq!(check(v12, 0, 0, m3 ^ 1), Some((Ecc::M, 3, 1)));
        let correctable = header(v12 ^ 1, v12 ^ 2, m3, m3);
        assert_eq!(read_version(&|x, y| correctable[y * 65 + x] == 1, 65), Some(12));
        assert_eq!(check(v12 ^ 1, v12 ^ 2, m3, m3), None);
        assert_eq!(check(v12, v13 ^ 1, m3, m3), None);
        assert_eq!(check(v12, v12, m3, q7 ^ 1), None);
        assert_eq!(check(v12, v12, 0, 0), None);
        assert_eq!(check(v13, 0, m3, m3), None);
        assert_eq!(curvature_header(&|_, _| false, 41), None);
    }
}