exatok 0.1.1

Exact GPU-resident BPE tokenizer whose token ids match tiktoken byte for byte
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
//! Pretokenization patterns. OWNER: Pretok.
//!
//! Owns the `gpt2` / `cl100k_base` / `o200k_base` split patterns and the
//! analysis of their DFA-expressibility. Published GPU work either deleted
//! this stage, losing exactness, or left it on the host; this module is the
//! exact host implementation plus the spec the GPU program targets.
//!
//! Why this stage matters: BlockBPE measured regex pretokenization at up to
//! 75% of CPU tokenizer runtime and dropped it, which is exactly why its ids
//! stop matching a CPU tokenizer. See `docs/pretokenization-dfa.md` for the
//! byte-level DFA specification a GPU program targets, including which vyre
//! primitive to build it with.
//!
//! # Output shape
//!
//! Splits are reported as half-open byte [`Span`]s over the input, never as
//! owned strings, so the host path and a device program consume one boundary
//! representation. The spans returned for an input are contiguous and gapless:
//! the first starts at 0, the last ends at `input.len()`, and each span begins
//! where the previous one ended. Every input byte therefore belongs to exactly
//! one pretoken, which is what makes [`segment_starts`] lossless.
//!
//! For these three tokenizers the initial BPE sequence is one token per byte,
//! so a pretoken's byte range is also its token-index range at pass 0.
//!
//! # Exactness
//!
//! The reference is tiktoken, which applies these patterns with the Rust
//! `regex` crate through `fancy-regex`. Three properties of that engine are
//! load-bearing and were confirmed against the real encoder rather than
//! assumed:
//!
//! * Unicode tables are version 16.0.0. See `unicode_class`.
//! * `\s` is `\p{White_Space}`, not the ASCII subset.
//! * `(?i:)` applies Unicode *simple case folding*, so U+017F LATIN SMALL
//!   LETTER LONG S matches `s` in the contraction alternatives. It is the only
//!   non-ASCII member of any fold class these patterns use.
//!
//! Matching is leftmost-first alternation with backtracking, not
//! leftmost-longest. Alternative order is part of the specification: reordering
//! `\s*[\r\n]` and `\s+(?!\S)` in the cl100k pattern changes where a newline
//! run splits, and therefore changes token ids.
//!
//! # Invalid UTF-8
//!
//! tiktoken cannot be called with malformed UTF-8 (its entry point takes
//! `str`), so there is no reference behavior to match and no divergence to
//! report. This module accepts arbitrary bytes and assigns each byte that is
//! not part of a well-formed UTF-8 sequence to no Unicode class at all, which
//! places it in the `[^\s\p{L}\p{N}]` alternative alongside punctuation. The
//! unit of recovery is one byte, matching what a byte-level DFA on a device
//! does naturally, so host and device agree without either side needing a
//! notion of "one replacement character per malformed sequence".

mod unicode_class;

use crate::ExatokError;
use unicode_class::{L, LL, LM_LO, LU_LT, M, N, WS, ascii_class, class_of};

/// `[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]`, o200k's leading letter class.
const O200K_LEADING: u8 = LU_LT | LM_LO | M;

/// `[\p{Ll}\p{Lm}\p{Lo}\p{M}]`, o200k's trailing letter class.
const O200K_TRAILING: u8 = LL | LM_LO | M;

/// Which reference split pattern to apply.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SplitPattern {
    /// `gpt2`, shared with `r50k_base`, `p50k_base`, and `p50k_edit`.
    Gpt2,
    /// `cl100k_base`.
    Cl100kBase,
    /// `o200k_base`, shared with `o200k_harmony`.
    O200kBase,
}

impl SplitPattern {
    /// Every pattern, for exhaustive test sweeps.
    pub const ALL: [Self; 3] = [Self::Gpt2, Self::Cl100kBase, Self::O200kBase];

    /// Encoding name this pattern belongs to.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Gpt2 => "gpt2",
            Self::Cl100kBase => "cl100k_base",
            Self::O200kBase => "o200k_base",
        }
    }

    /// The reference `pat_str`, verbatim from `tiktoken_ext.openai_public`.
    ///
    /// Reproduced so the implementation can be read against its specification
    /// and so a divergence report can quote the exact source expression. These
    /// are the possessive-quantifier forms tiktoken actually ships, not the
    /// canonical forms usually published in prose.
    #[must_use]
    pub const fn pattern(self) -> &'static str {
        match self {
            Self::Gpt2 => {
                r"'(?:[sdmt]|ll|ve|re)| ?\p{L}++| ?\p{N}++| ?[^\s\p{L}\p{N}]++|\s++$|\s+(?!\S)|\s"
            }
            Self::Cl100kBase => {
                r"'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}++|\p{N}{1,3}+| ?[^\s\p{L}\p{N}]++[\r\n]*+|\s++$|\s*[\r\n]|\s+(?!\S)|\s"
            }
            Self::O200kBase => {
                concat!(
                    r"[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?",
                    r"|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?",
                    r"|\p{N}{1,3}",
                    r"| ?[^\s\p{L}\p{N}]+[\r\n/]*",
                    r"|\s*[\r\n]+",
                    r"|\s+(?!\S)",
                    r"|\s+",
                )
            }
        }
    }

    /// Longest digit run this pattern keeps in one pretoken.
    ///
    /// `gpt2` is unbounded (` ?\p{N}++`), while `cl100k_base` and
    /// `o200k_base` both cap at three (`\p{N}{1,3}`). The cap is why a long
    /// number splits into three-digit groups under the newer encodings.
    #[must_use]
    pub const fn digit_run_cap(self) -> Option<usize> {
        match self {
            Self::Gpt2 => None,
            Self::Cl100kBase | Self::O200kBase => Some(3),
        }
    }
}

/// Unicode version the split patterns are resolved against.
///
/// Pinned to whatever the reference tokenizer uses, because general-category
/// membership decides split points and therefore token ids.
#[must_use]
pub const fn unicode_version() -> &'static str {
    unicode_class::UNICODE_VERSION
}

/// Half-open byte range `[start, end)` of one pretoken.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Span {
    /// First byte offset, inclusive.
    pub start: usize,
    /// One past the last byte offset.
    pub end: usize,
}

impl Span {
    /// Length in bytes. Never zero for a span this module produces.
    #[must_use]
    pub const fn len(self) -> usize {
        self.end - self.start
    }

    /// Always false for a span this module produces; present so `len` does not
    /// trip the usual clippy pairing lint.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.start == self.end
    }

    /// The bytes this span covers, or `None` if it does not fit `input`.
    #[must_use]
    pub fn bytes<'input>(self, input: &'input [u8]) -> Option<&'input [u8]> {
        input.get(self.start..self.end)
    }
}

/// Iterator over the pretoken spans of `input`. Allocation-free.
#[derive(Debug, Clone)]
pub struct Pretokens<'input> {
    cursor: Cursor<'input>,
    pattern: SplitPattern,
    at: usize,
}

impl Iterator for Pretokens<'_> {
    type Item = Span;

    fn next(&mut self) -> Option<Span> {
        if self.at >= self.cursor.input.len() {
            return None;
        }
        let start = self.at;
        let end = match self.pattern {
            SplitPattern::Gpt2 => self.cursor.gpt2_end(start),
            SplitPattern::Cl100kBase => self.cursor.cl100k_end(start),
            SplitPattern::O200kBase => self.cursor.o200k_end(start),
        };
        self.at = end;
        Some(Span { start, end })
    }
}

/// Split `input` into pretoken spans, lazily.
#[must_use]
pub const fn pretokens(pattern: SplitPattern, input: &[u8]) -> Pretokens<'_> {
    Pretokens {
        cursor: Cursor { input },
        pattern,
        at: 0,
    }
}

/// Append the pretoken spans of `input` to `out`.
///
/// Takes the destination so a caller splitting many inputs reuses one buffer
/// instead of allocating per call.
pub fn pretokenize(pattern: SplitPattern, input: &[u8], out: &mut Vec<Span>) {
    out.extend(pretokens(pattern, input));
}

/// Collect the pretoken spans of `input`.
#[must_use]
pub fn spans(pattern: SplitPattern, input: &[u8]) -> Vec<Span> {
    pretokens(pattern, input).collect()
}

/// Append pretoken start offsets to `out`, followed by a sentinel equal to
/// `input.len()`.
///
/// This is the device-facing form of the same boundaries: `out` gains
/// `num_pretokens + 1` entries, so segment `i` spans `out[i]..out[i + 1]` and a
/// kernel needs no search to bound a segment. Because the initial BPE sequence
/// is one token per byte, these are equally byte offsets and pass-0 token
/// indices.
///
/// # Errors
///
/// [`ExatokError::Backend`] when `input` is longer than [`u32::MAX`], which
/// u32 segment offsets cannot address. The input is rejected rather than
/// truncated, since a truncated boundary table would silently corrupt ids.
pub fn segment_starts(
    pattern: SplitPattern,
    input: &[u8],
    out: &mut Vec<u32>,
) -> Result<(), ExatokError> {
    let total = checked_total(input.len())?;
    for span in pretokens(pattern, input) {
        // `start` is bounded by `input.len()`, which the check above narrowed.
        out.push(span.start as u32);
    }
    out.push(total);
    Ok(())
}

/// Rejects a length that u32 segment offsets cannot address, split out of
/// [`segment_starts`] so the boundary is testable without allocating 4 GiB.
fn checked_total(len: usize) -> Result<u32, ExatokError> {
    u32::try_from(len).map_err(|_| {
        ExatokError::Backend(format!(
            "input is {} bytes, past the u32 addressing limit of {} for a device \
             segment-start buffer. Fix: shard the input below 4 GiB per dispatch.",
            len,
            u32::MAX
        ))
    })
}

/// One decoded scalar, or one byte that is not part of a well-formed UTF-8
/// sequence. `len == 0` means the cursor is at or past the end of input.
#[derive(Debug, Clone, Copy)]
struct Unit {
    len: usize,
    class: u8,
}

/// Past the end of input.
const END: Unit = Unit { len: 0, class: 0 };

/// A byte that is not part of a well-formed UTF-8 sequence. Class zero puts it
/// in `[^\s\p{L}\p{N}]`; see the module docs on invalid UTF-8.
const MALFORMED: Unit = Unit { len: 1, class: 0 };

/// True when `unit` exists and its class intersects `bits`.
const fn is(unit: Unit, bits: u8) -> bool {
    unit.len != 0 && unit.class & bits != 0
}

/// True when `unit` exists and its class avoids every bit of `bits`.
const fn is_not(unit: Unit, bits: u8) -> bool {
    unit.len != 0 && unit.class & bits == 0
}

/// Everything the whitespace alternatives need, from one walk of the run.
///
/// Each pattern ends with three or four whitespace alternatives, and each used
/// to walk the same run itself: `\s++$`, `\s*[\r\n]`, `\s+(?!\S)` and the bare
/// `\s` are four different questions about one run of units. Asking them off a
/// single walk is what removes three of the four.
#[derive(Debug, Clone, Copy)]
struct WhitespaceRun {
    /// One past the run's last byte: greedy `\s+`.
    end: usize,
    /// Start of the run's LAST unit, which is where `\s+(?!\S)` gives back to.
    /// Equal to the run's start when the run is one unit long.
    last: usize,
    /// One past the last `\r` or `\n` inside the run, if it holds one: the end
    /// of `\s*[\r\n]`.
    through_break: Option<usize>,
}

/// Byte-oriented scanner over one input.
#[derive(Debug, Clone)]
struct Cursor<'input> {
    input: &'input [u8],
}

impl Cursor<'_> {
    /// Decode the unit starting at `at`.
    ///
    /// Deliberately two functions. This one is small enough to inline at every
    /// call site, which is what makes a run over ASCII text one table load per
    /// byte; the multibyte decoder behind it is a loop and a nine-arm match,
    /// and inlining that into eleven call sites is what previously left a
    /// non-inlinable `unit` calling a non-inlinable `class_of` once per
    /// character of English prose.
    #[inline]
    fn unit(&self, at: usize) -> Unit {
        match self.input.get(at) {
            None => END,
            Some(&lead) if lead < 0x80 => Unit { len: 1, class: ascii_class(lead) },
            Some(_) => self.multibyte_unit(at),
        }
    }

    /// Decode the non-ASCII unit starting at `at`, which must be in bounds.
    ///
    /// Strict UTF-8: overlong forms, surrogates, and scalars past U+10FFFF are
    /// all rejected, and a rejected lead or continuation byte yields
    /// [`MALFORMED`] so the scan advances exactly one byte.
    ///
    /// `inline(never)` rather than left to the inliner: the point of the split
    /// is that [`Cursor::unit`]'s caller sees a few instructions, and LLVM is
    /// entitled to undo that by folding this body back in.
    #[inline(never)]
    fn multibyte_unit(&self, at: usize) -> Unit {
        let Some(rest) = self.input.get(at..) else {
            return END;
        };
        let Some(&lead) = rest.first() else {
            return END;
        };
        // Well-formed UTF-8 byte sequences, Unicode table 3-7. The bounds on
        // the FIRST continuation byte are what exclude overlongs (0xE0, 0xF0),
        // surrogates (0xED), and scalars above U+10FFFF (0xF4).
        let (len, low, high, mut scalar) = match lead {
            0xC2..=0xDF => (2, 0x80, 0xBF, u32::from(lead & 0x1F)),
            0xE0 => (3, 0xA0, 0xBF, u32::from(lead & 0x0F)),
            0xE1..=0xEC => (3, 0x80, 0xBF, u32::from(lead & 0x0F)),
            0xED => (3, 0x80, 0x9F, u32::from(lead & 0x0F)),
            0xEE..=0xEF => (3, 0x80, 0xBF, u32::from(lead & 0x0F)),
            0xF0 => (4, 0x90, 0xBF, u32::from(lead & 0x07)),
            0xF1..=0xF3 => (4, 0x80, 0xBF, u32::from(lead & 0x07)),
            0xF4 => (4, 0x80, 0x8F, u32::from(lead & 0x07)),
            _ => return MALFORMED,
        };
        // One length check for the whole sequence, so the continuation loop
        // below indexes a slice the compiler already knows is long enough.
        let Some(sequence) = rest.get(..len) else {
            return MALFORMED;
        };
        if sequence[1] < low || sequence[1] > high {
            return MALFORMED;
        }
        scalar = (scalar << 6) | u32::from(sequence[1] & 0x3F);
        for &byte in &sequence[2..] {
            // Equivalent to `byte < 0x80 || byte > 0xBF`, which is the
            // continuation range every byte after the first one takes.
            if byte & 0xC0 != 0x80 {
                return MALFORMED;
            }
            scalar = (scalar << 6) | u32::from(byte & 0x3F);
        }
        Unit {
            len,
            class: class_of(scalar),
        }
    }

    /// End of the maximal run of units whose class intersects `bits`.
    fn run_end(&self, at: usize, bits: u8) -> usize {
        let mut pos = at;
        loop {
            let unit = self.unit(pos);
            if !is(unit, bits) {
                return pos;
            }
            pos += unit.len;
        }
    }

    /// End of the maximal run of `[^\s\p{L}\p{N}]` units.
    fn other_run_end(&self, at: usize) -> usize {
        let mut pos = at;
        loop {
            let unit = self.unit(pos);
            if !is_not(unit, WS | L | N) {
                return pos;
            }
            pos += unit.len;
        }
    }

    /// End of the maximal run of literal bytes drawn from `set`.
    fn byte_run_end(&self, at: usize, set: &[u8]) -> usize {
        let mut pos = at;
        while self.input.get(pos).is_some_and(|byte| set.contains(byte)) {
            pos += 1;
        }
        pos
    }

    /// Bytes matched by a `(?i:)` occurrence of the ASCII lowercase `letter`.
    ///
    /// `fold` selects Unicode simple case folding, which the cl100k and o200k
    /// contraction groups request and the gpt2 one does not. U+017F is the
    /// only non-ASCII codepoint in any fold class reachable from the letters
    /// these patterns use, and it folds to `s`.
    fn letter_len(&self, at: usize, letter: u8, fold: bool) -> Option<usize> {
        match self.input.get(at) {
            Some(&byte) if byte == letter => Some(1),
            Some(&byte) if fold && byte | 0x20 == letter => Some(1),
            Some(&0xC5) if fold && letter == b's' && self.input.get(at + 1) == Some(&0xBF) => {
                Some(2)
            }
            _ => None,
        }
    }

    /// End of a contraction starting with the apostrophe at `at`.
    ///
    /// Covers gpt2's `'(?:[sdmt]|ll|ve|re)`, cl100k's
    /// `'(?i:[sdmt]|ll|ve|re)`, and o200k's `(?i:'s|'t|'re|'ve|'m|'ll|'d)`.
    /// The three spell the same language: an apostrophe followed by one of
    /// `s`, `d`, `m`, `t` or one of `ll`, `ve`, `re`.
    ///
    /// The apostrophe test is inline and the alternatives are not: at a
    /// pretoken start this fails on its first byte comparison almost every
    /// time, and paying a call to learn that cost more than the test does.
    #[inline]
    fn contraction_end(&self, at: usize, fold: bool) -> Option<usize> {
        if self.input.get(at) != Some(&b'\'') {
            return None;
        }
        self.contraction_tail(at, fold)
    }

    /// The contraction alternatives, given an apostrophe already seen at `at`.
    fn contraction_tail(&self, at: usize, fold: bool) -> Option<usize> {
        for letter in [b's', b'd', b'm', b't'] {
            if let Some(len) = self.letter_len(at + 1, letter, fold) {
                return Some(at + 1 + len);
            }
        }
        for [first, second] in [[b'l', b'l'], [b'v', b'e'], [b'r', b'e']] {
            if let Some(head) = self.letter_len(at + 1, first, fold) {
                if let Some(tail) = self.letter_len(at + 1 + head, second, fold) {
                    return Some(at + 1 + head + tail);
                }
            }
        }
        None
    }

    /// ` ?[^\s\p{L}\p{N}]+` followed by a run of `tail` bytes.
    ///
    /// `tail` is empty for gpt2, `\r\n` for cl100k, and `\r\n/` for o200k.
    ///
    /// `head` is the decoded unit at `at` and `after` the one at
    /// `at + head.len`. The optional space is a literal ` `, which is a
    /// one-byte unit, so when it is taken `after` is exactly the unit the run
    /// must start at and neither position is decoded twice.
    fn punctuation_end(&self, at: usize, head: Unit, after: Unit, tail: &[u8]) -> Option<usize> {
        let (start, first) =
            if self.input.get(at) == Some(&b' ') { (at + 1, after) } else { (at, head) };
        if !is_not(first, WS | L | N) {
            return None;
        }
        Some(self.byte_run_end(self.other_run_end(start + first.len), tail))
    }

    /// Walk the whitespace run starting at `at`, whose first unit is `head`.
    ///
    /// `second` is the unit at `at + head.len` when a caller has already
    /// decoded it, so the run's second unit is not decoded twice; passing
    /// `None` simply decodes it here.
    fn whitespace_run(&self, at: usize, head: Unit, second: Option<Unit>) -> WhitespaceRun {
        let mut pos = at;
        let mut unit = head;
        let mut second = second;
        let mut last = at;
        let mut through_break = None;
        while is(unit, WS) {
            if matches!(self.input.get(pos), Some(&b'\r' | &b'\n')) {
                through_break = Some(pos + 1);
            }
            last = pos;
            pos += unit.len;
            unit = second.take().unwrap_or_else(|| self.unit(pos));
        }
        WhitespaceRun { end: pos, last, through_break }
    }

    /// `\s+(?!\S)`, then the bare trailing `\s`, off an already-walked run.
    ///
    /// The lookahead is bounded, so greedy backtracking has only two outcomes.
    /// If the run reaches end of input the lookahead holds and the whole run
    /// matches. Otherwise the unit after the run is not whitespace, hence is
    /// `\S`, so the run gives back exactly one unit; that puts a whitespace
    /// unit next and satisfies the lookahead. A one-unit run cannot give
    /// anything back and fails outright, which is what leaves the final single
    /// `\s` alternative something to do, and for a one-unit run that single
    /// `\s` ends exactly where the run does.
    const fn ws_giveback_or_one(run: WhitespaceRun, at: usize) -> usize {
        if run.last == at { run.end } else { run.last }
    }

    /// `'(?:[sdmt]|ll|ve|re)| ?\p{L}++| ?\p{N}++| ?[^\s\p{L}\p{N}]++|\s++$|\s+(?!\S)|\s`
    ///
    /// Total: every unit is whitespace, `\p{L}`, `\p{N}`, or none of the
    /// three, and the four middle-to-last alternatives cover those four cases,
    /// so the returned end is always past `at`.
    ///
    /// Dispatched on the class of the unit at `at`, decoded once. That is not
    /// an optimization bolted onto the alternation, it IS the alternation: the
    /// three `<class>` runs are mutually exclusive at a given position, and the
    /// only alternative that can reach past a unit it does not itself accept is
    /// the literal ` ` of the three optional leads. So a non-whitespace head
    /// settles in one step, and a whitespace head is exactly the case where a
    /// second unit has to be consulted.
    fn gpt2_end(&self, at: usize) -> usize {
        let head = self.unit(at);
        if is(head, L) {
            // `'` is not a letter and ` ?` takes only a space, so alternative 2
            // is the first that can match, and its run is nonempty here.
            return self.run_end(at + head.len, L);
        }
        if is(head, N) {
            return self.run_end(at + head.len, N);
        }
        if is_not(head, WS) {
            // Class zero: `[^\s\p{L}\p{N}]` accepts the head, so alternative 4
            // is guaranteed and the whitespace alternatives are unreachable.
            // Only the contraction can win ahead of it.
            return self
                .contraction_end(at, false)
                .unwrap_or_else(|| self.other_run_end(at + head.len));
        }
        // Whitespace head. Alternatives 2 to 4 can still match, but only by
        // spending the head on their optional space, which a literal ` `
        // satisfies and no other whitespace does. The space never needs to be
        // given back: all three classes exclude whitespace, so a run that fails
        // after taking it also fails without it.
        let mut after = None;
        if self.input.get(at) == Some(&b' ') {
            let next = self.unit(at + 1);
            after = Some(next);
            if is(next, L) {
                return self.run_end(at + 1 + next.len, L);
            }
            if is(next, N) {
                return self.run_end(at + 1 + next.len, N);
            }
            if is_not(next, WS) {
                return self.other_run_end(at + 1 + next.len);
            }
        }
        let run = self.whitespace_run(at, head, after);
        // `\s++$`. Possessive, so it matches only when the whole whitespace run
        // reaches the end of input. That is also why the host and the reference
        // agree on `$` despite Rust anchoring it at end-of-haystack and other
        // engines also anchoring before a final newline: no backtracking means
        // the only position `$` is ever tested at is the end of the run.
        if run.end == self.input.len() {
            return run.end;
        }
        Self::ws_giveback_or_one(run, at)
    }

    /// `'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}++|\p{N}{1,3}+| ?[^\s\p{L}\p{N}]++[\r\n]*+|\s++$|\s*[\r\n]|\s+(?!\S)|\s`
    ///
    /// Dispatched on the head's class for the same reason as [`Self::gpt2_end`],
    /// with one difference that matters: this pattern's optional lead is
    /// `[^\r\n\p{L}\p{N}]?+` rather than ` ?`, so it accepts ANY unit that is
    /// neither a letter, a digit, nor a literal `\r` or `\n`. That is a wider
    /// class than the ` ?` of the punctuation alternative, and the two diverge
    /// on a tab or U+00A0, so they are not folded together.
    fn cl100k_end(&self, at: usize) -> usize {
        let head = self.unit(at);
        if is(head, L) {
            // The optional lead excludes `\p{L}`, so it cannot take a letter,
            // and `\p{L}++` starts here and is nonempty. `'` is not a letter.
            return self.run_end(at + head.len, L);
        }
        if is(head, N) {
            // The lead excludes `\p{N}` too, so alternative 2's run is empty
            // and `\p{N}{1,3}+` is the first that matches.
            return self.run_end_capped(at, head, 3);
        }
        // Whatever remains is whitespace or class zero, and both are accepted
        // by the optional lead unless the byte is a literal `\r` or `\n`.
        if matches!(self.input.get(at), Some(&b'\r' | &b'\n')) {
            // A lone `\r` or `\n` reaches the whitespace alternatives directly:
            // the lead rejects it, so alternative 2's run starts on it and is
            // empty, and it is neither `\p{N}` nor `[^\s\p{L}\p{N}]`.
            let run = self.whitespace_run(at, head, None);
            if run.end == self.input.len() {
                return run.end;
            }
            if let Some(end) = run.through_break {
                return end;
            }
            return Self::ws_giveback_or_one(run, at);
        }
        let after = self.unit(at + head.len);
        if is_not(head, WS) {
            // Class zero. Alternative 4 always matches from here, since
            // `[^\s\p{L}\p{N}]` accepts the head and the head is not a space,
            // so the whitespace alternatives are unreachable.
            if let Some(end) = self.contraction_end(at, true) {
                return end;
            }
            if is(after, L) {
                return self.run_end(at + head.len + after.len, L);
            }
            return self.byte_run_end(self.other_run_end(at + head.len), b"\r\n");
        }
        // Whitespace head that is not a line break. Alternative 2 spends it on
        // the lead whatever whitespace it is; alternative 4 spends it only if
        // it is a literal space, and a space is one byte, so `after` is the
        // unit both of them continue from.
        if is(after, L) {
            return self.run_end(at + head.len + after.len, L);
        }
        if let Some(end) = self.punctuation_end(at, head, after, b"\r\n") {
            return end;
        }
        let run = self.whitespace_run(at, head, Some(after));
        if run.end == self.input.len() {
            return run.end;
        }
        if let Some(end) = run.through_break {
            return end;
        }
        Self::ws_giveback_or_one(run, at)
    }

    /// `\p{N}{1,3}` starting at an `at` already known to hold a digit.
    fn run_end_capped(&self, at: usize, head: Unit, cap: usize) -> usize {
        let mut pos = at + head.len;
        let mut taken = 1;
        while taken < cap {
            let unit = self.unit(pos);
            if !is(unit, N) {
                break;
            }
            pos += unit.len;
            taken += 1;
        }
        pos
    }

    /// o200k branch 1 at a settled lead offset, `[A]*[B]+(?i:CONTR)?`, where
    /// `A` is [`O200K_LEADING`] and `B` is [`O200K_TRAILING`].
    ///
    /// `first` is the already-decoded unit at `start`.
    ///
    /// `[B]+` takes its maximal run and the optional contraction is tried once
    /// at the end: because nothing follows the group, the longest `[B]+` always
    /// succeeds and never has to be given back.
    fn o200k_lower_tail(&self, start: usize, first: Unit) -> Option<usize> {
        // Walk `[A]*` and remember the furthest position that can begin
        // `[B]+`. Greedy backtracking gives back `[A]` units one at a time
        // and stops at the first that works, which is exactly that
        // furthest position.
        let mut pos = start;
        let mut unit = first;
        let mut split = None;
        loop {
            if is(unit, O200K_TRAILING) {
                split = Some(pos);
            }
            if !is(unit, O200K_LEADING) {
                break;
            }
            pos += unit.len;
            unit = self.unit(pos);
        }
        let split = split?;
        // When the `[A]*` walk stopped on the very unit that set `split`, that
        // unit is already known to be `[B]`, so the `[B]+` run continues past
        // it rather than decoding it a second time. This is the common case:
        // a lowercase word takes the walk's break on its own first letter.
        let run_from =
            if split == pos { pos + unit.len } else { split };
        let end = self.run_end(run_from, O200K_TRAILING);
        Some(self.contraction_end(end, true).unwrap_or(end))
    }

    /// o200k branch 2 at a settled lead offset, `[A]+[B]*(?i:CONTR)?`.
    ///
    /// `[B]*` and the contraction are both optional, so the maximal `[A]+`
    /// always succeeds and no backtracking into it is needed.
    fn o200k_upper_tail(&self, start: usize, first: Unit) -> Option<usize> {
        if !is(first, O200K_LEADING) {
            return None;
        }
        let leading_end = self.run_end(start + first.len, O200K_LEADING);
        let end = self.run_end(leading_end, O200K_TRAILING);
        Some(self.contraction_end(end, true).unwrap_or(end))
    }

    /// The o200k pattern; see [`SplitPattern::pattern`].
    ///
    /// The optional `[^\r\n\p{L}\p{N}]?` lead of branches 1 and 2 is NOT
    /// possessive, and that is observable: `\p{M}` is in neither `\p{L}` nor
    /// `\p{N}`, so a leading combining mark is accepted by the optional class
    /// yet is also the only thing that could satisfy `[B]+`. On input that is a
    /// lone combining mark the greedy first attempt fails and the retry without
    /// the lead is what matches. So each branch is tried twice when the lead is
    /// available, in the order backtracking would take: with, then without.
    ///
    /// The lead is decided once for both branches and for the punctuation
    /// alternative's ` ?`, so `at` and the unit after it are each decoded once
    /// for the whole pattern.
    fn o200k_end(&self, at: usize) -> usize {
        let head = self.unit(at);
        let led =
            is_not(head, L | N) && !matches!(self.input.get(at), Some(&b'\r' | &b'\n'));
        // `after` is consulted only where the lead or the ` ?` can be spent,
        // and both require exactly `led`, so `END` here is never read: it fails
        // every class test rather than standing in for a real unit.
        let after = if led { self.unit(at + head.len) } else { END };
        if led {
            if let Some(end) = self.o200k_lower_tail(at + head.len, after) {
                return end;
            }
        }
        if let Some(end) = self.o200k_lower_tail(at, head) {
            return end;
        }
        if led {
            if let Some(end) = self.o200k_upper_tail(at + head.len, after) {
                return end;
            }
        }
        if let Some(end) = self.o200k_upper_tail(at, head) {
            return end;
        }
        if is(head, N) {
            return self.run_end_capped(at, head, 3);
        }
        if let Some(end) = self.punctuation_end(at, head, after, b"\r\n/") {
            return end;
        }
        // `\s*[\r\n]+`, `\s+(?!\S)`, then `\s+`. This pattern has no `\s++$`
        // alternative, and the line-break alternative comes FIRST rather than
        // second; both differences move split points, so the order here is the
        // pattern's and not the other two patterns'.
        let run = self.whitespace_run(at, head, if led { Some(after) } else { None });
        if let Some(end) = run.through_break {
            return end;
        }
        if run.end == self.input.len() {
            return run.end;
        }
        // The trailing alternative is `\s+`, not the single `\s` the other two
        // patterns end with. It is only reachable when the run is one unit
        // long, since a longer run is taken by `\s+(?!\S)` above, so the two
        // spell the same thing and `run.end` is both.
        Self::ws_giveback_or_one(run, at)
    }
}

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

    use super::*;

    /// Locks the strict UTF-8 decoder to the well-formed-sequence table.
    ///
    /// The decoder decides how many bytes one unit covers, so accepting an
    /// overlong, a surrogate, or an out-of-range scalar would merge bytes that
    /// the reference keeps apart and shift every later span. Regression here
    /// silently changes pretoken boundaries on adversarial input.
    #[test]
    fn decoder_rejects_overlongs_surrogates_and_out_of_range() {
        let cursor = Cursor { input: b"" };
        for (bytes, want_len, what) in [
            (&[0x41][..], 1, "ascii"),
            (&[0xC3, 0xA9][..], 2, "U+00E9"),
            (&[0xE2, 0x82, 0xAC][..], 3, "U+20AC"),
            (&[0xF0, 0x9F, 0x98, 0x80][..], 4, "U+1F600"),
            (&[0xC0, 0xAF][..], 1, "overlong slash"),
            (&[0xC1, 0xBF][..], 1, "overlong 0x7F"),
            (&[0xE0, 0x80, 0xAF][..], 1, "overlong 3-byte"),
            (&[0xF0, 0x80, 0x80, 0xAF][..], 1, "overlong 4-byte"),
            (&[0xED, 0xA0, 0x80][..], 1, "surrogate U+D800"),
            (&[0xED, 0xBF, 0xBF][..], 1, "surrogate U+DFFF"),
            (&[0xF4, 0x90, 0x80, 0x80][..], 1, "above U+10FFFF"),
            (&[0xF5, 0x80, 0x80, 0x80][..], 1, "lead 0xF5"),
            (&[0xFF][..], 1, "lead 0xFF"),
            (&[0x80][..], 1, "bare continuation"),
            (&[0xE2, 0x82][..], 1, "truncated 3-byte"),
        ] {
            let cursor = Cursor { input: bytes };
            assert_eq!(
                cursor.unit(0).len,
                want_len,
                "{what}: unit length for {bytes:02x?}"
            );
        }
        assert_eq!(cursor.unit(0).len, 0, "end of input yields a zero-length unit");
    }

    /// Every unit falls in exactly one of whitespace, `\p{L}`, `\p{N}`, or
    /// none of them.
    ///
    /// The three matchers rely on that partition for totality: it is why the
    /// trailing alternative is only ever reached for whitespace and why every
    /// scan step advances. If the classes ever overlapped, a scan could return
    /// its own start offset and the span iterator would spin forever.
    #[test]
    fn whitespace_letter_and_number_classes_are_disjoint() {
        let mut buffer = [0u8; 4];
        for scalar in (0u32..0x11_0000).filter(|cp| !(0xD800..0xE000).contains(cp)) {
            let class = class_of(scalar);
            let hits = u32::from(class & WS != 0) + u32::from(class & L != 0) + u32::from(class & N != 0);
            assert!(
                hits <= 1,
                "U+{scalar:04X} is in {hits} of whitespace/letter/number (class {class:#b})"
            );
            // And the scan advances on it, whichever bucket it landed in.
            let Some(ch) = char::from_u32(scalar) else {
                continue;
            };
            let encoded = ch.encode_utf8(&mut buffer).as_bytes();
            let cursor = Cursor { input: encoded };
            for pattern in SplitPattern::ALL {
                let end = match pattern {
                    SplitPattern::Gpt2 => cursor.gpt2_end(0),
                    SplitPattern::Cl100kBase => cursor.cl100k_end(0),
                    SplitPattern::O200kBase => cursor.o200k_end(0),
                };
                assert_eq!(
                    end,
                    encoded.len(),
                    "U+{scalar:04X} alone must be one whole pretoken under {}",
                    pattern.name()
                );
            }
        }
    }

    /// `\p{L}` must be exactly the union of the five letter subcategories.
    ///
    /// cl100k and gpt2 branch on `\p{L}` while o200k branches on the
    /// subcategories, so the two views have to agree or the same text would
    /// split inconsistently between encodings.
    #[test]
    fn letter_bit_is_the_union_of_letter_subcategories() {
        for scalar in (0u32..0x11_0000).filter(|cp| !(0xD800..0xE000).contains(cp)) {
            let class = class_of(scalar);
            assert_eq!(
                class & L != 0,
                class & (LU_LT | LL | LM_LO) != 0,
                "U+{scalar:04X} disagrees on letterhood (class {class:#b})"
            );
            // A mark is never a letter; o200k's letter classes include marks
            // precisely because `\p{M}` sits outside `\p{L}`.
            if class & M != 0 {
                assert_eq!(class & L, 0, "U+{scalar:04X} is both a mark and a letter");
            }
        }
    }

    /// `segment_starts` rejects an input past the `u32` addressing limit instead
    /// of truncating, and names both the limit and the way out.
    ///
    /// The public entry point cannot reach this without a 4 GiB allocation, so
    /// the guard is exercised directly. A truncated segment table would address
    /// the wrong bytes and silently corrupt every id after the wrap, and a
    /// message missing the limit or the sharding fix leaves a caller guessing.
    #[test]
    fn checked_total_rejects_lengths_past_the_u32_addressing_limit() {
        assert_eq!(checked_total(0).unwrap(), 0, "an empty input addresses fine");
        assert_eq!(
            checked_total(u32::MAX as usize).unwrap(),
            u32::MAX,
            "the largest addressable length is accepted, not rejected"
        );
        match checked_total(u32::MAX as usize + 1) {
            Err(ExatokError::Backend(message)) => assert_eq!(
                message,
                "input is 4294967296 bytes, past the u32 addressing limit of \
                 4294967295 for a device segment-start buffer. Fix: shard the \
                 input below 4 GiB per dispatch."
            ),
            other => panic!("expected a Backend error, got {other:?}"),
        }
    }

    /// Every pretoken start offset, for tests that read better as offsets than
    /// as spans.
    fn ends(pattern: SplitPattern, input: &[u8]) -> Vec<(usize, usize)> {
        spans(pattern, input).into_iter().map(|s| (s.start, s.end)).collect()
    }

    /// Inputs that decide a boundary, with the exact span vector each must
    /// produce and the reason it is that vector.
    ///
    /// Exact vectors rather than counts: the failure mode this guards is a
    /// boundary MOVING, and a count survives a boundary moving by one unit as
    /// long as it moves back somewhere else. Every entry is reasoned from the
    /// pattern in the comment beside it, not read off the implementation.
    fn boundary_cases() -> Vec<(SplitPattern, Vec<u8>, Vec<(usize, usize)>, &'static str)> {
        let long_run: Vec<u8> = {
            let mut v = vec![b' '; 64];
            v.push(b'x');
            v
        };
        vec![
            // A three-byte sequence truncated by the end of input decodes as two
            // separate malformed bytes, both class zero, so they form one
            // `[^\s\p{L}\p{N}]++` run rather than joining the letter before them.
            (SplitPattern::Cl100kBase, b"a\xE6\xBC".to_vec(), vec![(0, 1), (1, 3)],
             "multi-byte sequence split across the end of input"),
            // 0xED admits only 0x80..=0x9F as its first continuation, so 0xA0
            // rejects the lead and all three bytes recover one at a time into a
            // single class-zero run; the letter after them starts a new pretoken.
            (SplitPattern::Cl100kBase, b"\xED\xA0\x80a".to_vec(), vec![(0, 3), (3, 4)],
             "lone surrogate-shaped byte sequence"),
            // CJK ideographs are `\p{Lo}`, so a run of them is one `\p{L}++`
            // pretoken, and U+3002 IDEOGRAPHIC FULL STOP is `\p{Po}`, class zero,
            // so it starts the punctuation alternative instead of joining them.
            (SplitPattern::Cl100kBase, "漢字漢。".as_bytes().to_vec(), vec![(0, 9), (9, 12)],
             "CJK run followed by CJK punctuation"),
            // `\s+(?!\S)` gives back exactly one unit of a 64-space run because a
            // letter follows it, and that returned space then leads the word.
            (SplitPattern::Cl100kBase, long_run, vec![(0, 63), (63, 65)],
             "very long whitespace run before a word"),
            // The same run with nothing after it is taken whole by `\s++$`.
            (SplitPattern::Cl100kBase, vec![b' '; 64], vec![(0, 64)],
             "very long whitespace run at end of input"),
            // o200k has no `\s++$`, so the run reaches the end through
            // `\s+(?!\S)`, which is the same place here.
            (SplitPattern::O200kBase, vec![b' '; 64], vec![(0, 64)],
             "o200k reaches the same end without a dollar alternative"),
            // `\s*[\r\n]` outranks `\s+(?!\S)` under cl100k, so the run ends just
            // past the LAST line break rather than giving back one unit.
            (SplitPattern::Cl100kBase, b"a \r\n b".to_vec(),
             vec![(0, 1), (1, 4), (4, 6)], "whitespace run through its last line break"),
            // The digit cap cuts a run into threes and the remainder ends the
            // input mid-class, which must not extend the last group.
            (SplitPattern::Cl100kBase, b"12345".to_vec(), vec![(0, 3), (3, 5)],
             "input ending mid-class inside a capped digit run"),
            // gpt2 has no cap, so the same digits are one pretoken.
            (SplitPattern::Gpt2, b"12345".to_vec(), vec![(0, 5)],
             "uncapped digit run ends at the input"),
            // cl100k's two optional leads are NOT the same class. A space is
            // taken by the punctuation alternative's ` ?`...
            (SplitPattern::Cl100kBase, b" !".to_vec(), vec![(0, 2)],
             "a space leads the punctuation alternative"),
            // ...and a tab is not, even though the WORD alternative's
            // `[^\r\n\p{L}\p{N}]?+` would have taken either. So the tab is left
            // to the whitespace alternatives and splits off alone.
            (SplitPattern::Cl100kBase, b"\t!".to_vec(), vec![(0, 1), (1, 2)],
             "a tab does not lead the punctuation alternative"),
            // The word alternative's wider lead does take the class-zero byte,
            // which is why the letters after it do not start a new pretoken.
            (SplitPattern::Cl100kBase, b"!ab".to_vec(), vec![(0, 3)],
             "class-zero lead followed by letters"),
            // o200k's optional lead is not possessive: a lone combining mark is
            // accepted by the lead yet is also the only thing that can satisfy
            // `[B]+`, so the greedy attempt fails and the retry matches.
            (SplitPattern::O200kBase, "\u{301}".as_bytes().to_vec(), vec![(0, 2)],
             "o200k retries its lead for a lone combining mark"),
            // With a letter after it the greedy attempt succeeds instead: the
            // mark is the lead and the letter is `[B]+`.
            (SplitPattern::O200kBase, "\u{301}a".as_bytes().to_vec(), vec![(0, 3)],
             "o200k spends its lead on a mark before a letter"),
        ]
    }

    /// Each boundary case splits to its exact span vector.
    ///
    /// These are the cases the class dispatch in the three `*_end` functions
    /// has to get right: one entry per dispatch arm and per fall-through
    /// between arms, because an arm that skips an alternative it should have
    /// tried moves a boundary and therefore changes token ids.
    #[test]
    fn boundary_cases_split_to_exact_span_vectors() {
        for (pattern, input, want, why) in boundary_cases() {
            assert_eq!(
                ends(pattern, &input),
                want,
                "{}: {why} for {input:02x?}",
                pattern.name()
            );
        }
    }

    /// The spans tile every boundary case, under every pattern.
    ///
    /// Run over all three patterns rather than the one each case was written
    /// for: tiling is not pattern-specific, and a gap would silently drop bytes
    /// that both the device path and the host reference would then agree on.
    #[test]
    fn spans_tile_every_boundary_case_under_every_pattern() {
        let mut inputs: Vec<Vec<u8>> = boundary_cases().into_iter().map(|c| c.1).collect();
        // Long uniform runs of each class, which is where a single walk of a run
        // could plausibly lose or double-count a unit.
        inputs.push(vec![b'\n'; 300]);
        inputs.push(vec![b'\t'; 300]);
        inputs.push("\u{a0}".repeat(300).into_bytes());
        inputs.push("漢".repeat(300).into_bytes());
        inputs.push(b"\r\n".repeat(150).to_vec());
        inputs.push((0u8..=255).collect());
        for input in &inputs {
            for pattern in SplitPattern::ALL {
                let got = spans(pattern, input);
                let mut at = 0;
                for span in &got {
                    assert_eq!(span.start, at, "{}: gap before {span:?}", pattern.name());
                    assert!(span.end > span.start, "{}: empty {span:?}", pattern.name());
                    at = span.end;
                }
                assert_eq!(
                    at,
                    input.len(),
                    "{}: spans stop short of the input",
                    pattern.name()
                );
            }
        }
    }
}