zedbar 0.5.1

Pure Rust barcode and QR code scanning library supporting multiple 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
//! Code 128 barcode decoder
//!
//! This module implements decoding for Code 128 barcodes.

use crate::{
    SymbolType,
    color::Color,
    decoder::Modifier,
    decoder::decode_e,
    img_scanner::{BUFFER_MAX, ImageScanner},
};

// Character count
const NUM_CHARS: usize = 108;

// Code 128 character codes
const FNC3: u8 = 0x60;
const FNC2: u8 = 0x61;
const SHIFT: u8 = 0x62;
const CODE_C: u8 = 0x63;
// CODE_B = 0x64 - unused in decoder (part of spec)
const CODE_A: u8 = 0x65;
const FNC1: u8 = 0x66;
const START_A: u8 = 0x67;
// START_B = 0x68 - unused in decoder (part of spec)
const START_C: u8 = 0x69;
const STOP_FWD: u8 = 0x6a;
const STOP_REV: u8 = 0x6b;
// FNC4 = 0x6c - unused in decoder (FIXME: extended ASCII not implemented)

// Assertion macro
macro_rules! zassert {
    ($condition:expr, $retval:expr, $($arg:tt)*) => {
        if !$condition {
            return $retval;
        }
    };
}

// ============================================================================
// Code 128 lookup tables
// ============================================================================

static CHARACTERS: [u8; NUM_CHARS] = [
    0x5c, 0xbf, 0xa1, // [00] 00
    0x2a, 0xc5, 0x0c, 0xa4, // [03] 01
    0x2d, 0xe3, 0x0f, // [07] 02
    0x5f, 0xe4, // [0a] 03
    0x6b, 0xe8, 0x69, 0xa7, 0xe7, // [0c] 10
    0xc1, 0x51, 0x1e, 0x83, 0xd9, 0x00, 0x84, 0x1f, // [11] 11
    0xc7, 0x0d, 0x33, 0x86, 0xb5, 0x0e, 0x15, 0x87, // [19] 12
    0x10, 0xda, 0x11, // [21] 13
    0x36, 0xe5, 0x18, 0x37, // [24] 20
    0xcc, 0x13, 0x39, 0x89, 0x97, 0x14, 0x1b, 0x8a, 0x3a, 0xbd, // [28] 21
    0xa2, 0x5e, 0x01, 0x85, 0xb0, 0x02, 0xa3, // [32] 22
    0xa5, 0x2c, 0x16, 0x88, 0xbc, 0x12, 0xa6, // [39] 23
    0x61, 0xe6, 0x56, 0x62, // [40] 30
    0x19, 0xdb, 0x1a, // [44] 31
    0xa8, 0x32, 0x1c, 0x8b, 0xcd, 0x1d, 0xa9, // [47] 32
    0xc3, 0x20, 0xc4, // [4e] 33
    0x50, 0x5d, 0xc0, // [51] 0014 0025 0034
    0x2b, 0xc6, // [54] 0134 0143
    0x2e, // [56] 0243
    0x53, 0x60, // [57] 0341 0352
    0x31, // [59] 1024
    0x52, 0xc2, // [5a] 1114 1134
    0x34, 0xc8, // [5c] 1242 1243
    0x55, // [5e] 1441
    0x57, 0x3e, 0xce, // [5f] 4100 5200 4300
    0x3b, 0xc9, // [62] 4310 3410
    0x6a, // [64] 3420
    0x54, 0x4f, // [65] 1430 2530
    0x38, // [67] 4201
    0x58, 0xcb, // [68] 4111 4311
    0x2f, 0xca, // [6a] 2421 3421
];

static LO_BASE: [u8; 8] = [0x00, 0x07, 0x0c, 0x19, 0x24, 0x32, 0x40, 0x47];

static LO_OFFSET: [u8; 0x80] = [
    0xff, 0xf0, 0xff, 0x1f, 0xff, 0xf2, 0xff, 0xff, // 00 [00]
    0xff, 0xff, 0xff, 0x3f, 0xf4, 0xf5, 0xff, 0x6f, // 01
    0xff, 0xff, 0xff, 0xff, 0xf0, 0xf1, 0xff, 0x2f, // 02 [07]
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x4f, // 03
    0xff, 0x0f, 0xf1, 0xf2, 0xff, 0x3f, 0xff, 0xf4, // 10 [0c]
    0xf5, 0xf6, 0xf7, 0x89, 0xff, 0xab, 0xff, 0xfc, // 11
    0xff, 0xff, 0x0f, 0x1f, 0x23, 0x45, 0xf6, 0x7f, // 12 [19]
    0xff, 0xff, 0xff, 0xff, 0xf8, 0xff, 0xf9, 0xaf, // 13
    0xf0, 0xf1, 0xff, 0x2f, 0xff, 0xf3, 0xff, 0xff, // 20 [24]
    0x4f, 0x5f, 0x67, 0x89, 0xfa, 0xbf, 0xff, 0xcd, // 21
    0xf0, 0xf1, 0xf2, 0x3f, 0xf4, 0x56, 0xff, 0xff, // 22 [32]
    0xff, 0xff, 0x7f, 0x8f, 0x9a, 0xff, 0xbc, 0xdf, // 23
    0x0f, 0x1f, 0xf2, 0xff, 0xff, 0x3f, 0xff, 0xff, // 30 [40]
    0xf4, 0xff, 0xf5, 0x6f, 0xff, 0xff, 0xff, 0xff, // 31
    0x0f, 0x1f, 0x23, 0xff, 0x45, 0x6f, 0xff, 0xff, // 32 [47]
    0xf7, 0xff, 0xf8, 0x9f, 0xff, 0xff, 0xff, 0xff, // 33
];

// ============================================================================
// Code 128 Decoder functions
// ============================================================================

/// Decode low signature
fn decode_lo(sig: i32) -> i8 {
    let offset =
        (((sig >> 1) & 0x01) | ((sig >> 3) & 0x06) | ((sig >> 5) & 0x18) | ((sig >> 7) & 0x60))
            as u8;
    let mut idx = LO_OFFSET[offset as usize];

    if (sig & 1) != 0 {
        idx &= 0xf;
    } else {
        idx >>= 4;
    }
    if idx == 0xf {
        return -1;
    }

    let base = ((sig >> 11) | ((sig >> 9) & 1)) as u8;
    zassert!(
        base < 8,
        -1,
        "sig={:x} offset={:x} idx={:x} base={:x}\n",
        sig,
        offset,
        idx,
        base
    );
    let idx = idx + LO_BASE[base as usize];

    zassert!(
        idx <= 0x50,
        -1,
        "sig={:x} offset={:x} base={:x} idx={:x}\n",
        sig,
        offset,
        base,
        idx
    );
    CHARACTERS[idx as usize] as i8
}

/// Decode high signature
fn decode_hi(mut sig: i32) -> i8 {
    let mut rev = (sig & 0x4400) != 0;
    if rev {
        sig = ((sig >> 12) & 0x000f)
            | ((sig >> 4) & 0x00f0)
            | ((sig << 4) & 0x0f00)
            | ((sig << 12) & 0xf000);
    }

    let mut idx = match sig {
        0x0014 => 0x0,
        0x0025 => 0x1,
        0x0034 => 0x2,
        0x0134 => 0x3,
        0x0143 => 0x4,
        0x0243 => 0x5,
        0x0341 => 0x6,
        0x0352 => 0x7,
        0x1024 => 0x8,
        0x1114 => 0x9,
        0x1134 => 0xa,
        0x1242 => 0xb,
        0x1243 => 0xc,
        0x1441 => {
            rev = false;
            0xd
        }
        _ => return -1,
    };
    if rev {
        idx += 0xe;
    }
    CHARACTERS[0x51 + idx] as i8
}

/// Calculate check value
fn calc_check(c: u8) -> u8 {
    if (c & 0x80) == 0 {
        return 0x18;
    }
    let c = c & 0x7f;
    if c < 0x3d {
        return if c < 0x30 && c != 0x17 { 0x10 } else { 0x20 };
    }
    if c < 0x50 {
        return if c == 0x4d { 0x20 } else { 0x10 };
    }
    if c < 0x67 { 0x20 } else { 0x10 }
}

/// Decode 6 elements
fn decode6(dcode: &ImageScanner) -> i8 {
    let s = dcode.code128.s6;
    if s < 5 {
        return -1;
    }

    // Build edge signature of character
    let sig = if dcode.color() == Color::Bar {
        (decode_e(dcode.get_width(0) + dcode.get_width(1), s, 11) << 12)
            | (decode_e(dcode.get_width(1) + dcode.get_width(2), s, 11) << 8)
            | (decode_e(dcode.get_width(2) + dcode.get_width(3), s, 11) << 4)
            | decode_e(dcode.get_width(3) + dcode.get_width(4), s, 11)
    } else {
        (decode_e(dcode.get_width(5) + dcode.get_width(4), s, 11) << 12)
            | (decode_e(dcode.get_width(4) + dcode.get_width(3), s, 11) << 8)
            | (decode_e(dcode.get_width(3) + dcode.get_width(2), s, 11) << 4)
            | decode_e(dcode.get_width(2) + dcode.get_width(1), s, 11)
    };

    if sig < 0 {
        return -1;
    }

    // Lookup edge signature
    let c = if (sig & 0x4444) != 0 {
        decode_hi(sig)
    } else {
        decode_lo(sig)
    };

    if c == -1 {
        return -1;
    }

    // Character validation
    let bars = if dcode.color() == Color::Bar {
        dcode.get_width(0) + dcode.get_width(2) + dcode.get_width(4)
    } else {
        dcode.get_width(1) + dcode.get_width(3) + dcode.get_width(5)
    };
    let bars = bars * 11 * 4 / s;
    let chk = calc_check(c as u8);

    if (chk as i32 - 7) > bars as i32 || bars as i32 > (chk as i32 + 7) {
        return -1;
    }

    c & 0x7f
}

/// Validate checksum
fn validate_checksum(dcode: &ImageScanner) -> bool {
    if dcode.code128.character() < 3 {
        return true;
    }

    let buf = dcode.buffer_slice();

    // Add in irregularly weighted start character
    let idx = if dcode.code128.direction() != 0 {
        (dcode.code128.character() - 1) as usize
    } else {
        0
    };
    let mut sum = buf[idx] as u32;
    if sum >= 103 {
        sum -= 103;
    }

    // Calculate sum in reverse to avoid multiply operations
    let mut acc: u32 = 0;
    for i in (1..(dcode.code128.character() - 2) as usize).rev() {
        zassert!(
            sum < 103,
            true,
            "dir={:x} i={:x} sum={:x} acc={:x}\n",
            dcode.code128.direction(),
            i,
            sum,
            acc
        );
        let idx = if dcode.code128.direction() != 0 {
            (dcode.code128.character() as usize) - 1 - i
        } else {
            i
        };
        acc += buf[idx] as u32;
        if acc >= 103 {
            acc -= 103;
        }
        zassert!(
            acc < 103,
            true,
            "dir={:x} i={:x} sum={:x} acc={:x}\n",
            dcode.code128.direction(),
            i,
            sum,
            acc
        );
        sum += acc;
        if sum >= 103 {
            sum -= 103;
        }
    }

    // Compare to check character
    let idx = if dcode.code128.direction() != 0 {
        1
    } else {
        (dcode.code128.character() - 2) as usize
    };
    let check = buf[idx] as u32;
    sum != check
}

/// Expand and decode character set C in place.
///
/// Set C encodes two digits per character, so each expanded character needs
/// one extra byte. The still-unprocessed tail is relocated to the end of the
/// buffer to make room, and `character` grows to match — the caller's loop
/// bound must follow it (see [`postprocess`]).
///
/// Returns the number of characters expanded, or `None` if the buffer would
/// overflow.
fn postprocess_c(
    buf: &mut Vec<u8>,
    character: &mut usize,
    start: usize,
    end: usize,
    dst: usize,
) -> Option<usize> {
    let delta = end - start;
    let newlen = *character + delta;
    if newlen > BUFFER_MAX {
        return None;
    }

    // Room for the relocated tail and for the two digits each character
    // expands into.
    let needed = newlen.max(dst + delta * 2);
    if buf.len() < needed {
        buf.resize(needed, 0);
    }

    // Relocate unprocessed data to end of buffer
    buf.copy_within(start..*character, start + delta);
    *character = newlen;

    for i in 0..delta {
        let j = dst + i * 2;
        // Convert each set C character into two ASCII digits
        let mut code = buf[start + delta + i];
        buf[j] = b'0';
        if code >= 50 {
            code -= 50;
            buf[j] += 5;
        }
        if code >= 30 {
            code -= 30;
            buf[j] += 3;
        }
        if code >= 20 {
            code -= 20;
            buf[j] += 2;
        }
        if code >= 10 {
            code -= 10;
            buf[j] += 1;
        }
        zassert!(
            buf[j] <= b'9',
            Some(delta),
            "start={:x} end={:x} i={:x} j={:x}\n",
            start,
            end,
            i,
            j
        );
        zassert!(
            code <= 9,
            Some(delta),
            "start={:x} end={:x} i={:x} j={:x}\n",
            start,
            end,
            i,
            j
        );
        buf[j + 1] = b'0' + code;
    }

    Some(delta)
}

/// Resolve scan direction and convert to ASCII.
///
/// Returns `true` on failure, matching the C original's error convention.
fn postprocess(dcode: &mut ImageScanner) -> bool {
    // Take ownership of the shared buffer for the duration: set-C expansion
    // grows it, and going through `buffer_mut_slice` would truncate it back
    // on the next access.
    let mut buf = dcode.take_buffer();
    let outcome = postprocess_buf(dcode, &mut buf);
    match outcome {
        Some(len) => {
            buf.truncate(len);
            dcode.put_buffer(buf);
            false
        }
        None => {
            dcode.put_buffer(buf);
            true
        }
    }
}

/// Body of [`postprocess`]; returns the decoded length, or `None` on failure.
fn postprocess_buf(dcode: &mut ImageScanner, buf: &mut Vec<u8>) -> Option<usize> {
    dcode.modifiers = 0;
    let direction = dcode.code128.direction();
    dcode.direction = 1 - 2 * (direction as i32);

    // `character` tracks the live buffer length the way the C original's
    // `dcode128->character` does: `postprocess_c` grows it as set-C runs
    // expand, and the loop below must see those updates.
    let mut character = dcode.code128.character() as usize;
    if character < 3 || buf.len() < character {
        return None;
    }

    if direction != 0 {
        buf[..character].reverse();
        zassert!(
            buf[character - 1] == STOP_REV,
            None,
            "dir={:x}\n",
            direction
        );
    } else {
        zassert!(
            buf[character - 1] == STOP_FWD,
            None,
            "dir={:x}\n",
            direction
        );
    }

    let start_code = buf[0];
    zassert!(
        (START_A..=START_C).contains(&start_code),
        None,
        "code={:x}\n",
        start_code
    );

    let mut charset = start_code - START_A;
    let mut cexp = if start_code == START_C { 1 } else { 0 };

    let mut i = 1usize;
    let mut j = 0usize;
    while i < character - 2 {
        let code = buf[i];

        zassert!(
            (code & 0x80) == 0,
            None,
            "i={:x} j={:x} code={:02x} charset={:x} cexp={:x}\n",
            i,
            j,
            code,
            charset,
            cexp
        );

        if (charset & 0x2) != 0 && code < 100 {
            // Defer character set C for expansion
            i += 1;
            continue;
        } else if code < 0x60 {
            // Convert character set B to ASCII
            let mut ascii_code = code + 0x20;
            if (charset == 0 || charset == 0x81) && ascii_code >= 0x60 {
                // Convert character set A to ASCII
                ascii_code -= 0x60;
            }
            if buf.len() <= j {
                buf.resize(j + 1, 0);
            }
            buf[j] = ascii_code;
            j += 1;
            if (charset & 0x80) != 0 {
                charset &= 0x7f;
            }
        } else {
            if (charset & 0x2) != 0 {
                // Expand character set C to ASCII
                zassert!(
                    cexp != 0,
                    None,
                    "i={:x} j={:x} code={:02x} charset={:x} cexp={:x}\n",
                    i,
                    j,
                    code,
                    charset,
                    cexp
                );
                let delta = postprocess_c(buf, &mut character, cexp, i, j)?;
                i += delta;
                j += delta * 2;
                cexp = 0;
            }
            if code < CODE_C {
                if code == SHIFT {
                    charset |= 0x80;
                } else if code == FNC2 {
                    // FIXME FNC2 - message append
                } else if code == FNC3 {
                    // FIXME FNC3 - initialize
                }
            } else if code == FNC1 {
                // FNC1 - Code 128 subsets or ASCII 0x1d
                if i == 1 {
                    dcode.modifiers |= Modifier::Gs1.bit();
                } else if i == 2 {
                    dcode.modifiers |= Modifier::Aim.bit();
                } else if i < character - 3 {
                    if buf.len() <= j {
                        buf.resize(j + 1, 0);
                    }
                    buf[j] = 0x1d;
                    j += 1;
                }
                // else drop trailing FNC1
            } else if code >= START_A {
                // truncated
                return None;
            } else {
                let newset = CODE_A - code;
                zassert!(
                    (CODE_C..=CODE_A).contains(&code),
                    None,
                    "i={:x} j={:x} code={:02x} charset={:x} cexp={:x}\n",
                    i,
                    j,
                    code,
                    charset,
                    cexp
                );
                if newset != charset {
                    charset = newset;
                } else {
                    // FIXME FNC4 - extended ASCII
                }
            }
            if (charset & 0x2) != 0 {
                cexp = i + 1;
            }
        }
        i += 1;
    }

    if (charset & 0x2) != 0 {
        zassert!(
            cexp != 0,
            None,
            "i={:x} j={:x} charset={:x} cexp={:x}\n",
            i,
            j,
            charset,
            cexp
        );
        j += postprocess_c(buf, &mut character, cexp, i, j)? * 2;
    }

    zassert!(j <= buf.len(), None, "j={:02x}\n", j);
    dcode.code128.set_character(j as i16);
    Some(j)
}

/// Main Code 128 decode function
pub(crate) fn decode_code128(dcode: &mut ImageScanner) -> SymbolType {
    // Update latest character width
    dcode.code128.s6 = dcode
        .code128
        .s6
        .wrapping_sub(dcode.get_width(6))
        .wrapping_add(dcode.get_width(0));

    if (dcode.code128.character() < 0 && dcode.color() != Color::Space)
        || (dcode.code128.character() >= 0
            && (dcode.code128.element() + 1 != 6
                || dcode.color() as u8 != dcode.code128.direction()))
    {
        if dcode.code128.character() >= 0 {
            dcode.code128.set_element(dcode.code128.element() + 1);
        }
        return SymbolType::None;
    }
    dcode.code128.set_element(0);

    let c = decode6(dcode);

    if dcode.code128.character() < 0 {
        let qz = dcode.get_width(6);
        if c < START_A as i8 || c > STOP_REV as i8 || c == STOP_FWD as i8 {
            return SymbolType::None;
        }
        if qz != 0 && qz < (dcode.code128.s6 * 3) / 4 {
            return SymbolType::None;
        }
        // Decoded valid start/stop - initialize state
        dcode.code128.set_character(1);
        if c == STOP_REV as i8 {
            dcode.code128.set_direction(Color::Bar as u8);
            dcode.code128.set_element(7);
        } else {
            dcode.code128.set_direction(Color::Space as u8);
        }
        dcode.code128.set_start(c as u8);
        dcode.code128.width = dcode.code128.s6;
        return SymbolType::None;
    } else if c < 0
        || dcode
            .set_buffer_capacity(dcode.code128.character() as usize + 1)
            .is_err()
    {
        if dcode.code128.character() > 1 {
            dcode.release_lock(SymbolType::Code128);
        }
        dcode.code128.set_character(-1);
        return SymbolType::None;
    } else {
        let dw = dcode.code128.width.abs_diff(dcode.code128.s6);
        let dw = dw * 4;
        if dw > dcode.code128.width {
            if dcode.code128.character() > 1 {
                dcode.release_lock(SymbolType::Code128);
            }
            dcode.code128.set_character(-1);
            return SymbolType::None;
        }
    }
    dcode.code128.width = dcode.code128.s6;

    let capacity = dcode.buffer_capacity();
    zassert!(
        (capacity as i16) > dcode.code128.character(),
        SymbolType::None,
        "alloc={:x} idx={:x} c={:02x}\n",
        capacity,
        dcode.code128.character(),
        c
    );

    if dcode.code128.character() == 1 {
        // Lock shared resources
        if !dcode.acquire_lock(SymbolType::Code128) {
            dcode.code128.set_character(-1);
            return SymbolType::None;
        }
        let start = dcode.code128.start();
        if let Ok(buf) = dcode.buffer_mut_slice(1) {
            buf[0] = start;
        }
    }

    let character = dcode.code128.character();
    if let Ok(buf) = dcode.buffer_mut_slice((character + 1) as usize) {
        buf[character as usize] = c as u8;
    }
    dcode.code128.set_character(character + 1);

    if dcode.code128.character() > 2
        && ((dcode.code128.direction() != 0 && c >= START_A as i8 && c <= START_C as i8)
            || (dcode.code128.direction() == 0 && c == STOP_FWD as i8))
    {
        // FIXME STOP_FWD should check extra bar (and QZ!)
        let mut sym = SymbolType::Code128;
        #[allow(clippy::if_same_then_else)]
        let (min_len, max_len) = dcode
            .get_length_limits(SymbolType::Code128)
            // zbar sets no MIN_LEN for Code 128, so short payloads decode.
            .unwrap_or((0, 0));

        if validate_checksum(dcode)
            || postprocess(dcode)
            || dcode.code128.character() < min_len as i16
            || (max_len > 0 && dcode.code128.character() > max_len as i16)
        {
            sym = SymbolType::None;
        }
        dcode.code128.set_character(-1);
        if sym == SymbolType::None {
            dcode.release_lock(SymbolType::Code128);
        }
        return sym;
    }
    SymbolType::None
}

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

    /// Switch to character set B. Only the decoder's `CODE_A`/`CODE_C`
    /// bounds are needed by the decoder itself, so this one is test-local.
    const CODE_B: u8 = 0x64;

    /// Drive `postprocess` over a synthetic symbol buffer, as `decode_code128`
    /// would have filled it: start code, data characters, check character,
    /// stop character. Returns the decoded bytes.
    fn run_postprocess(codes: &[u8]) -> Option<Vec<u8>> {
        let mut dcode = ImageScanner::default();
        dcode
            .buffer_mut_slice(codes.len())
            .expect("buffer")
            .copy_from_slice(codes);
        dcode.code128.set_character(codes.len() as i16);
        dcode.code128.set_direction(0);
        if postprocess(&mut dcode) {
            return None;
        }
        Some(dcode.buffer_slice().to_vec())
    }

    /// Set C encodes two digits per character; the decoder expands them in
    /// place, which grows the buffer.
    #[test]
    fn postprocess_expands_character_set_c() {
        // START_C "12" "34" <check> STOP
        let decoded = run_postprocess(&[START_C, 12, 34, 0, STOP_FWD]).expect("decode");
        assert_eq!(decoded, b"1234");
    }

    /// Regression: data following a set-C run used to be dropped, because the
    /// loop bound was captured before the expansion grew the character count.
    #[test]
    fn postprocess_keeps_data_after_character_set_c() {
        // START_C "12" "34" CODE_B 'A' 'B' <check> STOP
        let decoded = run_postprocess(&[
            START_C,
            12,
            34,
            CODE_B,
            b'A' - 0x20,
            b'B' - 0x20,
            0,
            STOP_FWD,
        ])
        .expect("decode");
        assert_eq!(decoded, b"1234AB");
    }

    /// Two separate set-C runs: the second expansion must see the buffer the
    /// first one grew, not a truncated copy of it.
    #[test]
    fn postprocess_handles_repeated_character_set_c() {
        // START_C "12" CODE_B 'A' CODE_C "56" "78" <check> STOP
        let decoded = run_postprocess(&[
            START_C,
            12,
            CODE_B,
            b'A' - 0x20,
            CODE_C,
            56,
            78,
            0,
            STOP_FWD,
        ])
        .expect("decode");
        assert_eq!(decoded, b"12A5678");
    }

    /// Decoded data is the payload only — no C-style NUL terminator.
    #[test]
    fn postprocess_does_not_emit_a_nul_terminator() {
        let decoded = run_postprocess(&[START_C, 12, 34, 0, STOP_FWD]).expect("decode");
        assert!(!decoded.contains(&0), "unexpected NUL in {decoded:?}");
    }
}