snaptokens 0.2.2

Fast BPE tokenization from local Hugging Face tokenizer.json files
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
use std::collections::HashMap;
use std::fmt;

use daachorse::{DoubleArrayAhoCorasick, DoubleArrayAhoCorasickBuilder};
use icu_properties::{
    CodePointMapData, CodePointSetData,
    props::{Alphabetic, GeneralCategory, JoinControl},
};

use crate::{json_structs::AddedTokenConfig, normalizers::Normalizer};

/// Compiled patterns and prefilter metadata for one added-token matching phase.
struct AddedTokenMatcher {
    daac: DoubleArrayAhoCorasick<u32>,
    start_bytes: Vec<u8>,
    shared_prefix: Option<[u8; 2]>,
    max_token_len: usize,
}

impl AddedTokenMatcher {
    /// Compile owned patterns, returning `None` when this phase has no tokens.
    fn new(patterns: Vec<(String, u32)>) -> Result<Option<Self>, String> {
        if patterns.is_empty() {
            return Ok(None);
        }

        let mut start_set = [false; 256];
        let mut shared_prefix = None;
        let mut max_token_len = 0;
        for (index, (content, _)) in patterns.iter().enumerate() {
            let bytes = content.as_bytes();
            if let Some(&byte) = bytes.first() {
                start_set[byte as usize] = true;
            }
            let prefix = bytes.get(..2).map(|bytes| [bytes[0], bytes[1]]);
            if index == 0 {
                shared_prefix = prefix;
            } else if shared_prefix != prefix {
                shared_prefix = None;
            }
            max_token_len = max_token_len.max(content.len());
        }
        let start_bytes = start_set
            .iter()
            .enumerate()
            .filter(|&(_, present)| *present)
            .map(|(byte, _)| byte as u8)
            .collect();
        let daac = DoubleArrayAhoCorasickBuilder::new()
            .match_kind(daachorse::MatchKind::LeftmostLongest)
            .build_with_values(patterns.iter().map(|(content, id)| (content.as_str(), *id)))
            .map_err(|error| format!("error building added-tokens DAAC: {error}"))?;
        Ok(Some(Self {
            daac,
            start_bytes,
            shared_prefix,
            max_token_len,
        }))
    }

    /// Return whether the input contains any byte that can start a match.
    #[inline]
    fn has_candidate(&self, input: &str) -> bool {
        let bytes = input.as_bytes();
        // Every pattern starts with this pair, so its absence rules out a match.
        if let Some(prefix) = self.shared_prefix {
            return memchr::memchr_iter(prefix[0], bytes)
                .any(|index| bytes.get(index + 1) == Some(&prefix[1]));
        }
        match self.start_bytes.as_slice() {
            [first] => memchr::memchr(*first, bytes).is_some(),
            [first, second] => memchr::memchr2(*first, *second, bytes).is_some(),
            [first, second, third] => memchr::memchr3(*first, *second, *third, bytes).is_some(),
            _ => true,
        }
    }
}

/// Matching flags stored densely by token ID.
#[derive(Clone, Copy, Default)]
struct AddedTokenFlags {
    single_word: bool,
    lstrip: bool,
    rstrip: bool,
    special: bool,
}

/// A compiled set of added tokens that can be matched against input text.
///
/// The HuggingFace `tokenizer.json` format includes an `added_tokens` array of
/// literal patterns matched before or after normalization according to each
/// token's `normalized` flag. Matched spans emit their IDs directly; unmatched
/// spans continue through pre-tokenization and the model.
pub struct AddedTokens {
    /// Matchers run before and after normalization, respectively.
    non_normalized: Option<AddedTokenMatcher>,
    normalized: Option<AddedTokenMatcher>,
    /// Per-ID matching and decoding flags.
    flags: Vec<AddedTokenFlags>,
    /// Mapping from token ID to token content string.
    id_to_content: HashMap<u32, String>,
    /// Reverse mapping: token content string → token ID.
    content_to_id: HashMap<String, u32>,
}

/// A segment of the input after added-token splitting.
#[derive(Debug, PartialEq, Eq)]
pub enum Segment<'a> {
    /// A span that matched an added token. The `u32` is the token ID to emit
    /// directly.
    Token(u32),
    /// A span that did not match any added token. The `&str` should be run
    /// through the normal pipeline.
    Text(&'a str),
}

/// Public view of one added-token entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AddedTokenInfo<'a> {
    pub id: u32,
    pub content: &'a str,
    pub special: bool,
}

impl AddedTokens {
    /// Build from the `added_tokens` array in `tokenizer.json`.
    ///
    /// Returns `None` if there are no added tokens.
    pub fn from_configs(configs: &[AddedTokenConfig]) -> Result<Option<Self>, String> {
        Self::from_configs_with_normalizer(configs, None)
    }

    /// Build the raw and normalized matching phases used by the tokenizer pipeline.
    pub(crate) fn from_configs_with_normalizer(
        configs: &[AddedTokenConfig],
        normalizer: Option<&Normalizer>,
    ) -> Result<Option<Self>, String> {
        if configs.is_empty() {
            return Ok(None);
        }

        let max_id = configs.iter().map(|c| c.id).max().unwrap_or(0);
        let mut flags = vec![AddedTokenFlags::default(); (max_id + 1) as usize];
        let mut id_to_content = HashMap::with_capacity(configs.len());
        let mut content_to_id = HashMap::with_capacity(configs.len());
        let mut non_normalized_patterns = Vec::new();
        let mut normalized_patterns = Vec::new();

        for config in configs {
            flags[config.id as usize] = AddedTokenFlags {
                single_word: config.single_word,
                lstrip: config.lstrip,
                rstrip: config.rstrip,
                special: config.special,
            };
            id_to_content.insert(config.id, config.content.clone());
            content_to_id.insert(config.content.clone(), config.id);

            if config.normalized {
                // HF normalizes both the remaining input and the token pattern.
                let content = normalizer.map_or_else(
                    || config.content.clone(),
                    |normalizer| normalizer.normalize(&config.content).into_owned(),
                );
                normalized_patterns.push((content, config.id));
            } else {
                non_normalized_patterns.push((config.content.clone(), config.id));
            }
        }

        Ok(Some(Self {
            non_normalized: AddedTokenMatcher::new(non_normalized_patterns)?,
            normalized: AddedTokenMatcher::new(normalized_patterns)?,
            flags,
            id_to_content,
            content_to_id,
        }))
    }

    /// Look up the string content of an added token by ID.
    pub fn id_to_token(&self, id: u32) -> Option<&str> {
        self.id_to_content.get(&id).map(String::as_str)
    }

    /// Look up the token ID for a content string.
    pub fn token_to_id(&self, token: &str) -> Option<u32> {
        self.content_to_id.get(token).copied()
    }

    /// Check if a token ID is a special added token.
    pub fn is_special(&self, id: u32) -> bool {
        self.flags
            .get(id as usize)
            .is_some_and(|flags| flags.special)
    }

    /// Return the number of added tokens.
    pub fn len(&self) -> usize {
        self.id_to_content.len()
    }

    /// Return whether there are no added tokens.
    pub fn is_empty(&self) -> bool {
        self.id_to_content.is_empty()
    }

    /// Iterate over added-token entries.
    ///
    /// The iteration order is unspecified. Callers that need a stable order
    /// should sort by `id` themselves.
    pub fn iter(&self) -> impl Iterator<Item = AddedTokenInfo<'_>> {
        self.id_to_content
            .iter()
            .map(|(&id, content)| AddedTokenInfo {
                id,
                content: content.as_str(),
                special: self.flags[id as usize].special,
            })
    }

    /// Split `input` into segments: spans matching added tokens and spans of
    /// regular text.
    ///
    /// Added tokens are matched leftmost-longest. Non-overlapping matches are
    /// emitted as [`Segment::Token`]; the gaps between them as
    /// [`Segment::Text`].
    pub fn split<'a>(&self, input: &'a str) -> Vec<Segment<'a>> {
        let raw_segments = self.split_non_normalized(input);
        if self.normalized.is_none() {
            return raw_segments;
        }

        let mut segments = Vec::with_capacity(raw_segments.len());
        for segment in raw_segments {
            match segment {
                Segment::Token(id) => segments.push(Segment::Token(id)),
                Segment::Text(text) => segments.extend(self.split_normalized(text)),
            }
        }
        segments
    }

    /// Match tokens whose `normalized` flag is false against original input.
    pub(crate) fn split_non_normalized<'a>(&self, input: &'a str) -> Vec<Segment<'a>> {
        self.split_with(input, self.non_normalized.as_ref())
    }

    /// Match tokens whose `normalized` flag is true against normalized input.
    pub(crate) fn split_normalized<'a>(&self, input: &'a str) -> Vec<Segment<'a>> {
        self.split_with(input, self.normalized.as_ref())
    }

    /// Return whether a second, normalized matching phase is required.
    pub(crate) fn has_normalized(&self) -> bool {
        self.normalized.is_some()
    }

    /// Return whether either matching phase has a possible start position.
    pub(crate) fn has_candidate(&self, input: &str) -> bool {
        self.non_normalized
            .as_ref()
            .is_some_and(|matcher| matcher.has_candidate(input))
            || self
                .normalized
                .as_ref()
                .is_some_and(|matcher| matcher.has_candidate(input))
    }

    /// Split with one compiled matcher, or return the input unchanged if absent.
    fn split_with<'a>(
        &self,
        input: &'a str,
        matcher: Option<&AddedTokenMatcher>,
    ) -> Vec<Segment<'a>> {
        let Some(matcher) = matcher else {
            return if input.is_empty() {
                Vec::new()
            } else {
                vec![Segment::Text(input)]
            };
        };

        // When there are few distinct start bytes, use SIMD memchr to skip
        // positions that cannot start any added token. This avoids scanning
        // the full input through the Aho-Corasick automaton.
        match matcher.start_bytes.len() {
            1 => self.split_prefilter(
                input,
                matcher,
                memchr::memchr_iter(matcher.start_bytes[0], input.as_bytes()),
            ),
            2 => self.split_prefilter(
                input,
                matcher,
                memchr::memchr2_iter(
                    matcher.start_bytes[0],
                    matcher.start_bytes[1],
                    input.as_bytes(),
                ),
            ),
            3 => self.split_prefilter(
                input,
                matcher,
                memchr::memchr3_iter(
                    matcher.start_bytes[0],
                    matcher.start_bytes[1],
                    matcher.start_bytes[2],
                    input.as_bytes(),
                ),
            ),
            _ => self.split_full_scan(input, matcher),
        }
    }

    /// Prefiltered split: only check positions identified by memchr.
    fn split_prefilter<'a>(
        &self,
        input: &'a str,
        matcher: &AddedTokenMatcher,
        candidates: impl Iterator<Item = usize>,
    ) -> Vec<Segment<'a>> {
        let mut segments = Vec::new();
        let mut prev_match_end = 0;
        let mut prev_end = 0;

        for pos in candidates {
            // Match overlap is based on the raw token, before whitespace stripping.
            if pos < prev_match_end {
                continue;
            }
            // Run the DAAC on a short window starting at this position.
            let mut window_end = (pos + matcher.max_token_len).min(input.len());
            // Ensure window_end is at a UTF-8 char boundary.
            while window_end < input.len() && !input.is_char_boundary(window_end) {
                window_end += 1;
            }
            let window = &input[pos..window_end];
            if let Some(m) = matcher.daac.leftmost_find_iter(window).next()
                && m.start() == 0
            {
                let match_end = pos + m.end();
                // A rejected whole-word match still consumes this Aho-Corasick
                // candidate, matching the full iterator's non-overlap semantics.
                prev_match_end = match_end;
                if !self.is_single_word_match(input, m.value(), pos, match_end) {
                    continue;
                }
                let (start, end) = self.strip_bounds(input, m.value(), pos, match_end, prev_end);
                if start > prev_end {
                    segments.push(Segment::Text(&input[prev_end..start]));
                }
                segments.push(Segment::Token(m.value()));
                prev_end = end;
            }
        }

        if prev_end < input.len() {
            segments.push(Segment::Text(&input[prev_end..]));
        }

        segments
    }

    /// Check the Unicode word boundaries requested by an added token.
    fn is_single_word_match(&self, input: &str, id: u32, start: usize, end: usize) -> bool {
        if !self.flags[id as usize].single_word {
            return true;
        }

        let starts_at_boundary = input[..start]
            .chars()
            .next_back()
            .is_none_or(|ch| !is_word_character(ch));
        let ends_at_boundary = input[end..]
            .chars()
            .next()
            .is_none_or(|ch| !is_word_character(ch));
        starts_at_boundary && ends_at_boundary
    }

    /// Expand a match span to absorb adjacent Unicode whitespace per the
    /// token's `lstrip`/`rstrip` flags, matching HuggingFace `AddedToken`
    /// behavior. Absorbed whitespace is excluded from the surrounding text.
    ///
    /// `lstrip` extends the start left over whitespace, bounded by `floor`
    /// (the end of the previous segment) so it never reclaims already-emitted
    /// text. `rstrip` extends the end right over whitespace. When two strip
    /// tokens share a whitespace run, the left token's `rstrip` consumes it
    /// first (via the advanced `floor`), so the right token's `lstrip` finds
    /// none — mirroring HF's left-to-right resolution.
    fn strip_bounds(
        &self,
        input: &str,
        id: u32,
        mut start: usize,
        mut end: usize,
        floor: usize,
    ) -> (usize, usize) {
        let flags = self.flags[id as usize];
        if flags.lstrip {
            // HF keeps the token but clamps whitespace already consumed by the prior match.
            start = start.max(floor);
            for (rel_i, c) in input[floor..start].char_indices().rev() {
                if c.is_whitespace() {
                    start = floor + rel_i;
                } else {
                    break;
                }
            }
        }
        if flags.rstrip {
            for c in input[end..].chars() {
                if c.is_whitespace() {
                    end += c.len_utf8();
                } else {
                    break;
                }
            }
        }
        (start, end)
    }

    /// Full-scan fallback for >3 distinct start bytes.
    fn split_full_scan<'a>(&self, input: &'a str, matcher: &AddedTokenMatcher) -> Vec<Segment<'a>> {
        let mut segments = Vec::new();
        let mut prev_end = 0;

        for m in matcher.daac.leftmost_find_iter(input) {
            if !self.is_single_word_match(input, m.value(), m.start(), m.end()) {
                continue;
            }
            let (start, end) = self.strip_bounds(input, m.value(), m.start(), m.end(), prev_end);
            if start > prev_end {
                segments.push(Segment::Text(&input[prev_end..start]));
            }
            segments.push(Segment::Token(m.value()));
            prev_end = end;
        }

        if prev_end < input.len() {
            segments.push(Segment::Text(&input[prev_end..]));
        }

        segments
    }
}

/// Match the Unicode `\w` class used by Hugging Face's added-token boundaries.
fn is_word_character(ch: char) -> bool {
    if ch.is_ascii() {
        return ch.is_ascii_alphanumeric() || ch == '_';
    }
    if CodePointSetData::new::<Alphabetic>().contains(ch)
        || CodePointSetData::new::<JoinControl>().contains(ch)
    {
        return true;
    }

    matches!(
        CodePointMapData::<GeneralCategory>::new().get(ch),
        GeneralCategory::NonspacingMark
            | GeneralCategory::SpacingMark
            | GeneralCategory::EnclosingMark
            | GeneralCategory::DecimalNumber
            | GeneralCategory::ConnectorPunctuation
    )
}

impl fmt::Debug for AddedTokens {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AddedTokens")
            .field("count", &self.id_to_content.len())
            .finish()
    }
}

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

    fn make_config(id: u32, content: &str) -> AddedTokenConfig {
        AddedTokenConfig {
            id,
            content: content.to_string(),
            single_word: false,
            lstrip: false,
            rstrip: false,
            normalized: false,
            special: false,
        }
    }

    #[test]
    fn empty_configs() {
        let result = AddedTokens::from_configs(&[]).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn no_match() {
        let configs = vec![make_config(100, "<special>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("hello world");
        assert_eq!(segs, vec![Segment::Text("hello world")]);
    }

    #[test]
    fn single_match_at_start() {
        let configs = vec![make_config(100, "<s>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("<s>hello");
        assert_eq!(segs, vec![Segment::Token(100), Segment::Text("hello")]);
    }

    #[test]
    fn single_match_at_end() {
        let configs = vec![make_config(100, "</s>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("hello</s>");
        assert_eq!(segs, vec![Segment::Text("hello"), Segment::Token(100)]);
    }

    #[test]
    fn match_in_middle() {
        let configs = vec![make_config(42, "<sep>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("hello<sep>world");
        assert_eq!(
            segs,
            vec![
                Segment::Text("hello"),
                Segment::Token(42),
                Segment::Text("world"),
            ]
        );
    }

    #[test]
    fn multiple_matches() {
        let configs = vec![make_config(1, "<a>"), make_config(2, "<b>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("x<a>y<b>z");
        assert_eq!(
            segs,
            vec![
                Segment::Text("x"),
                Segment::Token(1),
                Segment::Text("y"),
                Segment::Token(2),
                Segment::Text("z"),
            ]
        );
    }

    #[test]
    fn adjacent_matches() {
        let configs = vec![make_config(1, "<a>"), make_config(2, "<b>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("<a><b>");
        assert_eq!(segs, vec![Segment::Token(1), Segment::Token(2)]);
    }

    #[test]
    fn longest_match_wins() {
        let configs = vec![make_config(1, "<file>"), make_config(2, "<filename>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("a<filename>b");
        assert_eq!(
            segs,
            vec![Segment::Text("a"), Segment::Token(2), Segment::Text("b"),]
        );
    }

    #[test]
    fn entire_input_is_added_token() {
        let configs = vec![make_config(99, "hello")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("hello");
        assert_eq!(segs, vec![Segment::Token(99)]);
    }

    #[test]
    fn empty_input() {
        let configs = vec![make_config(1, "<s>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("");
        assert!(segs.is_empty());
    }

    // ── token_to_id (content → id reverse lookup) ───────────────────────

    #[test]
    fn token_to_id_finds_added_token() {
        let configs = vec![make_config(42, "<special>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(at.token_to_id("<special>"), Some(42));
    }

    #[test]
    fn token_to_id_returns_none_for_unknown() {
        let configs = vec![make_config(1, "<known>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(at.token_to_id("<unknown>"), None);
    }

    #[test]
    fn token_to_id_and_id_to_token_are_inverses() {
        let configs = vec![
            make_config(10, "<bos>"),
            make_config(11, "<eos>"),
            make_config(12, "<pad>"),
        ];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        for cfg in &configs {
            let id = at.token_to_id(&cfg.content).unwrap();
            assert_eq!(id, cfg.id);
            assert_eq!(at.id_to_token(id), Some(cfg.content.as_str()));
        }
    }

    // ── Unicode and multi-byte token content ────────────────────────────

    #[test]
    fn unicode_token_content() {
        let configs = vec![
            make_config(1, "▁"), // U+2581  (SentencePiece metaspace)
            make_config(2, "Ġ"), // U+0120  (GPT-2 space marker)
            make_config(3, "日本語"),
        ];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(
            at.split("▁hello"),
            vec![Segment::Token(1), Segment::Text("hello")]
        );
        assert_eq!(
            at.split("Ġworld"),
            vec![Segment::Token(2), Segment::Text("world")]
        );
        assert_eq!(
            at.split("日本語text"),
            vec![Segment::Token(3), Segment::Text("text")]
        );
        assert_eq!(at.token_to_id("▁"), Some(1));
        assert_eq!(at.token_to_id("Ġ"), Some(2));
        assert_eq!(at.token_to_id("日本語"), Some(3));
    }

    #[test]
    fn emoji_token_content() {
        let configs = vec![make_config(7, "🌍")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(
            at.split("hello 🌍 world"),
            vec![
                Segment::Text("hello "),
                Segment::Token(7),
                Segment::Text(" world"),
            ]
        );
    }

    // ── is_special ──────────────────────────────────────────────────────

    #[test]
    fn is_special_only_for_marked_tokens() {
        let mut special = make_config(1, "<bos>");
        special.special = true;
        let non_special = make_config(2, "<extra>");
        let at = AddedTokens::from_configs(&[special, non_special])
            .unwrap()
            .unwrap();
        assert!(at.is_special(1));
        assert!(!at.is_special(2));
        assert!(!at.is_special(99)); // unknown id
    }

    #[test]
    fn iter_exposes_id_content_and_special_flag() {
        let mut special = make_config(1, "<bos>");
        special.special = true;
        let plain = make_config(2, "<extra>");
        let at = AddedTokens::from_configs(&[special, plain])
            .unwrap()
            .unwrap();

        let mut entries: Vec<_> = at.iter().collect();
        entries.sort_by_key(|entry| entry.id);

        assert_eq!(
            entries,
            vec![
                AddedTokenInfo {
                    id: 1,
                    content: "<bos>",
                    special: true,
                },
                AddedTokenInfo {
                    id: 2,
                    content: "<extra>",
                    special: false,
                },
            ]
        );
    }

    // ── len / is_empty ───────────────────────────────────────────────────

    #[test]
    fn len_returns_token_count() {
        let configs = vec![
            make_config(1, "<a>"),
            make_config(2, "<b>"),
            make_config(3, "<c>"),
        ];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(at.len(), 3);
        assert!(!at.is_empty());
    }

    #[test]
    fn three_tokens_with_shared_start_byte() {
        // <, <s>, <sep> all start with '<'  — exercises the memchr prefilter
        // (≤3 distinct first bytes → SIMD path).
        let configs = vec![
            make_config(1, "<"),
            make_config(2, "<s>"),
            make_config(3, "<sep>"),
        ];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        // Longest match: <sep> wins over <s> or <
        let segs = at.split("x<sep>y<s>z<");
        assert_eq!(
            segs,
            vec![
                Segment::Text("x"),
                Segment::Token(3),
                Segment::Text("y"),
                Segment::Token(2),
                Segment::Text("z"),
                Segment::Token(1),
            ]
        );
    }

    #[test]
    fn four_distinct_start_bytes_uses_full_scan() {
        // >3 distinct first bytes → full-scan path (no memchr prefilter).
        let configs = vec![
            make_config(1, "<bos>"),
            make_config(2, "[SEP]"),
            make_config(3, "{pad}"),
            make_config(4, "|mask|"),
        ];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("<bos>[SEP]{pad}|mask|");
        assert_eq!(
            segs,
            vec![
                Segment::Token(1),
                Segment::Token(2),
                Segment::Token(3),
                Segment::Token(4),
            ]
        );
    }

    #[test]
    fn token_surrounded_by_text() {
        let configs = vec![make_config(5, "<mid>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("prefix <mid> suffix");
        assert_eq!(
            segs,
            vec![
                Segment::Text("prefix "),
                Segment::Token(5),
                Segment::Text(" suffix"),
            ]
        );
    }

    #[test]
    fn repeated_same_token() {
        let configs = vec![make_config(9, "<r>")];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        let segs = at.split("<r><r><r>");
        assert_eq!(
            segs,
            vec![Segment::Token(9), Segment::Token(9), Segment::Token(9)]
        );
    }

    /// Require Unicode-aware word boundaries in both matching implementations.
    #[test]
    fn single_word_respects_ascii_and_unicode_boundaries() {
        let mut mask = make_config(1, "<mask>");
        mask.single_word = true;
        let input = "<mask>, <mask>- ◌̰<mask> A<mask> <mask>";
        let expected = vec![
            Segment::Token(1),
            Segment::Text(", "),
            Segment::Token(1),
            Segment::Text("- ◌̰<mask> A<mask> "),
            Segment::Token(1),
        ];

        let prefiltered = AddedTokens::from_configs(&[mask.clone()]).unwrap().unwrap();
        assert_eq!(prefiltered.split(input), expected);

        // Four distinct initial bytes force the full DAAC scan.
        let full_scan = AddedTokens::from_configs(&[
            mask,
            make_config(2, "[unused]"),
            make_config(3, "{unused}"),
            make_config(4, "|unused|"),
        ])
        .unwrap()
        .unwrap();
        assert_eq!(full_scan.split(input), expected);
    }

    // ── lstrip / rstrip whitespace absorption ───────────────────────────

    fn make_strip_config(id: u32, content: &str, lstrip: bool, rstrip: bool) -> AddedTokenConfig {
        AddedTokenConfig {
            id,
            content: content.to_string(),
            single_word: false,
            lstrip,
            rstrip,
            normalized: false,
            special: true,
        }
    }

    #[test]
    fn lstrip_absorbs_leading_whitespace() {
        let configs = vec![make_strip_config(1, "<s>", true, false)];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        // The spaces before <s> are absorbed into the token span; "ab" remains,
        // trailing "cd" is untouched.
        assert_eq!(
            at.split("ab   <s>cd"),
            vec![Segment::Text("ab"), Segment::Token(1), Segment::Text("cd")]
        );
    }

    #[test]
    fn rstrip_absorbs_trailing_whitespace() {
        let configs = vec![make_strip_config(1, "<s>", false, true)];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(
            at.split("ab<s>   cd"),
            vec![Segment::Text("ab"), Segment::Token(1), Segment::Text("cd")]
        );
    }

    #[test]
    fn strip_both_sides() {
        let configs = vec![make_strip_config(1, "<s>", true, true)];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(
            at.split("ab \t <s> \n cd"),
            vec![Segment::Text("ab"), Segment::Token(1), Segment::Text("cd")]
        );
    }

    #[test]
    fn no_strip_keeps_whitespace() {
        let configs = vec![make_strip_config(1, "<s>", false, false)];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(
            at.split("ab <s> cd"),
            vec![
                Segment::Text("ab "),
                Segment::Token(1),
                Segment::Text(" cd"),
            ]
        );
    }

    #[test]
    fn adjacent_strip_tokens_share_whitespace() {
        // The <|im_end|>\n<|im_start|> case from Phi-4: both tokens strip both
        // sides. The single \n between them must be absorbed exactly once and
        // produce no text token.
        let configs = vec![
            make_strip_config(1, "<|im_end|>", true, true),
            make_strip_config(2, "<|im_start|>", true, true),
        ];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(
            at.split("hi<|im_end|>\n<|im_start|>user"),
            vec![
                Segment::Text("hi"),
                Segment::Token(1),
                Segment::Token(2),
                Segment::Text("user"),
            ]
        );
    }

    #[test]
    fn lstrip_bounded_by_previous_token() {
        // A preceding token's span must not be reclaimed by the next token's
        // lstrip: there is no whitespace between the tokens here.
        let configs = vec![
            make_strip_config(1, "<a>", false, false),
            make_strip_config(2, "<b>", true, false),
        ];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(
            at.split("<a><b>"),
            vec![Segment::Token(1), Segment::Token(2)]
        );
    }

    #[test]
    fn strip_via_full_scan_path() {
        // >3 distinct start bytes forces the full-scan path; rstrip must still
        // absorb trailing whitespace there.
        let configs = vec![
            make_strip_config(1, "<bos>", false, true),
            make_config(2, "[SEP]"),
            make_config(3, "{pad}"),
            make_config(4, "|mask|"),
        ];
        let at = AddedTokens::from_configs(&configs).unwrap().unwrap();
        assert_eq!(
            at.split("<bos>   x"),
            vec![Segment::Token(1), Segment::Text("x")]
        );
    }

    /// Match HF when one token's `rstrip` overlaps the next token's `lstrip`.
    #[test]
    fn strip_overlap_matches_huggingface_in_both_paths() {
        let prefilter_configs = vec![
            make_strip_config(1, "<a>", false, true),
            make_strip_config(2, " X", true, false),
            make_config(3, "[d]"),
        ];
        let prefiltered = AddedTokens::from_configs(&prefilter_configs)
            .unwrap()
            .unwrap();

        let mut full_scan_configs = prefilter_configs;
        full_scan_configs.push(make_config(4, "{e}"));
        let full_scan = AddedTokens::from_configs(&full_scan_configs)
            .unwrap()
            .unwrap();

        let expected = vec![Segment::Token(1), Segment::Token(2)];
        assert_eq!(prefiltered.split("<a> X"), expected);
        assert_eq!(full_scan.split("<a> X"), expected);
    }
}