qrcode-generator 6.0.0

Generates ISO/IEC 18004 QR Code and Micro QR Code symbols and ISO/IEC 23941 rMQR symbols in pure Rust, then renders them as grayscale, PNG and SVG images.
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
use alloc::{collections::VecDeque, vec, vec::Vec};

#[cfg(feature = "qr")]
use super::QrVersion;
use super::{EciAssignment, Mode, Segment, alphanumeric_value, mode_rank};
use crate::EncodeError;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Profile {
    mode_bits: u8,
    cci:       [u8; 4],
}

impl Profile {
    #[cfg(feature = "qr")]
    #[inline]
    pub(crate) const fn qr(version: QrVersion) -> Self {
        Self {
            mode_bits: 4,
            cci:       [
                Mode::Numeric.cci_bits(version),
                Mode::Alphanumeric.cci_bits(version),
                Mode::Byte.cci_bits(version),
                Mode::Kanji.cci_bits(version),
            ],
        }
    }

    #[cfg(feature = "rmqr")]
    #[inline]
    pub(crate) const fn rmqr(cci: [u8; 4]) -> Self {
        Self {
            mode_bits: 3,
            cci,
        }
    }

    #[inline]
    pub(crate) const fn cci_bits(self, mode: Mode) -> u8 {
        match mode {
            Mode::Numeric => self.cci[0],
            Mode::Alphanumeric => self.cci[1],
            Mode::Byte => self.cci[2],
            Mode::Kanji => self.cci[3],
            Mode::Eci => 0,
        }
    }

    #[inline]
    const fn overhead_bits(self, mode: Mode) -> usize {
        self.mode_bits as usize + self.cci_bits(mode) as usize
    }

    #[inline]
    const fn eci_bits(self) -> usize {
        self.mode_bits as usize + 8
    }
}

// The character interpretation in force, following the strict ECI semantics of ISO/IEC 18004.
// `Default` means no ECI header has been emitted yet, so byte data reads as ISO-8859-1 and Kanji mode reads as Shift JIS.
// The other states are entered by emitting the matching character set ECI header.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Interpretation {
    Default  = 0,
    Latin1   = 1,
    Utf8     = 2,
    #[cfg(feature = "kanji")]
    ShiftJis = 3,
}

impl Interpretation {
    #[cfg(feature = "kanji")]
    const ALL: [Self; 4] = [Self::Default, Self::Latin1, Self::Utf8, Self::ShiftJis];
    #[cfg(not(feature = "kanji"))]
    const ALL: [Self; 3] = [Self::Default, Self::Latin1, Self::Utf8];
    const COUNT: usize = Self::ALL.len();

    #[inline]
    const fn index(self) -> usize {
        self as usize
    }

    // Returns the ECI assignment that this interpretation declares, or `None` for the default one.
    #[inline]
    const fn eci(self) -> Option<EciAssignment> {
        match self {
            Self::Default => None,
            Self::Latin1 => Some(EciAssignment::ISO_8859_1),
            Self::Utf8 => Some(EciAssignment::UTF_8),
            #[cfg(feature = "kanji")]
            Self::ShiftJis => Some(EciAssignment::SHIFT_JIS),
        }
    }
}

#[derive(Clone, Copy)]
struct TextStep {
    bits:                    usize,
    switches:                usize,
    segments:                usize,
    previous_position:       usize,
    previous_interpretation: Interpretation,
    mode:                    Mode,
    interpretation:          Interpretation,
    switched:                bool,
}

// One queued segment start with the end-dependent cost term removed, so entries compare independently of the end.
#[derive(Clone, Copy)]
struct QueueEntry {
    cost:       isize,
    switches:   usize,
    segments:   usize,
    start:      usize,
    // The start position measured in the coordinate of its queue: characters, UTF-8 bytes, Shift JIS bytes or encoded counts.
    coordinate: usize,
    step:       TextStep,
    active:     Interpretation,
}

impl QueueEntry {
    #[inline]
    const fn key(self) -> (isize, usize, usize, usize) {
        (self.cost, self.switches, self.segments, self.start)
    }
}

#[inline]
fn push_entry(queue: &mut VecDeque<QueueEntry>, entry: QueueEntry) {
    while queue.back().is_some_and(|back| back.key() > entry.key()) {
        queue.pop_back();
    }

    queue.push_back(entry);
}

// Per-character tables shared by the dynamic program and the reconstruction.
struct TextTables {
    offsets:      Vec<usize>,
    wide:         Vec<bool>,
    digit:        Vec<bool>,
    alnum_ok:     Vec<bool>,
    // Prefix sums of encoded alphanumeric characters; FNC1 doubles a literal percent.
    alnum_prefix: Vec<usize>,
    #[cfg(feature = "kanji")]
    kanji_ok:     Vec<bool>,
    #[cfg(feature = "kanji")]
    sjis_ok:      Vec<bool>,
    // Prefix sums of Shift JIS byte lengths; positions after an unencodable character keep the previous sum.
    #[cfg(feature = "kanji")]
    sjis_prefix:  Vec<usize>,
}

impl TextTables {
    fn new(text: &str, fnc1: bool) -> Self {
        let mut offsets: Vec<usize> = text.char_indices().map(|(offset, _)| offset).collect();

        offsets.push(text.len());

        let length = offsets.len() - 1;
        let mut wide = Vec::with_capacity(length);
        let mut digit = Vec::with_capacity(length);
        let mut alnum_ok = Vec::with_capacity(length);
        let mut alnum_prefix = Vec::with_capacity(length + 1);
        #[cfg(feature = "kanji")]
        let mut kanji_ok = Vec::with_capacity(length);
        #[cfg(feature = "kanji")]
        let mut sjis_ok = Vec::with_capacity(length);
        #[cfg(feature = "kanji")]
        let mut sjis_prefix = Vec::with_capacity(length + 1);

        alnum_prefix.push(0);
        #[cfg(feature = "kanji")]
        sjis_prefix.push(0);

        for character in text.chars() {
            wide.push(u32::from(character) > 0xFF);
            digit.push(character.is_ascii_digit());

            let byte = character as u32;
            let eligible = character.is_ascii()
                && (alphanumeric_value(byte as u8).is_some() || (fnc1 && byte == 0x1D));

            alnum_ok.push(eligible);

            let encoded = usize::from(eligible) * (1 + usize::from(fnc1 && character == '%'))
                + usize::from(!eligible);

            alnum_prefix
                .push(alnum_prefix.last().copied().expect("the prefix starts at zero") + encoded);

            #[cfg(feature = "kanji")]
            {
                let (kanji, sjis_length) = sjis_classification(character);

                kanji_ok.push(kanji);

                let previous = sjis_prefix.last().copied().expect("the prefix starts at zero");

                match sjis_length {
                    Some(bytes) => {
                        sjis_ok.push(true);
                        sjis_prefix.push(previous + bytes);
                    },
                    None => {
                        sjis_ok.push(false);
                        sjis_prefix.push(previous);
                    },
                }
            }
        }

        Self {
            offsets,
            wide,
            digit,
            alnum_ok,
            alnum_prefix,
            #[cfg(feature = "kanji")]
            kanji_ok,
            #[cfg(feature = "kanji")]
            sjis_ok,
            #[cfg(feature = "kanji")]
            sjis_prefix,
        }
    }
}

// Reports Kanji mode eligibility and the ECI 20 byte segment length of a character with one Shift JIS conversion.
// Backslash, tilde, yen and overline are rejected because WHATWG and JIS X 0201 decode bytes 5C and 7E differently.
#[cfg(feature = "kanji")]
fn sjis_classification(character: char) -> (bool, Option<usize>) {
    match character {
        '\\' | '~' | 'Â¥' | '\u{203E}' => (false, None),
        _ if character.is_ascii() => (false, Some(1)),
        '\u{FF61}'..='\u{FF9F}' => (false, Some(1)),
        _ => {
            let mut utf8 = [0; 4];
            let text = character.encode_utf8(&mut utf8);
            let (encoded, _, had_errors) = encoding_rs::SHIFT_JIS.encode(text);

            if had_errors {
                return (false, None);
            }

            // Kanji mode covers exactly the two-byte values inside the two compactable Shift JIS ranges.
            let kanji = encoded.len() == 2
                && matches!(
                    u16::from_be_bytes([encoded[0], encoded[1]]),
                    0x8140..=0x9FFC | 0xE040..=0xEBBF
                );

            (kanji, Some(encoded.len()))
        },
    }
}

pub(crate) fn text(
    text: &str,
    profile: Profile,
    fnc1: bool,
    force_initial_eci: bool,
) -> Result<Vec<Segment>, EncodeError> {
    let tables = TextTables::new(text, fnc1);
    let length = tables.offsets.len() - 1;

    // Each position keeps the shortest path for every interpretation that can be in force there.
    let mut best = vec![[None; Interpretation::COUNT]; length + 1];

    // A following Structured Append symbol must declare the interpretation that starts its data.
    if force_initial_eci {
        for interpretation in Interpretation::ALL {
            if interpretation == Interpretation::Default {
                continue;
            }

            best[0][interpretation.index()] = Some(TextStep {
                bits: profile.eci_bits(),
                switches: 1,
                segments: 1,
                previous_position: 0,
                previous_interpretation: interpretation,
                mode: Mode::Byte,
                interpretation,
                switched: false,
            });
        }
    } else {
        best[0][Interpretation::Default.index()] = Some(TextStep {
            bits:                    0,
            switches:                0,
            segments:                0,
            previous_position:       0,
            previous_interpretation: Interpretation::Default,
            mode:                    Mode::Byte,
            interpretation:          Interpretation::Default,
            switched:                false,
        });
    }

    let eci_bits = profile.eci_bits();
    let numeric_overhead = profile.overhead_bits(Mode::Numeric);
    let alnum_overhead = profile.overhead_bits(Mode::Alphanumeric);
    let byte_overhead = profile.overhead_bits(Mode::Byte);
    #[cfg(feature = "kanji")]
    let kanji_overhead = profile.overhead_bits(Mode::Kanji);

    let numeric_window = max_count(Mode::Numeric, profile);
    let alnum_window = max_count(Mode::Alphanumeric, profile);
    let byte_window = max_count(Mode::Byte, profile);
    #[cfg(feature = "kanji")]
    let kanji_window = max_count(Mode::Kanji, profile);

    // One monotonic queue per target keeps the cheapest in-range segment start, making every edge O(1) amortized.
    let mut byte_queues: [VecDeque<QueueEntry>; Interpretation::COUNT] =
        core::array::from_fn(|_| VecDeque::new());
    let mut numeric_queues: [[VecDeque<QueueEntry>; 3]; Interpretation::COUNT] =
        core::array::from_fn(|_| core::array::from_fn(|_| VecDeque::new()));
    let mut alnum_queues: [[VecDeque<QueueEntry>; 2]; Interpretation::COUNT] =
        core::array::from_fn(|_| core::array::from_fn(|_| VecDeque::new()));
    // Kanji mode is only valid under the default interpretation or an explicit Shift JIS ECI.
    #[cfg(feature = "kanji")]
    let mut kanji_queues: [VecDeque<QueueEntry>; 2] = [VecDeque::new(), VecDeque::new()];

    for position in 0..=length {
        if position >= 1 {
            // Byte edges targeting Default and Latin1 measure the segment in characters.
            for target in [Interpretation::Default, Interpretation::Latin1] {
                let queue = &mut byte_queues[target.index()];

                while queue.front().is_some_and(|entry| entry.coordinate + byte_window < position) {
                    queue.pop_front();
                }

                if let Some(entry) = queue.front().copied() {
                    let switched = entry.active != target;

                    update_text(
                        &mut best[position][target.index()],
                        entry.step,
                        entry.start,
                        entry.active,
                        Mode::Byte,
                        target,
                        switched,
                        usize::from(switched) * eci_bits
                            + byte_overhead
                            + (position - entry.coordinate) * 8,
                    );
                }
            }

            // Byte edges targeting Utf8 measure the segment in UTF-8 bytes.
            {
                let coordinate = tables.offsets[position];
                let queue = &mut byte_queues[Interpretation::Utf8.index()];

                while queue.front().is_some_and(|entry| entry.coordinate + byte_window < coordinate)
                {
                    queue.pop_front();
                }

                if let Some(entry) = queue.front().copied() {
                    let switched = entry.active != Interpretation::Utf8;

                    update_text(
                        &mut best[position][Interpretation::Utf8.index()],
                        entry.step,
                        entry.start,
                        entry.active,
                        Mode::Byte,
                        Interpretation::Utf8,
                        switched,
                        usize::from(switched) * eci_bits
                            + byte_overhead
                            + (coordinate - entry.coordinate) * 8,
                    );
                }
            }

            // Byte edges targeting ShiftJis measure the segment in Shift JIS bytes.
            #[cfg(feature = "kanji")]
            {
                let coordinate = tables.sjis_prefix[position];
                let queue = &mut byte_queues[Interpretation::ShiftJis.index()];

                while queue.front().is_some_and(|entry| entry.coordinate + byte_window < coordinate)
                {
                    queue.pop_front();
                }

                if let Some(entry) = queue.front().copied() {
                    let switched = entry.active != Interpretation::ShiftJis;

                    update_text(
                        &mut best[position][Interpretation::ShiftJis.index()],
                        entry.step,
                        entry.start,
                        entry.active,
                        Mode::Byte,
                        Interpretation::ShiftJis,
                        switched,
                        usize::from(switched) * eci_bits
                            + byte_overhead
                            + (coordinate - entry.coordinate) * 8,
                    );
                }
            }

            // Numeric and alphanumeric segments never change the interpretation in force.
            for state in Interpretation::ALL {
                for queue in &mut numeric_queues[state.index()] {
                    while queue.front().is_some_and(|entry| entry.start + numeric_window < position)
                    {
                        queue.pop_front();
                    }

                    if let Some(entry) = queue.front().copied() {
                        update_text(
                            &mut best[position][state.index()],
                            entry.step,
                            entry.start,
                            state,
                            Mode::Numeric,
                            state,
                            false,
                            numeric_overhead + numeric_bits(position - entry.start),
                        );
                    }
                }

                let encoded = tables.alnum_prefix[position];

                for queue in &mut alnum_queues[state.index()] {
                    while queue
                        .front()
                        .is_some_and(|entry| entry.coordinate + alnum_window < encoded)
                    {
                        queue.pop_front();
                    }

                    if let Some(entry) = queue.front().copied() {
                        update_text(
                            &mut best[position][state.index()],
                            entry.step,
                            entry.start,
                            state,
                            Mode::Alphanumeric,
                            state,
                            false,
                            alnum_overhead + alphanumeric_bits(encoded - entry.coordinate),
                        );
                    }
                }
            }

            #[cfg(feature = "kanji")]
            {
                // Kanji edges targeting the default interpretation need no ECI header.
                let queue = &mut kanji_queues[0];

                while queue.front().is_some_and(|entry| entry.start + kanji_window < position) {
                    queue.pop_front();
                }

                if let Some(entry) = queue.front().copied() {
                    update_text(
                        &mut best[position][Interpretation::Default.index()],
                        entry.step,
                        entry.start,
                        Interpretation::Default,
                        Mode::Kanji,
                        Interpretation::Default,
                        false,
                        kanji_overhead + (position - entry.start) * 13,
                    );
                }

                // Kanji edges after any explicit ECI must declare Shift JIS first.
                let queue = &mut kanji_queues[1];

                while queue.front().is_some_and(|entry| entry.start + kanji_window < position) {
                    queue.pop_front();
                }

                if let Some(entry) = queue.front().copied() {
                    let switched = entry.active != Interpretation::ShiftJis;

                    update_text(
                        &mut best[position][Interpretation::ShiftJis.index()],
                        entry.step,
                        entry.start,
                        entry.active,
                        Mode::Kanji,
                        Interpretation::ShiftJis,
                        switched,
                        usize::from(switched) * eci_bits
                            + kanji_overhead
                            + (position - entry.start) * 13,
                    );
                }
            }
        }

        if position == length {
            break;
        }

        let default_bits = best[position][Interpretation::Default.index()].map(|step| step.bits);

        for state in Interpretation::ALL {
            let Some(step) = best[position][state.index()] else {
                continue;
            };

            // A default prefix replays any continuation of this state by paying its ECI header later, so the state is not a useful source.
            if state != Interpretation::Default
                && default_bits.is_some_and(|bits| step.bits >= bits + eci_bits)
            {
                continue;
            }

            let bits = step.bits as isize;

            // A start only enters a queue when its mode can extend through the character here.
            // A byte segment kept in the default interpretation can only continue a default prefix.
            if !tables.wide[position] {
                if state == Interpretation::Default {
                    push_entry(&mut byte_queues[Interpretation::Default.index()], QueueEntry {
                        cost: bits - 8 * position as isize,
                        switches: step.switches,
                        segments: step.segments,
                        start: position,
                        coordinate: position,
                        step,
                        active: state,
                    });
                } else {
                    // Declaring ECI 3 from the default interpretation is never cheaper than staying in it.
                    let switched = state != Interpretation::Latin1;

                    push_entry(&mut byte_queues[Interpretation::Latin1.index()], QueueEntry {
                        cost: bits + (usize::from(switched) * eci_bits) as isize
                            - 8 * position as isize,
                        switches: step.switches + usize::from(switched),
                        segments: step.segments + usize::from(switched),
                        start: position,
                        coordinate: position,
                        step,
                        active: state,
                    });
                }
            }

            {
                let switched = state != Interpretation::Utf8;
                let coordinate = tables.offsets[position];

                push_entry(&mut byte_queues[Interpretation::Utf8.index()], QueueEntry {
                    cost: bits + (usize::from(switched) * eci_bits) as isize
                        - 8 * coordinate as isize,
                    switches: step.switches + usize::from(switched),
                    segments: step.segments + usize::from(switched),
                    start: position,
                    coordinate,
                    step,
                    active: state,
                });
            }

            #[cfg(feature = "kanji")]
            if tables.sjis_ok[position] {
                let switched = state != Interpretation::ShiftJis;
                let coordinate = tables.sjis_prefix[position];

                push_entry(&mut byte_queues[Interpretation::ShiftJis.index()], QueueEntry {
                    cost: bits + (usize::from(switched) * eci_bits) as isize
                        - 8 * coordinate as isize,
                    switches: step.switches + usize::from(switched),
                    segments: step.segments + usize::from(switched),
                    start: position,
                    coordinate,
                    step,
                    active: state,
                });
            }

            if tables.digit[position] {
                push_entry(&mut numeric_queues[state.index()][position % 3], QueueEntry {
                    cost: 3 * bits - 10 * position as isize,
                    switches: step.switches,
                    segments: step.segments,
                    start: position,
                    coordinate: position,
                    step,
                    active: state,
                });
            }

            if tables.alnum_ok[position] {
                let coordinate = tables.alnum_prefix[position];

                push_entry(&mut alnum_queues[state.index()][coordinate & 1], QueueEntry {
                    cost: 2 * bits - 11 * coordinate as isize,
                    switches: step.switches,
                    segments: step.segments,
                    start: position,
                    coordinate,
                    step,
                    active: state,
                });
            }

            #[cfg(feature = "kanji")]
            if tables.kanji_ok[position] {
                if state == Interpretation::Default {
                    push_entry(&mut kanji_queues[0], QueueEntry {
                        cost: bits - 13 * position as isize,
                        switches: step.switches,
                        segments: step.segments,
                        start: position,
                        coordinate: position,
                        step,
                        active: state,
                    });
                } else {
                    // Declaring ECI 20 from the default interpretation is never cheaper than staying in it.
                    let switched = state != Interpretation::ShiftJis;

                    push_entry(&mut kanji_queues[1], QueueEntry {
                        cost: bits + (usize::from(switched) * eci_bits) as isize
                            - 13 * position as isize,
                        switches: step.switches + usize::from(switched),
                        segments: step.segments + usize::from(switched),
                        start: position,
                        coordinate: position,
                        step,
                        active: state,
                    });
                }
            }
        }

        // A character that a mode cannot represent ends every segment run of that mode.
        if !tables.digit[position] {
            for queues in &mut numeric_queues {
                for queue in queues {
                    queue.clear();
                }
            }
        }

        if !tables.alnum_ok[position] {
            for queues in &mut alnum_queues {
                for queue in queues {
                    queue.clear();
                }
            }
        }

        if tables.wide[position] {
            byte_queues[Interpretation::Default.index()].clear();
            byte_queues[Interpretation::Latin1.index()].clear();
        }

        #[cfg(feature = "kanji")]
        {
            if !tables.kanji_ok[position] {
                kanji_queues[0].clear();
                kanji_queues[1].clear();
            }

            if !tables.sjis_ok[position] {
                byte_queues[Interpretation::ShiftJis.index()].clear();
            }
        }
    }

    let mut final_choice: Option<(Interpretation, TextStep)> = None;

    // The iteration order makes ties prefer the default interpretation, then the lowest ECI usage.
    for interpretation in Interpretation::ALL {
        if let Some(step) = best[length][interpretation.index()]
            && final_choice.is_none_or(|(_, current)| {
                (step.bits, step.switches, step.segments)
                    < (current.bits, current.switches, current.segments)
            })
        {
            final_choice = Some((interpretation, step));
        }
    }

    let (final_interpretation, _) = final_choice
        .ok_or(EncodeError::DataTooLong {
            required_bits: None, capacity_bits: 0
        })?;

    // Backtracking also recovers the interpretation selected before the first segment.
    let mut edges = Vec::new();
    let mut position = length;
    let mut interpretation = final_interpretation;

    while position != 0 {
        let step = best[position][interpretation.index()].expect("the final state is reachable");
        edges.push((step.previous_position, position, step));
        position = step.previous_position;
        interpretation = step.previous_interpretation;
    }

    edges.reverse();

    let mut result = Vec::new();

    if let Some(assignment) = interpretation.eci() {
        result.push(Segment::eci(assignment));
    }

    for (start, end, step) in edges {
        if step.switched {
            result.push(Segment::eci(
                step.interpretation.eci().expect("switched edges declare an explicit ECI"),
            ));
        }

        let slice = &text[tables.offsets[start]..tables.offsets[end]];

        result.push(match step.mode {
            Mode::Numeric => Segment::numeric(slice)?,
            Mode::Alphanumeric if fnc1 => Segment::fnc1_alphanumeric(slice.as_bytes())?,
            Mode::Alphanumeric => Segment::alphanumeric(slice)?,
            Mode::Byte => match step.interpretation {
                Interpretation::Default | Interpretation::Latin1 => {
                    let bytes: Vec<u8> = slice.chars().map(|character| character as u8).collect();
                    Segment::bytes(&bytes)
                },
                Interpretation::Utf8 => Segment::bytes(slice.as_bytes()),
                #[cfg(feature = "kanji")]
                Interpretation::ShiftJis => {
                    let (encoded, _, had_errors) = encoding_rs::SHIFT_JIS.encode(slice);

                    debug_assert!(!had_errors);

                    Segment::bytes(&encoded)
                },
            },
            #[cfg(feature = "kanji")]
            Mode::Kanji => Segment::kanji(slice)?,
            #[cfg(not(feature = "kanji"))]
            Mode::Kanji => unreachable!(),
            Mode::Eci => unreachable!(),
        });
    }
    Ok(result)
}

#[derive(Clone, Copy)]
struct ByteStep {
    bits:     usize,
    segments: usize,
    previous: usize,
    mode:     Mode,
}

// One queued byte-segmentation start with the end-dependent cost term removed.
#[derive(Clone, Copy)]
struct ByteQueueEntry {
    cost:       isize,
    segments:   usize,
    start:      usize,
    coordinate: usize,
    step:       ByteStep,
}

impl ByteQueueEntry {
    #[inline]
    const fn key(self) -> (isize, usize, usize) {
        (self.cost, self.segments, self.start)
    }
}

#[inline]
fn push_byte_entry(queue: &mut VecDeque<ByteQueueEntry>, entry: ByteQueueEntry) {
    while queue.back().is_some_and(|back| back.key() > entry.key()) {
        queue.pop_back();
    }

    queue.push_back(entry);
}

pub(crate) fn bytes(
    data: &[u8],
    profile: Profile,
    fnc1: bool,
) -> Result<Vec<Segment>, EncodeError> {
    // Each offset stores the shortest complete segmentation of the preceding bytes.
    let mut best = vec![None; data.len() + 1];

    best[0] = Some(ByteStep {
        bits: 0, segments: 0, previous: 0, mode: Mode::Byte
    });

    // Prefix sums of encoded alphanumeric characters; FNC1 doubles a literal percent.
    let mut alnum_prefix = Vec::with_capacity(data.len() + 1);

    alnum_prefix.push(0usize);

    for &byte in data {
        let eligible = alphanumeric_value(byte).is_some() || (fnc1 && byte == 0x1D);
        let encoded = usize::from(eligible) * (1 + usize::from(fnc1 && byte == b'%'))
            + usize::from(!eligible);

        alnum_prefix
            .push(alnum_prefix.last().copied().expect("the prefix starts at zero") + encoded);
    }

    let numeric_overhead = profile.overhead_bits(Mode::Numeric);
    let alnum_overhead = profile.overhead_bits(Mode::Alphanumeric);
    let byte_overhead = profile.overhead_bits(Mode::Byte);

    let numeric_window = max_count(Mode::Numeric, profile);
    let alnum_window = max_count(Mode::Alphanumeric, profile);
    let byte_window = max_count(Mode::Byte, profile);

    // A monotonic queue per mode keeps the cheapest in-range segment start, making each edge O(1) amortized.
    let mut byte_queue: VecDeque<ByteQueueEntry> = VecDeque::new();
    let mut numeric_queues: [VecDeque<ByteQueueEntry>; 3] =
        core::array::from_fn(|_| VecDeque::new());
    let mut alnum_queues: [VecDeque<ByteQueueEntry>; 2] = core::array::from_fn(|_| VecDeque::new());

    for position in 0..=data.len() {
        if position >= 1 {
            while byte_queue.front().is_some_and(|entry| entry.start + byte_window < position) {
                byte_queue.pop_front();
            }

            if let Some(entry) = byte_queue.front().copied() {
                update_byte(
                    &mut best[position],
                    entry.step,
                    entry.start,
                    Mode::Byte,
                    byte_overhead + (position - entry.start) * 8,
                );
            }

            for queue in &mut numeric_queues {
                while queue.front().is_some_and(|entry| entry.start + numeric_window < position) {
                    queue.pop_front();
                }

                if let Some(entry) = queue.front().copied() {
                    update_byte(
                        &mut best[position],
                        entry.step,
                        entry.start,
                        Mode::Numeric,
                        numeric_overhead + numeric_bits(position - entry.start),
                    );
                }
            }

            let encoded = alnum_prefix[position];

            for queue in &mut alnum_queues {
                while queue.front().is_some_and(|entry| entry.coordinate + alnum_window < encoded) {
                    queue.pop_front();
                }

                if let Some(entry) = queue.front().copied() {
                    update_byte(
                        &mut best[position],
                        entry.step,
                        entry.start,
                        Mode::Alphanumeric,
                        alnum_overhead + alphanumeric_bits(encoded - entry.coordinate),
                    );
                }
            }
        }

        if position == data.len() {
            break;
        }

        let byte = data[position];
        let digit = byte.is_ascii_digit();
        let alnum = alphanumeric_value(byte).is_some() || (fnc1 && byte == 0x1D);

        // A start only enters a queue when its mode can extend through the byte at this position.
        if let Some(step) = best[position] {
            let bits = step.bits as isize;

            push_byte_entry(&mut byte_queue, ByteQueueEntry {
                cost: bits - 8 * position as isize,
                segments: step.segments,
                start: position,
                coordinate: position,
                step,
            });

            if digit {
                push_byte_entry(&mut numeric_queues[position % 3], ByteQueueEntry {
                    cost: 3 * bits - 10 * position as isize,
                    segments: step.segments,
                    start: position,
                    coordinate: position,
                    step,
                });
            }

            if alnum {
                let coordinate = alnum_prefix[position];

                push_byte_entry(&mut alnum_queues[coordinate & 1], ByteQueueEntry {
                    cost: 2 * bits - 11 * coordinate as isize,
                    segments: step.segments,
                    start: position,
                    coordinate,
                    step,
                });
            }
        }

        // A byte that a mode cannot represent ends every segment run of that mode.
        if !digit {
            for queue in &mut numeric_queues {
                queue.clear();
            }
        }

        if !alnum {
            for queue in &mut alnum_queues {
                queue.clear();
            }
        }
    }

    reconstruct_bytes(data, best, fnc1)
}

fn reconstruct_bytes(
    data: &[u8],
    best: Vec<Option<ByteStep>>,
    fnc1: bool,
) -> Result<Vec<Segment>, EncodeError> {
    let mut position = data.len();
    let mut ranges = Vec::new();

    while position != 0 {
        let step = best[position]
            .ok_or(EncodeError::DataTooLong {
                required_bits: None, capacity_bits: 0
            })?;

        ranges.push((step.previous, position, step.mode));
        position = step.previous;
    }

    ranges.reverse();
    ranges
        .into_iter()
        .map(|(start, end, mode)| match mode {
            Mode::Numeric => Segment::numeric(
                core::str::from_utf8(&data[start..end]).expect("numeric data is UTF-8"),
            ),
            Mode::Alphanumeric if fnc1 => Segment::fnc1_alphanumeric(&data[start..end]),
            Mode::Alphanumeric => Segment::alphanumeric(
                core::str::from_utf8(&data[start..end]).expect("alphanumeric data is UTF-8"),
            ),
            Mode::Byte => Ok(Segment::bytes(&data[start..end])),
            Mode::Kanji | Mode::Eci => unreachable!(),
        })
        .collect()
}

fn update_byte(
    slot: &mut Option<ByteStep>,
    prefix: ByteStep,
    previous: usize,
    mode: Mode,
    segment_bits: usize,
) {
    let candidate = ByteStep {
        bits: prefix.bits + segment_bits,
        segments: prefix.segments + 1,
        previous,
        mode,
    };

    if slot.is_none_or(|current| {
        (candidate.bits, candidate.segments, mode_rank(candidate.mode), candidate.previous)
            < (current.bits, current.segments, mode_rank(current.mode), current.previous)
    }) {
        *slot = Some(candidate);
    }
}

#[allow(clippy::too_many_arguments)]
fn update_text(
    slot: &mut Option<TextStep>,
    prefix: TextStep,
    previous_position: usize,
    previous_interpretation: Interpretation,
    mode: Mode,
    interpretation: Interpretation,
    switched: bool,
    edge_bits: usize,
) {
    let candidate = TextStep {
        bits: prefix.bits + edge_bits,
        switches: prefix.switches + usize::from(switched),
        segments: prefix.segments + 1 + usize::from(switched),
        previous_position,
        previous_interpretation,
        mode,
        interpretation,
        switched,
    };

    if slot.is_none_or(|current| {
        (
            candidate.bits,
            candidate.switches,
            candidate.segments,
            mode_rank(candidate.mode),
            candidate.previous_position,
        ) < (
            current.bits,
            current.switches,
            current.segments,
            mode_rank(current.mode),
            current.previous_position,
        )
    }) {
        *slot = Some(candidate);
    }
}

#[inline]
const fn max_count(mode: Mode, profile: Profile) -> usize {
    (1usize << profile.cci_bits(mode)) - 1
}

#[inline]
const fn numeric_bits(count: usize) -> usize {
    count / 3 * 10
        + match count % 3 {
            1 => 4,
            2 => 7,
            _ => 0,
        }
}

#[inline]
const fn alphanumeric_bits(count: usize) -> usize {
    count / 2 * 11 + count % 2 * 6
}

#[cfg(all(test, feature = "qr"))]
#[path = "optimizer_tests.rs"]
mod tests;