qrcode-barcode-scanner 0.12.2

QR code decoding and scannability scoring for artistic, AI-generated, and photo-captured QR codes
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
//! GS1 parsing + validation — element strings (FNC1 QR, GS1 `GenSpecs` §3/§7)
//! and Digital Link URIs (GS1 DL URI Syntax 1.6, Sunrise-2027 retail form).
//!
//! Scope honesty: this is a SYNTAX validator over the `GenSpecs` subset below
//! (the retail/product set), not a full `GenSpecs` engine. Unknown AIs are
//! flagged as issues and leave the data non-`conformant` — every issue
//! string names the violated criterion.

/// One parsed `(AI, value)` element string.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Gs1Element {
    /// Application Identifier digits as written (`"01"`, `"3103"`, …).
    pub ai: String,
    /// Raw value (not normalized).
    pub value: String,
}

/// Parse + validation outcome shared by both GS1 carriers.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct Gs1Data {
    pub elements: Vec<Gs1Element>,
    pub gtin: Option<String>,
    pub issues: Vec<String>,
}

/// ASCII Group Separator — the transmitted FNC1 inside data (ISO 18004 §7.4.9).
const GS: char = '\u{1d}';

/// `GenSpecs` figure 7.8.4-2: AIs whose first two digits predefine the TOTAL
/// element length (AI + value) — no GS separator needed after them.
const PREDEFINED_TOTAL_LEN: [(&str, usize); 20] = [
    ("00", 20),
    ("01", 16),
    ("02", 16),
    ("11", 8),
    ("12", 8),
    ("13", 8),
    ("14", 8),
    ("15", 8),
    ("16", 8),
    ("17", 8),
    ("18", 8),
    ("19", 8),
    ("20", 4),
    ("31", 10),
    ("32", 10),
    ("33", 10),
    ("34", 10),
    ("35", 10),
    ("36", 10),
    ("41", 16),
];

/// Value shape for a known AI.
#[derive(Clone, Copy)]
enum Shape {
    /// Exactly `n` digits.
    Digits(usize),
    /// Exactly `n` digits, last one a GS1 mod-10 check digit.
    DigitsCheck(usize),
    /// `YYMMDD` (DD=00 allowed: "end of month", `GenSpecs` 3.4.2).
    Date,
    /// 1..=n chars from CSET 82.
    Cset82(usize),
    /// 1..=n digits.
    VarDigits(usize),
}

/// AI → value shape for the validated subset (`GenSpecs` release 25 / ref.gs1.org/ai).
/// 4-digit metric AIs (31nn-36nn) are matched on their 3-digit stem.
fn shape_of(ai: &str) -> Option<Shape> {
    Some(match ai {
        "00" => Shape::DigitsCheck(18),
        "01" | "02" => Shape::DigitsCheck(14),
        "11" | "12" | "13" | "15" | "16" | "17" => Shape::Date,
        "20" => Shape::Digits(2),
        "10" | "21" | "22" => Shape::Cset82(20),
        "30" | "37" => Shape::VarDigits(8),
        "235" => Shape::Cset82(28),
        "8005" => Shape::Digits(6),
        "8011" => Shape::VarDigits(12),
        "8019" => Shape::VarDigits(10),
        "8020" => Shape::Cset82(25),
        "8200" => Shape::Cset82(70),
        "90" | "240" | "241" | "250" | "251" => Shape::Cset82(30),
        "91" | "92" | "93" | "94" | "95" | "96" | "97" | "98" | "99" => Shape::Cset82(90),
        _ if ai.len() == 3 && ("410"..="418").contains(&ai) => Shape::DigitsCheck(13),
        _ if ai.len() == 4
            && matches!(ai.get(..2), Some("31" | "32" | "33" | "34" | "35" | "36"))
            && ai.as_bytes()[3].is_ascii_digit() =>
        {
            Shape::Digits(6)
        }
        _ => return None,
    })
}

/// GS1 mod-10 check digit (`GenSpecs` §7.2.7): weights 3,1,3,… from the digit
/// left of the check position.
pub(crate) fn check_digit_ok(digits: &str) -> bool {
    let bytes = digits.as_bytes();
    if bytes.is_empty() || !bytes.iter().all(u8::is_ascii_digit) {
        return false;
    }
    let mut sum = 0u32;
    // all positions except the last, weighted 3/1 alternating from the right
    for (i, b) in bytes[..bytes.len() - 1].iter().rev().enumerate() {
        let d = u32::from(b - b'0');
        sum += if i % 2 == 0 { d * 3 } else { d };
    }
    let expect = (10 - sum % 10) % 10;
    u32::from(bytes[bytes.len() - 1] - b'0') == expect
}

/// Expand an 8-digit UPC-E symbol (number-system digit · 6 compressed data
/// digits · check digit) to its equivalent 12-digit UPC-A, per the UPC-E
/// zero-suppression table (GS1 General Specifications §5.2.2.4 / the
/// barcodeisland UPC-E reference — the inverse of UPC-A→UPC-E compression).
///
/// The LAST compressed data digit selects the split:
/// `0/1/2`→`M1 M2 D 0000 M3 M4 M5` · `3`→`M1 M2 M3 00000 M4 M5` ·
/// `4`→`M1 M2 M3 M4 00000 M5` · `5-9`→`M1..M5 0000 D`. The UPC-E check digit
/// is defined by this expansion, NOT by the compressed string, so callers
/// must run the mod-10 check + derive GTIN-14 from the returned UPC-A.
/// `None` for anything that is not exactly 8 ASCII digits.
pub(crate) fn expand_upce_to_upca(upce: &str) -> Option<String> {
    let b = upce.as_bytes();
    if b.len() != 8 || !b.iter().all(u8::is_ascii_digit) {
        return None;
    }
    let number_system = b[0];
    let data = &b[1..7]; // the 6 compressed manufacturer/product digits
    let check = b[7];
    let mut expanded = Vec::with_capacity(12);
    expanded.push(number_system);
    match data[5] {
        b'0' | b'1' | b'2' => {
            expanded.extend_from_slice(&data[0..2]);
            expanded.push(data[5]);
            expanded.extend_from_slice(b"0000");
            expanded.extend_from_slice(&data[2..5]);
        }
        b'3' => {
            expanded.extend_from_slice(&data[0..3]);
            expanded.extend_from_slice(b"00000");
            expanded.extend_from_slice(&data[3..5]);
        }
        b'4' => {
            expanded.extend_from_slice(&data[0..4]);
            expanded.extend_from_slice(b"00000");
            expanded.push(data[4]);
        }
        _ => {
            expanded.extend_from_slice(&data[0..5]);
            expanded.extend_from_slice(b"0000");
            expanded.push(data[5]);
        }
    }
    expanded.push(check);
    // every pushed byte was an ASCII digit → always valid UTF-8
    String::from_utf8(expanded).ok()
}

/// CSET 82 (`GenSpecs` figure 7.11-1) — GS1's own value-charset class.
fn is_cset82(c: char) -> bool {
    matches!(c,
        '0'..='9' | 'A'..='Z' | 'a'..='z'
        | '!' | '"' | '%' | '&' | '\'' | '(' | ')' | '*' | '+' | ','
        | '-' | '.' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '_')
}

fn valid_date(v: &str) -> bool {
    if v.len() != 6 || !v.bytes().all(|b| b.is_ascii_digit()) {
        return false;
    }
    let mm: u8 = v[2..4].parse().unwrap_or(99);
    let dd: u8 = v[4..6].parse().unwrap_or(99);
    (1..=12).contains(&mm) && dd <= 31
}

fn validate(ai: &str, value: &str, shape: Shape, issues: &mut Vec<String>) {
    let ok = match shape {
        Shape::Digits(n) => value.len() == n && value.bytes().all(|b| b.is_ascii_digit()),
        Shape::DigitsCheck(n) => {
            if value.len() == n && value.bytes().all(|b| b.is_ascii_digit()) {
                if check_digit_ok(value) {
                    true
                } else {
                    issues.push(format!(
                        "AI {ai}: check digit invalid for '{value}' (GenSpecs 7.2.7)"
                    ));
                    return;
                }
            } else {
                false
            }
        }
        Shape::Date => {
            if valid_date(value) {
                true
            } else {
                issues.push(format!(
                    "AI {ai}: invalid YYMMDD date '{value}' (GenSpecs 3.4)"
                ));
                return;
            }
        }
        Shape::Cset82(max) => (1..=max).contains(&value.len()) && value.chars().all(is_cset82),
        Shape::VarDigits(max) => {
            (1..=max).contains(&value.len()) && value.bytes().all(|b| b.is_ascii_digit())
        }
    };
    if !ok {
        issues.push(format!(
            "AI {ai}: value '{value}' violates the AI format (ref.gs1.org/ai/{ai})"
        ));
    }
}

/// Split at most `max_bytes` off the head WITHOUT crossing a char boundary
/// (FNC1 payloads are attacker-controlled UTF-8 — byte-index slicing
/// panicked on multi-byte content pre-fix; this is the one safe primitive
/// every byte-budget split in this module goes through).
fn split_head(s: &str, max_bytes: usize) -> (&str, &str) {
    let mut cut = max_bytes.min(s.len());
    while cut > 0 && !s.is_char_boundary(cut) {
        cut -= 1;
    }
    s.split_at(cut)
}

/// Longest known AI at the head of `s` (4 → 3 → 2 digits).
fn known_ai_at(s: &str) -> Option<&str> {
    for len in [4usize, 3, 2] {
        if let Some(head) = s.get(..len)
            && head.bytes().all(|b| b.is_ascii_digit())
            && shape_of(head).is_some()
        {
            return Some(head);
        }
    }
    None
}

/// Parse a GS1 element string (decoded FNC1-first QR data: AIs concatenated,
/// variable-length values terminated by GS). Never fails — problems land in
/// `issues`, each naming its criterion.
pub(crate) fn parse_element_string(data: &str) -> Gs1Data {
    let mut out = Gs1Data::default();
    let mut rest = data;
    while !rest.is_empty() {
        // a stray separator before the next AI is legal noise after a
        // predefined-length element; skip it
        if let Some(stripped) = rest.strip_prefix(GS) {
            rest = stripped;
            continue;
        }
        let Some(ai) = known_ai_at(rest) else {
            let fragment: String = rest.chars().take(8).collect();
            out.issues.push(format!(
                "unknown AI at '{fragment}…': not in the validated GenSpecs subset"
            ));
            // resync at the next GS — the rest of THIS element can't be split
            match rest.find(GS) {
                Some(i) => rest = &rest[i + 1..],
                None => break,
            }
            continue;
        };
        let ai = ai.to_owned();
        rest = &rest[ai.len()..];

        let predefined = PREDEFINED_TOTAL_LEN
            .iter()
            .find(|(p, _)| *p == &ai[..2])
            .map(|(_, total)| *total);
        let value = match predefined {
            Some(total) => {
                // boundary-safe split: a multi-byte char inside the value
                // zone shortens the cut — the value then fails shape
                // validation (CSET 82 / digits are ASCII-only), never panics
                // saturating: the predefined-total tables and shape_of are
                // maintained independently — a future AI longer than its
                // family total must not underflow
                let (v, tail) = split_head(rest, total.saturating_sub(ai.len()));
                rest = tail;
                if v.len() + ai.len() < total {
                    out.issues.push(format!(
                        "AI {ai}: truncated — predefined length is {total} incl. AI (GenSpecs 7.8.4)"
                    ));
                }
                v.to_owned()
            }
            None => match rest.find(GS) {
                Some(i) => {
                    let v = &rest[..i];
                    rest = &rest[i + 1..];
                    v.to_owned()
                }
                None => std::mem::take(&mut rest).to_owned(),
            },
        };

        if let Some(shape) = shape_of(&ai) {
            validate(&ai, &value, shape, &mut out.issues);
        }
        if ai == "01" && out.gtin.is_none() {
            out.gtin = Some(value.clone());
        }
        out.elements.push(Gs1Element { ai, value });
    }
    if out.elements.is_empty() {
        out.issues
            .push("no parseable GS1 element string (ISO 18004 §7.4.9 FNC1 data)".to_owned());
    }
    out
}

/// Primary keys we recognize in a Digital Link path: AI → value length.
const DL_PRIMARY_KEYS: [(&str, usize); 3] = [("01", 14), ("00", 18), ("414", 13)];
/// GTIN key qualifiers in their ONLY legal order (DL URI Syntax §4.4 ABNF).
const DL_QUALIFIER_ORDER: [&str; 3] = ["22", "10", "21"];

/// Recognize + validate a GS1 Digital Link URI (any domain — `id.gs1.org` is
/// just the canonical resolver). `None` = not Digital-Link-shaped at all;
/// `Some` with issues = DL-shaped but non-conformant.
pub(crate) fn parse_digital_link(url: &str) -> Option<Gs1Data> {
    let after_scheme = url
        .get(..8)
        .filter(|h| h.eq_ignore_ascii_case("https://"))
        .map(|_| &url[8..])
        .or_else(|| {
            url.get(..7)
                .filter(|h| h.eq_ignore_ascii_case("http://"))
                .map(|_| &url[7..])
        })?;
    let (_host, path_query) = after_scheme.split_once('/')?;
    let (path, query) = match path_query.split_once('?') {
        Some((p, q)) => (p, Some(q)),
        None => (path_query, None),
    };
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    // locate a primary key whose NEXT segment has the exact key length —
    // the shape guard that keeps /2024/01/15/ blog paths out
    let (key_idx, key_ai, key_len) = segments.iter().enumerate().find_map(|(i, seg)| {
        DL_PRIMARY_KEYS.iter().find_map(|(ai, len)| {
            (seg == ai
                && segments
                    .get(i + 1)
                    .is_some_and(|v| v.len() == *len && v.bytes().all(|b| b.is_ascii_digit())))
            .then_some((i, *ai, *len))
        })
    })?;

    let mut out = Gs1Data::default();
    let key_value = segments[key_idx + 1];
    debug_assert_eq!(key_value.len(), key_len);
    if !check_digit_ok(key_value) {
        out.issues.push(format!(
            "AI {key_ai}: check digit invalid for '{key_value}' (GenSpecs 7.2.7)"
        ));
    }
    if key_ai == "01" {
        out.gtin = Some(key_value.to_owned());
    }
    out.elements.push(Gs1Element {
        ai: key_ai.to_owned(),
        value: key_value.to_owned(),
    });

    // qualifiers after the key: /22/../10/../21/.. — order is normative
    let mut cursor = key_idx + 2;
    let mut min_rank = 0usize;
    while cursor < segments.len() {
        let ai_seg = segments[cursor];
        let Some(&value_seg) = segments.get(cursor + 1) else {
            out.issues.push(format!(
                "qualifier AI {ai_seg} has no value segment (DL URI Syntax 4.4)"
            ));
            break;
        };
        let Some(rank) = DL_QUALIFIER_ORDER.iter().position(|q| *q == ai_seg) else {
            out.issues.push(format!(
                "unexpected path segment '{ai_seg}' after the primary key (DL URI Syntax 4.4)"
            ));
            break;
        };
        if rank < min_rank {
            out.issues.push(format!(
                "qualifier AI {ai_seg} out of order — path order is 01→22→10→21 (DL URI Syntax 4.4)"
            ));
        }
        min_rank = min_rank.max(rank);
        if let Some(shape) = shape_of(ai_seg) {
            validate(ai_seg, value_seg, shape, &mut out.issues);
        }
        out.elements.push(Gs1Element {
            ai: ai_seg.to_owned(),
            value: value_seg.to_owned(),
        });
        cursor += 2;
    }

    // all-numeric query keys are AI data attributes (DL URI Syntax 4.5)
    if let Some(query) = query {
        for pair in query.split('&') {
            let Some((k, v)) = pair.split_once('=') else {
                continue;
            };
            if k.is_empty() || !k.bytes().all(|b| b.is_ascii_digit()) {
                continue;
            }
            if let Some(shape) = shape_of(k) {
                validate(k, v, shape, &mut out.issues);
            } else {
                out.issues.push(format!(
                    "unknown AI {k} in query (not in the validated subset)"
                ));
            }
            out.elements.push(Gs1Element {
                ai: k.to_owned(),
                value: v.to_owned(),
            });
        }
    }
    Some(out)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;

    const GS_S: &str = "\u{1d}";

    #[test]
    fn element_string_fixed_then_variable_then_fixed_no_separator_needed() {
        // 01 (predefined 16) + 10 batch (GS) + 17 expiry (predefined 8)
        let data = format!("010950600013435210ABC123{GS_S}17261231");
        let parsed = parse_element_string(&data);
        assert_eq!(parsed.issues, Vec::<String>::new());
        assert_eq!(parsed.gtin.as_deref(), Some("09506000134352"));
        assert_eq!(
            parsed.elements,
            vec![
                Gs1Element {
                    ai: "01".into(),
                    value: "09506000134352".into()
                },
                Gs1Element {
                    ai: "10".into(),
                    value: "ABC123".into()
                },
                Gs1Element {
                    ai: "17".into(),
                    value: "261231".into()
                },
            ]
        );
    }

    #[test]
    fn element_string_last_variable_needs_no_terminator() {
        let parsed = parse_element_string("010950600013435221SER42");
        assert!(parsed.issues.is_empty(), "{:?}", parsed.issues);
        assert_eq!(parsed.elements[1].ai, "21");
        assert_eq!(parsed.elements[1].value, "SER42");
    }

    #[test]
    fn element_string_metric_ai_and_sscc() {
        // 3103 = net weight kg, 3 decimals (predefined total 10) · 00 SSCC 18+check
        let parsed = parse_element_string("310300019500106141411234567897");
        assert!(parsed.issues.is_empty(), "{:?}", parsed.issues);
        assert_eq!(
            parsed.elements[0],
            Gs1Element {
                ai: "3103".into(),
                value: "000195".into()
            }
        );
        assert_eq!(parsed.elements[1].ai, "00");
    }

    #[test]
    fn element_string_bad_check_digit_names_the_criterion() {
        let parsed = parse_element_string("0109506000134353");
        assert_eq!(parsed.issues.len(), 1);
        assert!(
            parsed.issues[0].contains("GenSpecs 7.2.7"),
            "{:?}",
            parsed.issues
        );
        // gtin still extracted — consumers decide what to do with a bad one
        assert_eq!(parsed.gtin.as_deref(), Some("09506000134353"));
    }

    #[test]
    fn element_string_bad_date_and_cset_violation() {
        let parsed = parse_element_string(&format!("17269931{GS_S}10sp ace"));
        // 17269931 → date 269931 invalid (month 99)... wait: predefined 8 total
        assert!(
            parsed.issues.iter().any(|i| i.contains("GenSpecs 3.4")),
            "{:?}",
            parsed.issues
        );
        // space is outside CSET 82
        assert!(
            parsed
                .issues
                .iter()
                .any(|i| i.contains("ref.gs1.org/ai/10")),
            "{:?}",
            parsed.issues
        );
    }

    #[test]
    fn element_string_unknown_ai_flagged_and_resyncs_at_gs() {
        let parsed = parse_element_string(&format!("4399XYZ{GS_S}10OK"));
        assert!(
            parsed.issues.iter().any(|i| i.contains("unknown AI")),
            "{:?}",
            parsed.issues
        );
        assert!(
            parsed
                .elements
                .iter()
                .any(|e| e.ai == "10" && e.value == "OK"),
            "resync after GS must recover the next element: {:?}",
            parsed.elements
        );
    }

    #[test]
    fn element_string_multibyte_utf8_never_panics() {
        // attacker-controlled FNC1 payloads can carry arbitrary UTF-8 —
        // byte-index slicing must never cross a char boundary (live DoS
        // class: "01é" panicked at known_ai_at's s[..3] pre-fix)
        for hostile in [
            "01é",
            "é0109506000134352",
            "0109506000134352é10ABC\u{1d}é",
            "010950600013435é",
            "10\u{e9}\u{1d}21x",
            "🦋",
            "9é",
        ] {
            let parsed = parse_element_string(hostile);
            // non-conformant is fine; panicking is the bug
            assert!(
                !parsed.issues.is_empty() || !parsed.elements.is_empty(),
                "{hostile}"
            );
        }
    }

    proptest::proptest! {
        #[test]
        fn element_string_parser_never_panics(s in ".*") {
            let _ = parse_element_string(&s);
        }

        #[test]
        fn digital_link_parser_never_panics(s in ".*") {
            let _ = parse_digital_link(&s);
        }
    }

    #[test]
    fn check_digit_known_goods() {
        for good in ["09506000134352", "00614141123452", "106141411234567897"] {
            assert!(check_digit_ok(good), "{good}");
        }
        assert!(!check_digit_ok("09506000134353"));
        assert!(!check_digit_ok(""));
        assert!(!check_digit_ok("12a4"));
    }

    #[test]
    fn upce_expands_to_upca_per_the_gs1_zero_suppression_table() {
        // 8-digit UPC-E (numsys · 6 data · check) → 12-digit UPC-A. Each
        // expansion is computed BY HAND from the split table; the last data
        // digit picks the case. The first pair is the Wikipedia UPC worked
        // example (external anchor); the rest cover the 3, 4 and 5-9 splits.
        for (upce, upca) in [
            ("04252614", "042100005264"), // last data digit 1 → {0,1,2} split
            ("03456733", "034500000673"), // last data digit 3 → 3-split
            ("03456741", "034560000071"), // last data digit 4 → 4-split
            ("02345680", "023456000080"), // last data digit 8 → {5-9} split
        ] {
            assert_eq!(expand_upce_to_upca(upce).as_deref(), Some(upca), "{upce}");
            // the expansion is internally consistent — its own mod-10 holds…
            assert!(check_digit_ok(upca), "{upca} check digit");
            // …and the UPC-E's 8th digit IS that expansion's check digit
            assert_eq!(upce.as_bytes()[7], upca.as_bytes()[11], "{upce}");
        }
        // ill-formed input yields None rather than a fabricated GTIN
        assert_eq!(expand_upce_to_upca("0123"), None);
        assert_eq!(expand_upce_to_upca("0123456a"), None);
        assert_eq!(expand_upce_to_upca("012345678"), None); // 9 digits
    }

    #[test]
    fn digital_link_canonical_example_is_conformant() {
        // the GS1 DL URI Syntax worked example
        let dl = parse_digital_link(
            "https://id.gs1.org/01/09506000134352/10/ABC123/21/456789?17=261231",
        )
        .expect("DL-shaped");
        assert_eq!(dl.issues, Vec::<String>::new());
        assert_eq!(dl.gtin.as_deref(), Some("09506000134352"));
        let ais: Vec<&str> = dl.elements.iter().map(|e| e.ai.as_str()).collect();
        assert_eq!(ais, vec!["01", "10", "21", "17"]);
    }

    #[test]
    fn digital_link_works_on_any_domain() {
        let dl = parse_digital_link("https://qrc-ai.com/01/09506000134352").expect("DL");
        assert_eq!(dl.issues.len(), 0);
        assert_eq!(dl.gtin.as_deref(), Some("09506000134352"));
    }

    #[test]
    fn digital_link_qualifier_order_violation_flagged() {
        let dl = parse_digital_link("https://id.gs1.org/01/09506000134352/21/456789/10/ABC123")
            .expect("DL-shaped");
        assert!(
            dl.issues.iter().any(|i| i.contains("01→22→10→21")),
            "{:?}",
            dl.issues
        );
    }

    #[test]
    fn digital_link_rejects_non_14_digit_gtin_and_short_names() {
        // 13-digit GTIN path → not even DL-shaped under v1.4 (14-digit law);
        // the shape guard refuses, the URL stays a plain URL
        assert!(parse_digital_link("https://id.gs1.org/01/9506000134352").is_none());
        // short names were REMOVED in DL 1.3 — never DL-shaped
        assert!(parse_digital_link("https://id.gs1.org/gtin/09506000134352").is_none());
    }

    #[test]
    fn digital_link_blog_path_false_positive_guard() {
        assert!(parse_digital_link("https://example.com/2024/01/15/post").is_none());
        assert!(parse_digital_link("https://example.com/").is_none());
        assert!(parse_digital_link("not a url").is_none());
    }

    #[test]
    fn digital_link_bad_query_attribute_flagged() {
        let dl = parse_digital_link("https://id.gs1.org/01/09506000134352?17=269931")
            .expect("DL-shaped");
        assert!(
            dl.issues.iter().any(|i| i.contains("GenSpecs 3.4")),
            "{:?}",
            dl.issues
        );
    }

    // ── AI dictionary + boundary predicates (mutation pins) ──────────────

    /// Collapse a `Shape` to a comparable `(kind, param)` literal so the AI
    /// table can be asserted against hand-derived GS1 values WITHOUT deriving
    /// `PartialEq` on the production enum and WITHOUT letting `shape_of` grade
    /// its own output.
    fn shape_tag(s: Shape) -> (&'static str, usize) {
        match s {
            Shape::Digits(n) => ("Digits", n),
            Shape::DigitsCheck(n) => ("DigitsCheck", n),
            Shape::Date => ("Date", 0),
            Shape::Cset82(n) => ("Cset82", n),
            Shape::VarDigits(n) => ("VarDigits", n),
        }
    }

    #[test]
    fn shape_of_maps_every_ai_to_its_genspecs_shape() {
        // (AI, expected shape) — every value a LITERAL read from the GS1
        // General Specifications (release 25 / ref.gs1.org/ai), never computed
        // by shape_of. Deleting ANY arm turns its AI into `None`, tripping the
        // pair below. Subset scope pinned by spec/05-payloads.md §Scope honesty
        // (00·01·02·10-22·30·37·240/241/250/251·310n-369n·41x·8005·8011·8019·
        // 8020·8200·90-99).
        let table: &[(&str, (&str, usize))] = &[
            ("00", ("DigitsCheck", 18)), // SSCC, N18 incl. check
            ("01", ("DigitsCheck", 14)), // GTIN, N14 incl. check
            ("02", ("DigitsCheck", 14)), // GTIN of contained items
            ("11", ("Date", 0)),         // production date YYMMDD
            ("12", ("Date", 0)),         // due date
            ("13", ("Date", 0)),         // packaging date
            ("15", ("Date", 0)),         // best-before date
            ("16", ("Date", 0)),         // sell-by date
            ("17", ("Date", 0)),         // expiry date
            ("20", ("Digits", 2)),       // product variant, N2
            ("10", ("Cset82", 20)),      // batch/lot,  X..20
            ("21", ("Cset82", 20)),      // serial,     X..20
            ("22", ("Cset82", 20)),      // CPV,        X..20
            ("30", ("VarDigits", 8)),    // variable count, N..8
            ("37", ("VarDigits", 8)),    // count of items, N..8
            ("235", ("Cset82", 28)),     // TPX,        X..28
            ("8005", ("Digits", 6)),     // price per UoM, N6
            ("8011", ("VarDigits", 12)), // CPID serial, N..12
            ("8019", ("VarDigits", 10)), // SRIN,        N..10
            ("8020", ("Cset82", 25)),    // payment slip ref, X..25
            ("8200", ("Cset82", 70)),    // product URL, X..70
            ("90", ("Cset82", 30)),      // mutually agreed, X..30
            ("240", ("Cset82", 30)),     // additional product id
            ("241", ("Cset82", 30)),     // customer part number
            ("250", ("Cset82", 30)),     // secondary serial
            ("251", ("Cset82", 30)),     // ref to source entity
            ("91", ("Cset82", 90)),      // company internal 91..99, X..90
            ("92", ("Cset82", 90)),
            ("93", ("Cset82", 90)),
            ("94", ("Cset82", 90)),
            ("95", ("Cset82", 90)),
            ("96", ("Cset82", 90)),
            ("97", ("Cset82", 90)),
            ("98", ("Cset82", 90)),
            ("99", ("Cset82", 90)),
            ("410", ("DigitsCheck", 13)), // ship-to GLN, N13 incl. check
            ("411", ("DigitsCheck", 13)), // bill-to GLN
            ("414", ("DigitsCheck", 13)), // physical location GLN
            ("417", ("DigitsCheck", 13)), // party GLN
            ("418", ("DigitsCheck", 13)), // range upper bound
            ("3103", ("Digits", 6)),      // net weight kg, 3 dp — 31nn stem
            ("3600", ("Digits", 6)),      // volume — 36nn stem, edge byte '0'
        ];
        for &(ai, expected) in table {
            assert_eq!(shape_of(ai).map(shape_tag), Some(expected), "AI {ai}");
        }

        // Negative pins around `_ if ai.len() == 3 && ("410"..="418")…`: the
        // range must not leak to neighbours, and a 4-digit "41xx" must NOT be
        // taken for a 3-digit AI. shape_of("4100") == None is the exact witness
        // that dies when `==` flips to `!=` (len 4 ≠ 3 passes the length half,
        // and "4100" IS lexically inside "410".."418"). The 80xx / 82xx pins
        // prove those arms are exact-match, not prefix.
        for unknown in ["409", "419", "4100", "42", "8000", "8201"] {
            assert!(shape_of(unknown).is_none(), "AI {unknown} must be unknown");
        }
    }

    #[test]
    fn valid_date_enforces_yymmdd() {
        // GenSpecs §3.4: 6 ASCII digits, MM in 1..=12, DD in 00..=31 (DD=00 is
        // the legal "end of month" form).
        assert!(valid_date("261231")); // 2026-12-31
        assert!(valid_date("000101")); // 2000-01-01
        assert!(valid_date("261200")); // DD=00 end-of-month
        assert!(!valid_date("261301")); // month 13
        assert!(!valid_date("260001")); // month 00
        assert!(!valid_date("261232")); // day 32
        assert!(!valid_date("2612")); // too short
        assert!(!valid_date("26123100")); // too long
        // The reject-guard is `len != 6 OR non-digit`. Flipping OR→AND lets a
        // non-digit-but-6-long value (a lettered year) slip through to the
        // numeric parse, which yields a "valid" 12/31 — this witness dies:
        assert!(!valid_date("ab1231"));
    }

    #[test]
    fn validate_flags_each_shape_conjunction() {
        // Every branch tests `length && charset`. Feeding one half true and the
        // other false MUST still flag. Flipping `&&`→`||` (mutants 184/186/211)
        // drops the issue — these witnesses die.
        fn issues(ai: &str, value: &str, shape: Shape) -> Vec<String> {
            let mut v = Vec::new();
            validate(ai, value, shape, &mut v);
            v
        }

        // Digits(2): correct length, non-digit char → 184 && → ||
        let d = issues("20", "1a", Shape::Digits(2));
        assert_eq!(d.len(), 1, "{d:?}");
        assert!(d[0].contains("ref.gs1.org/ai/20"), "{d:?}");

        // DigitsCheck(14): all-digit but WRONG length. `||` would enter the
        // check-digit branch, where "123" happens to carry a valid mod-10 →
        // wrongly accepted; the original rejects it as a format violation. → 186
        let dc = issues("01", "123", Shape::DigitsCheck(14));
        assert_eq!(dc.len(), 1, "{dc:?}");
        assert!(dc[0].contains("violates the AI format"), "{dc:?}");

        // VarDigits(8): in-range length, non-digit char → 211 && → ||
        let vd = issues("30", "12a", Shape::VarDigits(8));
        assert_eq!(vd.len(), 1, "{vd:?}");
        assert!(vd[0].contains("ref.gs1.org/ai/30"), "{vd:?}");

        // Conformant values of each shape raise NO issue (proves the asserts
        // above pin the violation, not a validator that flags everything).
        assert_eq!(issues("20", "42", Shape::Digits(2)).len(), 0);
        assert_eq!(
            issues("01", "09506000134352", Shape::DigitsCheck(14)).len(),
            0
        );
        assert_eq!(issues("30", "12345", Shape::VarDigits(8)).len(), 0);
    }

    #[test]
    fn split_head_walks_down_to_the_char_boundary() {
        // ASCII: exact cut, and an over-long budget returns the whole head.
        assert_eq!(split_head("abcdef", 3), ("abc", "def"));
        assert_eq!(split_head("ab", 9), ("ab", ""));
        // A budget LANDING inside a multi-byte char walks DOWN to the boundary
        // before it (never up). "é0" = [C3 A9 30]: budget 1 is mid-é, so the
        // head is empty and é stays with the tail. `-=`→`+=` (mutant 228) would
        // walk UP and yield ("é","0") — this witness dies. The down-walk also
        // shows why `cut > 0` vs `cut >= 0` (mutant 227) is behaviourally
        // identical: at cut==0, is_char_boundary(0) is always true, so both
        // conditions stop the loop at the same index (argued equivalent).
        assert_eq!(split_head("é0", 1), ("", "é0"));
        assert_eq!(split_head("🦋x", 2), ("", "🦋x"));
        // A budget exactly on a boundary is kept as-is.
        assert_eq!(split_head("é0", 2), ("é", "0"));
    }

    #[test]
    fn element_string_one_short_of_its_predefined_length_is_truncated() {
        // the AI's length and the value's add up to the predefined total:
        // one character short of it is truncated, for a two-digit AI and a
        // four-digit one alike
        for (data, ai, total) in [("010950600013435", "01", 16), ("310300019", "3103", 10)] {
            let parsed = parse_element_string(data);
            let truncated = format!(
                "AI {ai}: truncated — predefined length is {total} incl. AI (GenSpecs 7.8.4)"
            );
            assert!(
                parsed.issues.contains(&truncated),
                "{data}: {:?}",
                parsed.issues
            );
        }
    }

    #[test]
    fn digital_link_reads_every_qualifier_in_its_place() {
        // all three key qualifiers, CPV first: each takes the segment after
        // its own, 22 at rank 0 is in order, the third one is still read,
        // and a query key that is not all digits is no AI attribute
        let dl = parse_digital_link(
            "https://id.gs1.org/01/09506000134352/22/CPV1/10/LOT1/21/SER1?src=mail&17=261231",
        )
        .expect("DL-shaped");
        assert_eq!(dl.issues, Vec::<String>::new());
        let pairs: Vec<(&str, &str)> = dl
            .elements
            .iter()
            .map(|e| (e.ai.as_str(), e.value.as_str()))
            .collect();
        assert_eq!(
            pairs,
            vec![
                ("01", "09506000134352"),
                ("22", "CPV1"),
                ("10", "LOT1"),
                ("21", "SER1"),
                ("17", "261231"),
            ]
        );
    }
}