gigatoken 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/Cargo.lock +3016 -0
- data/Cargo.toml +135 -0
- data/LICENSE +21 -0
- data/README.md +141 -0
- data/exe/gigatoken +9 -0
- data/ext/gigatoken/Cargo.toml +24 -0
- data/ext/gigatoken/extconf.rb +19 -0
- data/ext/gigatoken/src/error.rs +20 -0
- data/ext/gigatoken/src/gvl.rs +122 -0
- data/ext/gigatoken/src/lib.rs +50 -0
- data/ext/gigatoken/src/sentencepiece.rs +205 -0
- data/ext/gigatoken/src/sources.rs +207 -0
- data/ext/gigatoken/src/tokenizer.rs +571 -0
- data/lib/gigatoken/cli/bench.rb +64 -0
- data/lib/gigatoken/cli/support.rb +132 -0
- data/lib/gigatoken/cli/validate.rb +55 -0
- data/lib/gigatoken/cli.rb +18 -0
- data/lib/gigatoken/hub.rb +242 -0
- data/lib/gigatoken/packed_result.rb +48 -0
- data/lib/gigatoken/tokenizer.rb +117 -0
- data/lib/gigatoken/version.rb +5 -0
- data/lib/gigatoken.rb +29 -0
- data/rust-toolchain.toml +8 -0
- data/src/batch.rs +1808 -0
- data/src/bindings/bridge.rs +396 -0
- data/src/bindings/hub.rs +42 -0
- data/src/bindings/matcher.rs +114 -0
- data/src/bindings/mod.rs +14 -0
- data/src/bindings/padding.rs +177 -0
- data/src/bindings/pretokenize.rs +53 -0
- data/src/bindings/sources.rs +273 -0
- data/src/bindings/train.rs +125 -0
- data/src/bpe/mod.rs +1217 -0
- data/src/bpe/pretoken_cache.rs +495 -0
- data/src/bpe/sentencepiece.rs +1485 -0
- data/src/bpe/tiktoken.rs +2555 -0
- data/src/bpe_train.rs +351 -0
- data/src/input/decompress.rs +11 -0
- data/src/input/file_source.rs +514 -0
- data/src/input/jsonl.rs +94 -0
- data/src/input/mod.rs +333 -0
- data/src/input/parquet.rs +303 -0
- data/src/lib.rs +578 -0
- data/src/load_tokenizer/hf.rs +1036 -0
- data/src/load_tokenizer/hub.rs +344 -0
- data/src/load_tokenizer/mod.rs +3 -0
- data/src/load_tokenizer/tiktoken.rs +87 -0
- data/src/main.rs +95 -0
- data/src/pretokenize/fast/cl100k.rs +426 -0
- data/src/pretokenize/fast/cl100k_family.rs +891 -0
- data/src/pretokenize/fast/deepseek_v3.rs +605 -0
- data/src/pretokenize/fast/kimi.rs +281 -0
- data/src/pretokenize/fast/mask.rs +1486 -0
- data/src/pretokenize/fast/mod.rs +446 -0
- data/src/pretokenize/fast/nemotron.rs +138 -0
- data/src/pretokenize/fast/o200k.rs +347 -0
- data/src/pretokenize/fast/o200k_family.rs +1734 -0
- data/src/pretokenize/fast/olmo3.rs +505 -0
- data/src/pretokenize/fast/qwen2.rs +429 -0
- data/src/pretokenize/fast/qwen3_5.rs +541 -0
- data/src/pretokenize/fast/r50k.rs +1250 -0
- data/src/pretokenize/mod.rs +1079 -0
- data/src/pretokenize/options.rs +188 -0
- data/src/pretokenize/pretoken.rs +20 -0
- data/src/pretokenize/pretokenize_traits.rs +49 -0
- data/src/pretokenize/reference/avx512.rs +522 -0
- data/src/pretokenize/reference/combinator.rs +572 -0
- data/src/pretokenize/reference/mod.rs +28 -0
- data/src/pretokenize/reference/simd.rs +852 -0
- data/src/pretokenize/reference/state_machine.rs +365 -0
- data/src/pretokenize/unicode.rs +546 -0
- data/src/test_hub.rs +28 -0
- data/src/token.rs +42 -0
- metadata +161 -0
|
@@ -0,0 +1,1734 @@
|
|
|
1
|
+
//! Shared implementation for the o200k regex family: o200k_base (GPT-4o,
|
|
2
|
+
//! gpt-oss), the Nemotron-3 variant, and the Kimi (moonshotai K2) variant.
|
|
3
|
+
//! Their patterns share the shape
|
|
4
|
+
//!
|
|
5
|
+
//! `HAN-RUN?|
|
|
6
|
+
//! [^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+SUF?|
|
|
7
|
+
//! [^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*SUF?|
|
|
8
|
+
//! \p{N}{1,3} or \p{N}| ?[^\s\p{L}\p{N}]+TAIL|\s*[\r\n]+|\s+(?!\S)|\s+`
|
|
9
|
+
//!
|
|
10
|
+
//! where `SUF = (?i:'s|'t|'re|'ve|'m|'ll|'d)` exists in o200k and Kimi
|
|
11
|
+
//! (`CONTRACTIONS`), the digit group is `\p{N}{1,3}` for o200k/Kimi vs
|
|
12
|
+
//! `\p{N}` for Nemotron (`DIGITS3`), the absorbed punct tail `TAIL` is
|
|
13
|
+
//! `[\r\n/]*` for o200k/Nemotron vs `[\r\n]*` for Kimi (`SLASH`), and Kimi
|
|
14
|
+
//! alone (`HAN`) prepends a `[\p{Han}]+` alternative while intersecting
|
|
15
|
+
//! both letter brackets with `[^\p{Han}]` — Han chars form their own runs
|
|
16
|
+
//! and never join letter runs, though a Han numeral (Nl) still counts
|
|
17
|
+
//! toward a `\p{N}{1,3}` group entered on a non-Han digit and a Han symbol
|
|
18
|
+
//! (So/Mc) still continues a `[^\s\p{L}\p{N}]+` punct run (the Han
|
|
19
|
+
//! alternative only wins where a token starts; see
|
|
20
|
+
//! [`crate::pretokenize::unicode::KimiCharClass`]).
|
|
21
|
+
//!
|
|
22
|
+
//! Differences from the cl100k family:
|
|
23
|
+
//! - Letter runs are case-structured. Under leftmost-greedy backtracking
|
|
24
|
+
//! the two letter alternatives reduce to a phase automaton (see
|
|
25
|
+
//! [`CaseState`]): ULC phase until the first strict-lower (Ll), then
|
|
26
|
+
//! LLC phase, where a strict-upper (Lu/Lt) ends the token; a run ending
|
|
27
|
+
//! while still in ULC phase backtracks to its last caseless/mark char
|
|
28
|
+
//! ("camelCase" -> `camel|Case`, "HTTPResponse" one token,
|
|
29
|
+
//! "AxxB" -> `Axx|B` for caseless x). For pure-ASCII text there are no
|
|
30
|
+
//! caseless letters, so the rule IS pairwise: a boundary sits before
|
|
31
|
+
//! `[A-Z]` exactly when the previous char is `[a-z]` — what the ASCII
|
|
32
|
+
//! mask algebra uses; caseless-before-upper needs the phase and
|
|
33
|
+
//! lookahead, so the extended path defers those (rare) chars.
|
|
34
|
+
//! - Contractions are attached suffixes of the letter alternatives, not a
|
|
35
|
+
//! standalone alternative: "don't" is ONE token, and the char after a
|
|
36
|
+
//! consumed suffix always starts a new token ("can'ts" -> `can't|s`).
|
|
37
|
+
//! A contraction applies only when the apostrophe directly follows a
|
|
38
|
+
//! letter-run char; elsewhere `'` is ordinary punctuation (which may
|
|
39
|
+
//! still prefix a letter run: "3'ts" -> `3|'ts`).
|
|
40
|
+
//! - Punctuation runs absorb a `[\r\n/]*` tail. Since `/` is itself in
|
|
41
|
+
//! the punct class, the absorbed tail always begins with a newline:
|
|
42
|
+
//! ".\n//" is one token.
|
|
43
|
+
//! - Marks (`\p{M}`) are dual-class: they join letter runs (they sit in
|
|
44
|
+
//! both letter brackets) AND continue `[^\s\p{L}\p{N}]+` punct runs.
|
|
45
|
+
//! Their effective class is run-contextual, so the mask scanner routes
|
|
46
|
+
//! mark chars (rare) through the scalar path as bad zones.
|
|
47
|
+
//!
|
|
48
|
+
//! The boundary algebra below mirrors `cl100k_family` — see that module
|
|
49
|
+
//! and pretokenizer_optimization_log.md step 16 for the base rules.
|
|
50
|
+
|
|
51
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
52
|
+
use super::mask::{self, AsciiMasks};
|
|
53
|
+
use super::{decode_cp, is_ascii_ws, is_digit, is_letter, scan_numbers_max3};
|
|
54
|
+
use crate::pretokenize::unicode::{O200kCharClass, kimi_class_of, o200k_class_of};
|
|
55
|
+
|
|
56
|
+
#[inline(always)]
|
|
57
|
+
fn is_upper_ascii(b: u8) -> bool {
|
|
58
|
+
b.wrapping_sub(b'A') < 26
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Is this byte in the absorbed-tail class (`[\r\n/]` or `[\r\n]`)?
|
|
62
|
+
#[inline(always)]
|
|
63
|
+
fn is_tail_byte<const SLASH: bool>(b: u8) -> bool {
|
|
64
|
+
b == b'\r' || b == b'\n' || (SLASH && b == b'/')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/// Classify `cp` for the scheme: its effective o200k class plus whether it
|
|
68
|
+
/// is a `[\p{Han}]+` run member (always false off the Kimi scheme; one
|
|
69
|
+
/// table load either way).
|
|
70
|
+
#[inline(always)]
|
|
71
|
+
fn family_class_of<const HAN: bool>(cp: u32) -> (O200kCharClass, bool) {
|
|
72
|
+
if HAN {
|
|
73
|
+
let k = kimi_class_of(cp);
|
|
74
|
+
(k.base(), k.is_han())
|
|
75
|
+
} else {
|
|
76
|
+
(o200k_class_of(cp), false)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// -----------------------------------------------------------------------
|
|
81
|
+
// Scalar ground truth
|
|
82
|
+
// -----------------------------------------------------------------------
|
|
83
|
+
|
|
84
|
+
/// Scan state of a case-structured letter run, mirroring the two-bracket
|
|
85
|
+
/// alternatives under leftmost-greedy backtracking. `U`: still inside
|
|
86
|
+
/// `[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*` (no strict-lower seen yet);
|
|
87
|
+
/// `last_cl_end` is the end offset of the last caseless/mark char in the
|
|
88
|
+
/// phase (0 = none) — the backtrack split point if the run ends on a
|
|
89
|
+
/// strict-upper tail. `L`: inside `[\p{Ll}\p{Lm}\p{Lo}\p{M}]+`, where a
|
|
90
|
+
/// strict-upper char ends the token unconditionally.
|
|
91
|
+
#[derive(Clone, Copy)]
|
|
92
|
+
enum CaseState {
|
|
93
|
+
U { last_cl_end: usize },
|
|
94
|
+
L,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/// Initial [`CaseState`] for a run starting on an ASCII letter (ASCII has
|
|
98
|
+
/// no caseless letters).
|
|
99
|
+
#[inline(always)]
|
|
100
|
+
fn ascii_letter_state(b: u8) -> CaseState {
|
|
101
|
+
if is_upper_ascii(b) {
|
|
102
|
+
CaseState::U { last_cl_end: 0 }
|
|
103
|
+
} else {
|
|
104
|
+
CaseState::L
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/// If the char at `pos` is a letter-run member (`\p{L}` or `\p{M}`, minus
|
|
109
|
+
/// Han under the Kimi scheme), return (offset past it, initial scan state).
|
|
110
|
+
#[inline(always)]
|
|
111
|
+
fn letter_run_first<const HAN: bool>(bytes: &[u8], pos: usize) -> Option<(usize, CaseState)> {
|
|
112
|
+
let &b = bytes.get(pos)?;
|
|
113
|
+
if is_letter(b) {
|
|
114
|
+
return Some((pos + 1, ascii_letter_state(b)));
|
|
115
|
+
}
|
|
116
|
+
if b >= 0x80 {
|
|
117
|
+
let (cp, l) = unsafe { decode_cp(bytes, pos) };
|
|
118
|
+
match family_class_of::<HAN>(cp) {
|
|
119
|
+
(_, true) => {}
|
|
120
|
+
(O200kCharClass::Upper, _) => return Some((pos + l, CaseState::U { last_cl_end: 0 })),
|
|
121
|
+
(O200kCharClass::Lower, _) => return Some((pos + l, CaseState::L)),
|
|
122
|
+
(O200kCharClass::Caseless | O200kCharClass::Mark, _) => {
|
|
123
|
+
return Some((pos + l, CaseState::U { last_cl_end: pos + l }));
|
|
124
|
+
}
|
|
125
|
+
_ => {}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
None
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/// Letter-run continuation with the o200k casing rules: scan run members
|
|
132
|
+
/// (letters and marks) from `pos` with the phase automaton described on
|
|
133
|
+
/// [`CaseState`]. In phase U a strict-upper char continues the token and
|
|
134
|
+
/// a strict-lower switches to phase L; in phase L a strict-upper ends
|
|
135
|
+
/// the token. A run that ends while still in phase U backtracks to the
|
|
136
|
+
/// last caseless/mark char, splitting off the trailing strict-upper run
|
|
137
|
+
/// (which the next `advance` then consumes whole): "AxxB" -> `Axx|B`
|
|
138
|
+
/// for caseless x, "HTTPResponse" and "Z\u{5BF}\u{416}dz" one token.
|
|
139
|
+
#[inline(always)]
|
|
140
|
+
fn scan_case_run<const HAN: bool>(bytes: &[u8], mut pos: usize, mut st: CaseState) -> usize {
|
|
141
|
+
let len = bytes.len();
|
|
142
|
+
loop {
|
|
143
|
+
while pos < len {
|
|
144
|
+
let b = unsafe { *bytes.get_unchecked(pos) };
|
|
145
|
+
if is_upper_ascii(b) {
|
|
146
|
+
if matches!(st, CaseState::L) {
|
|
147
|
+
return pos;
|
|
148
|
+
}
|
|
149
|
+
pos += 1;
|
|
150
|
+
} else if is_letter(b) {
|
|
151
|
+
st = CaseState::L;
|
|
152
|
+
pos += 1;
|
|
153
|
+
} else {
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if pos < len && unsafe { *bytes.get_unchecked(pos) } >= 0x80 {
|
|
158
|
+
let (cp, l) = unsafe { decode_cp(bytes, pos) };
|
|
159
|
+
match family_class_of::<HAN>(cp) {
|
|
160
|
+
(_, true) => break,
|
|
161
|
+
(O200kCharClass::Upper, _) => {
|
|
162
|
+
if matches!(st, CaseState::L) {
|
|
163
|
+
return pos;
|
|
164
|
+
}
|
|
165
|
+
pos += l;
|
|
166
|
+
}
|
|
167
|
+
(O200kCharClass::Lower, _) => {
|
|
168
|
+
st = CaseState::L;
|
|
169
|
+
pos += l;
|
|
170
|
+
}
|
|
171
|
+
(O200kCharClass::Caseless | O200kCharClass::Mark, _) => {
|
|
172
|
+
pos += l;
|
|
173
|
+
if let CaseState::U { ref mut last_cl_end } = st {
|
|
174
|
+
*last_cl_end = pos;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
_ => break,
|
|
178
|
+
}
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
// End of the letter run. A phase-U run ending on a strict-upper tail
|
|
184
|
+
// backtracks to the last caseless/mark char (`[LLC]+` must consume at
|
|
185
|
+
// least one char, and only a caseless/mark can be given back).
|
|
186
|
+
match st {
|
|
187
|
+
CaseState::U { last_cl_end } if last_cl_end != 0 => last_cl_end,
|
|
188
|
+
_ => pos,
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/// Attach a `(?i:'s|'t|'re|'ve|'m|'ll|'d)?` suffix to a letter token
|
|
193
|
+
/// ending at `end`, when the scheme has contractions.
|
|
194
|
+
#[inline(always)]
|
|
195
|
+
fn try_suffix<const CONTRACTIONS: bool>(bytes: &[u8], end: usize) -> usize {
|
|
196
|
+
if !CONTRACTIONS || bytes.get(end) != Some(&b'\'') {
|
|
197
|
+
return end;
|
|
198
|
+
}
|
|
199
|
+
match bytes.get(end + 1).map(u8::to_ascii_lowercase) {
|
|
200
|
+
Some(b's' | b'd' | b'm' | b't') => end + 2,
|
|
201
|
+
Some(b'l') if bytes.get(end + 2).map(u8::to_ascii_lowercase) == Some(b'l') => end + 3,
|
|
202
|
+
Some(b'v') if bytes.get(end + 2).map(u8::to_ascii_lowercase) == Some(b'e') => end + 3,
|
|
203
|
+
Some(b'r') if bytes.get(end + 2).map(u8::to_ascii_lowercase) == Some(b'e') => end + 3,
|
|
204
|
+
// U+017F LATIN SMALL LETTER LONG S case-folds to 's' under `(?i)`
|
|
205
|
+
Some(0xC5) if bytes.get(end + 2) == Some(&0xBF) => end + 3,
|
|
206
|
+
_ => end,
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/// `[^\s\p{L}\p{N}]+` from `pos` (punctuation, symbols, marks, controls —
|
|
211
|
+
/// everything except letters, numbers, and whitespace; a Han symbol's
|
|
212
|
+
/// effective class is Other, so it continues the run under Kimi too).
|
|
213
|
+
#[inline(always)]
|
|
214
|
+
fn scan_punct_from<const HAN: bool>(bytes: &[u8], pos: usize) -> usize {
|
|
215
|
+
let len = bytes.len();
|
|
216
|
+
let mut p = pos;
|
|
217
|
+
loop {
|
|
218
|
+
while p < len {
|
|
219
|
+
let b = unsafe { *bytes.get_unchecked(p) };
|
|
220
|
+
if b >= 0x80 {
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
if is_letter(b) || is_digit(b) || is_ascii_ws(b) {
|
|
224
|
+
return p;
|
|
225
|
+
}
|
|
226
|
+
p += 1;
|
|
227
|
+
}
|
|
228
|
+
if p < len {
|
|
229
|
+
let (cp, l) = unsafe { decode_cp(bytes, p) };
|
|
230
|
+
if matches!(
|
|
231
|
+
family_class_of::<HAN>(cp).0,
|
|
232
|
+
O200kCharClass::Other | O200kCharClass::Mark
|
|
233
|
+
) {
|
|
234
|
+
p += l;
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return p;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/// The `[\r\n/]*` (or Kimi `[\r\n]*`) tail absorbed after a punct run.
|
|
243
|
+
#[inline(always)]
|
|
244
|
+
fn scan_tail<const SLASH: bool>(bytes: &[u8], mut pos: usize) -> usize {
|
|
245
|
+
while pos < bytes.len() && is_tail_byte::<SLASH>(unsafe { *bytes.get_unchecked(pos) }) {
|
|
246
|
+
pos += 1;
|
|
247
|
+
}
|
|
248
|
+
pos
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/// `[\p{Han}]+` from `pos` (chars of any Han class — letters, numerals,
|
|
252
|
+
/// symbols; the leading alternative consumes the maximal Han run).
|
|
253
|
+
#[inline(always)]
|
|
254
|
+
fn scan_han_run(bytes: &[u8], mut pos: usize) -> usize {
|
|
255
|
+
while pos < bytes.len() {
|
|
256
|
+
let b = unsafe { *bytes.get_unchecked(pos) };
|
|
257
|
+
if b < 0x80 {
|
|
258
|
+
return pos;
|
|
259
|
+
}
|
|
260
|
+
let (cp, l) = unsafe { decode_cp(bytes, pos) };
|
|
261
|
+
if !kimi_class_of(cp).is_han() {
|
|
262
|
+
return pos;
|
|
263
|
+
}
|
|
264
|
+
pos += l;
|
|
265
|
+
}
|
|
266
|
+
pos
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/// Whitespace-led token starting at `start`: `\s*[\r\n]+` | `\s+(?!\S)` |
|
|
270
|
+
/// `\s+`, in that priority. Precondition: the letter-prefix and
|
|
271
|
+
/// space+punct alternatives were ruled out.
|
|
272
|
+
#[inline(always)]
|
|
273
|
+
fn ws_token_end(bytes: &[u8], start: usize) -> usize {
|
|
274
|
+
let len = bytes.len();
|
|
275
|
+
let mut p = start;
|
|
276
|
+
let mut last_nl_end = 0usize; // 0 = run contains no \r\n
|
|
277
|
+
let mut last_char_start = start;
|
|
278
|
+
while p < len {
|
|
279
|
+
let b = unsafe { *bytes.get_unchecked(p) };
|
|
280
|
+
if b == b'\r' || b == b'\n' {
|
|
281
|
+
last_char_start = p;
|
|
282
|
+
p += 1;
|
|
283
|
+
last_nl_end = p;
|
|
284
|
+
} else if is_ascii_ws(b) {
|
|
285
|
+
last_char_start = p;
|
|
286
|
+
p += 1;
|
|
287
|
+
} else if b >= 0x80 {
|
|
288
|
+
let (cp, l) = unsafe { decode_cp(bytes, p) };
|
|
289
|
+
if o200k_class_of(cp) == O200kCharClass::Whitespace {
|
|
290
|
+
last_char_start = p;
|
|
291
|
+
p += l;
|
|
292
|
+
} else {
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
} else {
|
|
296
|
+
break;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if last_nl_end != 0 {
|
|
300
|
+
return last_nl_end; // `\s*[\r\n]+`: through the last newline
|
|
301
|
+
}
|
|
302
|
+
if p >= len {
|
|
303
|
+
return p; // `\s+(?!\S)`: lookahead succeeds at EOS
|
|
304
|
+
}
|
|
305
|
+
if last_char_start > start {
|
|
306
|
+
return last_char_start; // `\s+(?!\S)`: all but the last ws char
|
|
307
|
+
}
|
|
308
|
+
p // `\s+`: single whitespace char before content
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/// `\p{N}{1,3}` or `\p{N}` starting at a digit char ending at `first_end`.
|
|
312
|
+
#[inline(always)]
|
|
313
|
+
fn digit_token_end<const DIGITS3: bool>(bytes: &[u8], first_end: usize) -> usize {
|
|
314
|
+
if DIGITS3 {
|
|
315
|
+
scan_numbers_max3(bytes, first_end, 1)
|
|
316
|
+
} else {
|
|
317
|
+
first_end
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/// Advance past one token starting at `pos`. Returns the new position.
|
|
322
|
+
/// `pos` must be < `bytes.len()`.
|
|
323
|
+
#[inline(always)]
|
|
324
|
+
pub(crate) fn advance_pos<
|
|
325
|
+
const CONTRACTIONS: bool,
|
|
326
|
+
const DIGITS3: bool,
|
|
327
|
+
const SLASH: bool,
|
|
328
|
+
const HAN: bool,
|
|
329
|
+
>(
|
|
330
|
+
bytes: &[u8],
|
|
331
|
+
pos: usize,
|
|
332
|
+
) -> usize {
|
|
333
|
+
let b0 = unsafe { *bytes.get_unchecked(pos) };
|
|
334
|
+
|
|
335
|
+
// Hot path 1: ASCII letter run (empty prefix)
|
|
336
|
+
if is_letter(b0) {
|
|
337
|
+
let e = scan_case_run::<HAN>(bytes, pos + 1, ascii_letter_state(b0));
|
|
338
|
+
return try_suffix::<CONTRACTIONS>(bytes, e);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Hot path 2: space prefix
|
|
342
|
+
if b0 == b' ' {
|
|
343
|
+
let Some(&b1) = bytes.get(pos + 1) else {
|
|
344
|
+
return pos + 1; // trailing lone space (`\s+(?!\S)` at EOS)
|
|
345
|
+
};
|
|
346
|
+
if is_letter(b1) {
|
|
347
|
+
let e = scan_case_run::<HAN>(bytes, pos + 2, ascii_letter_state(b1));
|
|
348
|
+
return try_suffix::<CONTRACTIONS>(bytes, e);
|
|
349
|
+
}
|
|
350
|
+
if b1 < 0x80 {
|
|
351
|
+
if is_digit(b1) {
|
|
352
|
+
return pos + 1; // numbers never absorb the space
|
|
353
|
+
}
|
|
354
|
+
if is_ascii_ws(b1) {
|
|
355
|
+
return ws_token_end(bytes, pos);
|
|
356
|
+
}
|
|
357
|
+
// ` ?[^\s\p{L}\p{N}]+` + tail
|
|
358
|
+
let p = scan_punct_from::<HAN>(bytes, pos + 2);
|
|
359
|
+
return scan_tail::<SLASH>(bytes, p);
|
|
360
|
+
}
|
|
361
|
+
let (cp, l) = unsafe { decode_cp(bytes, pos + 1) };
|
|
362
|
+
let p1 = pos + 1 + l;
|
|
363
|
+
return match family_class_of::<HAN>(cp) {
|
|
364
|
+
// A Han letter can neither join a letter run nor (being \p{L})
|
|
365
|
+
// extend ` ?[^\s\p{L}\p{N}]+`: the space is a lone `\s+` token
|
|
366
|
+
// and the Han run starts after it. (Han symbols fall to the
|
|
367
|
+
// Other arm — they are ordinary punct-run members here — and
|
|
368
|
+
// Han numerals to the Number arm.)
|
|
369
|
+
(O200kCharClass::Caseless, true) => pos + 1,
|
|
370
|
+
(O200kCharClass::Upper, _) => try_suffix::<CONTRACTIONS>(
|
|
371
|
+
bytes,
|
|
372
|
+
scan_case_run::<HAN>(bytes, p1, CaseState::U { last_cl_end: 0 }),
|
|
373
|
+
),
|
|
374
|
+
(O200kCharClass::Lower, _) => {
|
|
375
|
+
try_suffix::<CONTRACTIONS>(bytes, scan_case_run::<HAN>(bytes, p1, CaseState::L))
|
|
376
|
+
}
|
|
377
|
+
(O200kCharClass::Caseless | O200kCharClass::Mark, _) => try_suffix::<CONTRACTIONS>(
|
|
378
|
+
bytes,
|
|
379
|
+
scan_case_run::<HAN>(bytes, p1, CaseState::U { last_cl_end: p1 }),
|
|
380
|
+
),
|
|
381
|
+
(O200kCharClass::Whitespace, _) => ws_token_end(bytes, pos),
|
|
382
|
+
(O200kCharClass::Number, _) => pos + 1,
|
|
383
|
+
(O200kCharClass::Other, _) => {
|
|
384
|
+
scan_tail::<SLASH>(bytes, scan_punct_from::<HAN>(bytes, p1))
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// Non-ASCII first char
|
|
390
|
+
if b0 >= 0x80 {
|
|
391
|
+
let (cp, l) = unsafe { decode_cp(bytes, pos) };
|
|
392
|
+
let p0 = pos + l;
|
|
393
|
+
let (class, han) = family_class_of::<HAN>(cp);
|
|
394
|
+
// `[\p{Han}]+` is the leading alternative: any Han char (whatever
|
|
395
|
+
// its base class) starting a token starts a Han run.
|
|
396
|
+
if HAN && han {
|
|
397
|
+
return scan_han_run(bytes, p0);
|
|
398
|
+
}
|
|
399
|
+
return match class {
|
|
400
|
+
O200kCharClass::Upper => try_suffix::<CONTRACTIONS>(
|
|
401
|
+
bytes,
|
|
402
|
+
scan_case_run::<HAN>(bytes, p0, CaseState::U { last_cl_end: 0 }),
|
|
403
|
+
),
|
|
404
|
+
O200kCharClass::Lower => {
|
|
405
|
+
try_suffix::<CONTRACTIONS>(bytes, scan_case_run::<HAN>(bytes, p0, CaseState::L))
|
|
406
|
+
}
|
|
407
|
+
O200kCharClass::Caseless | O200kCharClass::Mark => try_suffix::<CONTRACTIONS>(
|
|
408
|
+
bytes,
|
|
409
|
+
scan_case_run::<HAN>(bytes, p0, CaseState::U { last_cl_end: p0 }),
|
|
410
|
+
),
|
|
411
|
+
O200kCharClass::Number => digit_token_end::<DIGITS3>(bytes, p0),
|
|
412
|
+
// Any non-letter/number char except \r\n may prefix a run
|
|
413
|
+
class => {
|
|
414
|
+
if let Some((e, st)) = letter_run_first::<HAN>(bytes, p0) {
|
|
415
|
+
return try_suffix::<CONTRACTIONS>(bytes, scan_case_run::<HAN>(bytes, e, st));
|
|
416
|
+
}
|
|
417
|
+
if class == O200kCharClass::Whitespace {
|
|
418
|
+
ws_token_end(bytes, pos)
|
|
419
|
+
} else {
|
|
420
|
+
scan_tail::<SLASH>(bytes, scan_punct_from::<HAN>(bytes, p0))
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// ASCII digit
|
|
427
|
+
if is_digit(b0) {
|
|
428
|
+
return digit_token_end::<DIGITS3>(bytes, pos + 1);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// \r and \n are excluded from the letter-run prefix
|
|
432
|
+
if b0 == b'\r' || b0 == b'\n' {
|
|
433
|
+
return ws_token_end(bytes, pos);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// Other ASCII whitespace (\t, \x0b, \x0c) may prefix a letter run
|
|
437
|
+
if is_ascii_ws(b0) {
|
|
438
|
+
if let Some((e, st)) = letter_run_first::<HAN>(bytes, pos + 1) {
|
|
439
|
+
return try_suffix::<CONTRACTIONS>(bytes, scan_case_run::<HAN>(bytes, e, st));
|
|
440
|
+
}
|
|
441
|
+
return ws_token_end(bytes, pos);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// ASCII punctuation/symbol/control (including `'`: o200k has no
|
|
445
|
+
// standalone contraction alternative, so a leading apostrophe is
|
|
446
|
+
// ordinary punctuation / a letter-run prefix: "'sound" is one token)
|
|
447
|
+
if let Some((e, st)) = letter_run_first::<HAN>(bytes, pos + 1) {
|
|
448
|
+
return try_suffix::<CONTRACTIONS>(bytes, scan_case_run::<HAN>(bytes, e, st));
|
|
449
|
+
}
|
|
450
|
+
scan_tail::<SLASH>(bytes, scan_punct_from::<HAN>(bytes, pos + 1))
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// -----------------------------------------------------------------------
|
|
454
|
+
// Mask-scanner boundary algebra
|
|
455
|
+
// -----------------------------------------------------------------------
|
|
456
|
+
|
|
457
|
+
/// Smear `seed` upward (toward higher bits) through contiguous set bits of
|
|
458
|
+
/// `within`, in log steps.
|
|
459
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
460
|
+
#[inline(always)]
|
|
461
|
+
fn smear_up(seed: u64, within: u64) -> u64 {
|
|
462
|
+
let mut a = seed;
|
|
463
|
+
let mut m = within;
|
|
464
|
+
let mut sh = 1u32;
|
|
465
|
+
while sh < 64 {
|
|
466
|
+
a |= (a << sh) & m;
|
|
467
|
+
m &= m << sh;
|
|
468
|
+
sh <<= 1;
|
|
469
|
+
}
|
|
470
|
+
a
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/// Per-byte class masks for a batch's unicode chars under the o200k
|
|
474
|
+
/// classifier — the o200k analogue of [`mask::UniClasses`], with the
|
|
475
|
+
/// case-split letter masks the scheme needs. Every byte of a classified
|
|
476
|
+
/// char carries the char's class, so byte-adjacency == char-adjacency.
|
|
477
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
478
|
+
#[derive(Clone, Copy, Default)]
|
|
479
|
+
struct OUni {
|
|
480
|
+
/// All letter-run bytes (upper + lower + caseless; marks excluded —
|
|
481
|
+
/// they are contextual and deferred via `mk`).
|
|
482
|
+
l: u64,
|
|
483
|
+
/// Strict-upper (Lu/Lt) bytes.
|
|
484
|
+
u: u64,
|
|
485
|
+
/// Caseless-letter (Lm/Lo) bytes.
|
|
486
|
+
cl: u64,
|
|
487
|
+
/// Number / punct-run / whitespace bytes.
|
|
488
|
+
n: u64,
|
|
489
|
+
o: u64,
|
|
490
|
+
ws: u64,
|
|
491
|
+
/// Whitespace lead bits by char length (for `(?!\S)` shift tests).
|
|
492
|
+
w2: u64,
|
|
493
|
+
w3: u64,
|
|
494
|
+
/// Lead bits of all classified chars by length (two-chars-back rule).
|
|
495
|
+
lead2: u64,
|
|
496
|
+
lead3: u64,
|
|
497
|
+
lead4: u64,
|
|
498
|
+
/// Continuation bytes of classified chars.
|
|
499
|
+
cont: u64,
|
|
500
|
+
/// Bytes only the scalar path can decide (±1 bad smear): number chars
|
|
501
|
+
/// (char-counted grouping), ws straddling the batch end, stray
|
|
502
|
+
/// continuation bytes.
|
|
503
|
+
resid: u64,
|
|
504
|
+
/// Mark bytes (±4 bad smear). A mark's run-contextual class can
|
|
505
|
+
/// affect boundaries up to two CHARS after it, which multi-byte
|
|
506
|
+
/// followers can push past the 4-byte smear; those stragglers are
|
|
507
|
+
/// wrongly-cleared bits (extending the scalar walk) or wrongly-set
|
|
508
|
+
/// bits interior to a token starting inside the zone, both killed by
|
|
509
|
+
/// MaskState's resume masking after the scalar overrun — the same
|
|
510
|
+
/// invariant the resid zones rely on. Kimi routes Han symbols (So/Mc)
|
|
511
|
+
/// here too: punct-run members mid-run, Han-run chars at a token
|
|
512
|
+
/// start, so their class is run-contextual exactly like a mark's.
|
|
513
|
+
mk: u64,
|
|
514
|
+
/// Han-letter bytes (Kimi only): their own run class, with the
|
|
515
|
+
/// boundary rule `han_leads & !prev-is-han`. Han numerals go through
|
|
516
|
+
/// `resid` (their `\p{N}{1,3}`-vs-Han-run role is contextual) and Han
|
|
517
|
+
/// symbols through `mk`.
|
|
518
|
+
han: u64,
|
|
519
|
+
/// Lead bits of the `han` chars.
|
|
520
|
+
han_leads: u64,
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/// Boundary carries from the chars before the batch (o200k variant of the
|
|
524
|
+
/// cl100k family's `Carries`, plus the case and absorbed-tail bits).
|
|
525
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
526
|
+
#[derive(Clone, Copy, Default)]
|
|
527
|
+
struct OCarries {
|
|
528
|
+
/// P1 is a letter / strict-upper / caseless / space (0x20) /
|
|
529
|
+
/// non-newline non-space ws / punct / any ws / digit.
|
|
530
|
+
pl: u64,
|
|
531
|
+
pu: u64,
|
|
532
|
+
pcl: u64,
|
|
533
|
+
ps: u64,
|
|
534
|
+
pwt: u64,
|
|
535
|
+
po: u64,
|
|
536
|
+
pws: u64,
|
|
537
|
+
pd: u64,
|
|
538
|
+
/// P1 is a Han letter (Kimi only).
|
|
539
|
+
phan: u64,
|
|
540
|
+
/// P2 is punct-or-space, for a char lead at bit 0.
|
|
541
|
+
c2_os: u64,
|
|
542
|
+
/// Same test positioned at the first lead AFTER a straddling-in P1.
|
|
543
|
+
b2b_in: u64,
|
|
544
|
+
/// P1 is an absorbed `[\r\n/]*` tail byte whose token may continue
|
|
545
|
+
/// into this batch (seeds the tail smear at bit 0).
|
|
546
|
+
p_abs: bool,
|
|
547
|
+
/// The tail walkback could not resolve (pathological run): the batch's
|
|
548
|
+
/// leading tail-class run must be a bad zone.
|
|
549
|
+
force_bad_lead: bool,
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/// Was the tail-class byte at `scan - 1` absorbed by a punct run's
|
|
553
|
+
/// `[\r\n/]*` (Kimi: `[\r\n]*`) tail (as opposed to being a fresh
|
|
554
|
+
/// punct-run `/` or a ws-run newline)? Walks the tail-class run back
|
|
555
|
+
/// (bounded) and classifies the byte before it. `None`: unresolved
|
|
556
|
+
/// (over-long run, or a preceding mark or Han symbol whose own class is
|
|
557
|
+
/// run-contextual).
|
|
558
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
559
|
+
fn prev_tail_absorbed<const SLASH: bool, const HAN: bool>(
|
|
560
|
+
bytes: &[u8],
|
|
561
|
+
scan: usize,
|
|
562
|
+
) -> Option<bool> {
|
|
563
|
+
debug_assert!(scan >= 1 && is_tail_byte::<SLASH>(bytes[scan - 1]));
|
|
564
|
+
let mut r = scan - 1;
|
|
565
|
+
let mut steps = 0;
|
|
566
|
+
while r > 0 && is_tail_byte::<SLASH>(bytes[r - 1]) {
|
|
567
|
+
r -= 1;
|
|
568
|
+
steps += 1;
|
|
569
|
+
if steps > 8 {
|
|
570
|
+
return None;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
// T-run = bytes[r..scan]. The `[\r\n/]*` tail is greedy, so once
|
|
574
|
+
// absorption triggers — at the first newline that directly follows a
|
|
575
|
+
// punct-run char (an in-run slash, or the pre-run char for a
|
|
576
|
+
// run-leading newline) — everything to the run's end is absorbed.
|
|
577
|
+
// Before the trigger, newlines are ws-run members and slashes are
|
|
578
|
+
// ordinary punct-run bytes.
|
|
579
|
+
let run = &bytes[r..scan];
|
|
580
|
+
let mut trigger = usize::MAX;
|
|
581
|
+
let mut seen_slash = false;
|
|
582
|
+
for (j, &b) in run.iter().enumerate() {
|
|
583
|
+
if b == b'/' {
|
|
584
|
+
seen_slash = true;
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
if seen_slash {
|
|
588
|
+
trigger = j;
|
|
589
|
+
break;
|
|
590
|
+
}
|
|
591
|
+
if j == 0 {
|
|
592
|
+
// Run-leading newline: the pre-run char decides.
|
|
593
|
+
if r == 0 {
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
let pb = bytes[r - 1];
|
|
597
|
+
let pred_punct = if pb < 0x80 {
|
|
598
|
+
if !is_letter(pb) && !is_digit(pb) && !is_ascii_ws(pb) {
|
|
599
|
+
Some(true)
|
|
600
|
+
} else {
|
|
601
|
+
Some(false)
|
|
602
|
+
}
|
|
603
|
+
} else {
|
|
604
|
+
let mut k = r - 1;
|
|
605
|
+
while k > 0 && bytes[k] & 0xC0 == 0x80 {
|
|
606
|
+
k -= 1;
|
|
607
|
+
}
|
|
608
|
+
let (cp, _) = unsafe { decode_cp(bytes, k) };
|
|
609
|
+
match family_class_of::<HAN>(cp) {
|
|
610
|
+
(O200kCharClass::Other, false) => Some(true),
|
|
611
|
+
// A mark continues whatever run precedes it; a Han
|
|
612
|
+
// symbol is a punct-run member or a Han-run char
|
|
613
|
+
// depending on where its token started.
|
|
614
|
+
(O200kCharClass::Mark, _) | (O200kCharClass::Other, true) => None,
|
|
615
|
+
_ => Some(false),
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
match pred_punct {
|
|
619
|
+
Some(true) => {
|
|
620
|
+
trigger = 0;
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
Some(false) => {}
|
|
624
|
+
None => return None,
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
Some(scan - 1 - r >= trigger)
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/// Two-back "punct or space" test (`c2_os`) for the ASCII byte at `idx`.
|
|
632
|
+
/// A slash may be an absorbed tail byte — a token end, neither punct-run
|
|
633
|
+
/// member nor space — so it resolves through the walkback (only when the
|
|
634
|
+
/// scheme absorbs slashes). `None`: unresolved (callers set
|
|
635
|
+
/// `force_bad_lead`).
|
|
636
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
637
|
+
#[inline(always)]
|
|
638
|
+
fn c2_os_ascii<const SLASH: bool, const HAN: bool>(bytes: &[u8], idx: usize) -> Option<u64> {
|
|
639
|
+
let b2 = bytes[idx];
|
|
640
|
+
if SLASH && b2 == b'/' {
|
|
641
|
+
return prev_tail_absorbed::<SLASH, HAN>(bytes, idx + 1).map(|abs| u64::from(!abs));
|
|
642
|
+
}
|
|
643
|
+
Some(u64::from(
|
|
644
|
+
b2 == b' ' || (!is_letter(b2) && !is_digit(b2) && !is_ascii_ws(b2)),
|
|
645
|
+
))
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/// Pure-ASCII carries. Requires `scan > 0`, `bytes[scan-1] < 0x80` (and
|
|
649
|
+
/// `bytes[scan-2] < 0x80` when present), and `bytes[scan-1]` NOT a
|
|
650
|
+
/// tail-class byte (those route through [`prev_tail_absorbed`] first).
|
|
651
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
652
|
+
#[inline(always)]
|
|
653
|
+
fn ascii_carries<const SLASH: bool, const HAN: bool>(bytes: &[u8], scan: usize) -> OCarries {
|
|
654
|
+
let b = bytes[scan - 1];
|
|
655
|
+
debug_assert!(!is_tail_byte::<SLASH>(b));
|
|
656
|
+
let bit = |c: bool| u64::from(c);
|
|
657
|
+
let (l, d, w) = (is_letter(b), is_digit(b), is_ascii_ws(b));
|
|
658
|
+
let (c2_os, c2_unresolved) = if scan >= 2 {
|
|
659
|
+
match c2_os_ascii::<SLASH, HAN>(bytes, scan - 2) {
|
|
660
|
+
Some(v) => (v, false),
|
|
661
|
+
None => (0, true),
|
|
662
|
+
}
|
|
663
|
+
} else {
|
|
664
|
+
(0, false)
|
|
665
|
+
};
|
|
666
|
+
OCarries {
|
|
667
|
+
force_bad_lead: c2_unresolved,
|
|
668
|
+
pl: bit(l),
|
|
669
|
+
pu: bit(is_upper_ascii(b)),
|
|
670
|
+
pcl: 0,
|
|
671
|
+
ps: bit(b == b' '),
|
|
672
|
+
pwt: bit(w && b != b' '), // \r\n excluded by the debug_assert
|
|
673
|
+
po: bit(!l && !d && !w),
|
|
674
|
+
pws: bit(w),
|
|
675
|
+
pd: bit(d),
|
|
676
|
+
phan: 0,
|
|
677
|
+
c2_os,
|
|
678
|
+
b2b_in: 0,
|
|
679
|
+
p_abs: false,
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/// Carries when the byte before the batch is tail-class (`[\r\n/]`):
|
|
684
|
+
/// resolves absorbed-tail vs fresh-run via [`prev_tail_absorbed`]. An
|
|
685
|
+
/// absorbed tail ended the previous token, so every "P1 is X" carry is
|
|
686
|
+
/// zero and only the tail-continuation seed survives.
|
|
687
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
688
|
+
#[inline(never)]
|
|
689
|
+
fn tail_carries<const SLASH: bool, const HAN: bool>(bytes: &[u8], scan: usize) -> OCarries {
|
|
690
|
+
match prev_tail_absorbed::<SLASH, HAN>(bytes, scan) {
|
|
691
|
+
Some(true) => OCarries { p_abs: true, ..OCarries::default() },
|
|
692
|
+
Some(false) => {
|
|
693
|
+
let b = bytes[scan - 1];
|
|
694
|
+
let bit = |c: bool| u64::from(c);
|
|
695
|
+
// A fresh '/' is an ordinary punct byte; \r\n are newlines
|
|
696
|
+
// (ws class, po = 0). c2_os as in ascii_carries when P2 is
|
|
697
|
+
// ASCII; a non-ASCII P2 next to a tail byte is rare — defer.
|
|
698
|
+
if scan >= 2 && bytes[scan - 2] >= 0x80 {
|
|
699
|
+
return OCarries {
|
|
700
|
+
force_bad_lead: true,
|
|
701
|
+
..OCarries::default()
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
let c2_os = if scan >= 2 {
|
|
705
|
+
let b2 = bytes[scan - 2];
|
|
706
|
+
bit(b2 == b' ' || (!is_letter(b2) && !is_digit(b2) && !is_ascii_ws(b2)))
|
|
707
|
+
} else {
|
|
708
|
+
0
|
|
709
|
+
};
|
|
710
|
+
OCarries {
|
|
711
|
+
po: bit(b == b'/'),
|
|
712
|
+
pws: bit(b != b'/'),
|
|
713
|
+
c2_os,
|
|
714
|
+
..OCarries::default()
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
None => OCarries {
|
|
718
|
+
force_bad_lead: true,
|
|
719
|
+
..OCarries::default()
|
|
720
|
+
},
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/// Classify every unicode char whose lead bit is in `m` for
|
|
725
|
+
/// `bytes[scan..scan+64]` with the o200k classifier — the o200k analogue
|
|
726
|
+
/// of [`mask::classify_uni_chars`] (NUMBERS = false, LEADS = true), with
|
|
727
|
+
/// case-split letter masks and marks deferred via `mk`.
|
|
728
|
+
///
|
|
729
|
+
/// # Safety
|
|
730
|
+
///
|
|
731
|
+
/// `scan + 70 <= bytes.len()` (the batch classifiers' lookahead guard).
|
|
732
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
733
|
+
#[inline(always)]
|
|
734
|
+
unsafe fn classify_uni_o200k<const HAN: bool>(bytes: &[u8], scan: usize, mut m: u64) -> OUni {
|
|
735
|
+
use super::decode_cp_inbounds;
|
|
736
|
+
let mut u = OUni::default();
|
|
737
|
+
while m != 0 {
|
|
738
|
+
let i = m.trailing_zeros() as usize;
|
|
739
|
+
m &= m - 1;
|
|
740
|
+
let b = bytes[scan + i];
|
|
741
|
+
if b < 0xC2 {
|
|
742
|
+
u.resid |= 1 << i; // stray continuation byte (invalid UTF-8)
|
|
743
|
+
continue;
|
|
744
|
+
}
|
|
745
|
+
let l = if b < 0xE0 {
|
|
746
|
+
2
|
|
747
|
+
} else if b < 0xF0 {
|
|
748
|
+
3
|
|
749
|
+
} else {
|
|
750
|
+
4
|
|
751
|
+
};
|
|
752
|
+
let chm = ((1u64 << l) - 1) << i; // in-batch bytes (excess drops)
|
|
753
|
+
let lead = 1u64 << i;
|
|
754
|
+
// SAFETY: scan + 70 <= len (this fn's contract), i <= 63, so
|
|
755
|
+
// scan + i + 4 <= len even for a 4-byte lead at bit 63.
|
|
756
|
+
let (cp, _) = unsafe { decode_cp_inbounds(bytes, scan + i) };
|
|
757
|
+
match family_class_of::<HAN>(cp) {
|
|
758
|
+
// Han letters: their own run class (see OUni::han). Han
|
|
759
|
+
// numerals fall to the Number arm (whose resid already defers
|
|
760
|
+
// them: their Han-run-vs-digit-group role is contextual) and
|
|
761
|
+
// Han symbols to the Mark arm (same run-contextual deferral).
|
|
762
|
+
(O200kCharClass::Caseless, true) => {
|
|
763
|
+
u.han |= chm;
|
|
764
|
+
u.han_leads |= lead;
|
|
765
|
+
}
|
|
766
|
+
(O200kCharClass::Upper, _) => {
|
|
767
|
+
u.l |= chm;
|
|
768
|
+
u.u |= chm;
|
|
769
|
+
}
|
|
770
|
+
(O200kCharClass::Lower, _) => u.l |= chm,
|
|
771
|
+
(O200kCharClass::Caseless, _) => {
|
|
772
|
+
u.l |= chm;
|
|
773
|
+
u.cl |= chm;
|
|
774
|
+
}
|
|
775
|
+
(O200kCharClass::Mark, _) | (O200kCharClass::Other, true) => {
|
|
776
|
+
// Contextual (letter-run joiner AND punct-run member, or
|
|
777
|
+
// for Han symbols punct-run member AND Han-run char):
|
|
778
|
+
// punct-class for the neighbors' mask algebra, deferred
|
|
779
|
+
// (±4) for everything the context could change.
|
|
780
|
+
u.o |= chm;
|
|
781
|
+
u.mk |= chm;
|
|
782
|
+
}
|
|
783
|
+
(O200kCharClass::Number, _) => {
|
|
784
|
+
u.n |= chm;
|
|
785
|
+
u.resid |= chm; // char-counted grouping: scalar
|
|
786
|
+
}
|
|
787
|
+
(O200kCharClass::Other, _) => u.o |= chm,
|
|
788
|
+
(O200kCharClass::Whitespace, _) => {
|
|
789
|
+
u.ws |= chm;
|
|
790
|
+
if i + l > 64 || l == 4 {
|
|
791
|
+
u.resid |= chm; // straddling-out ws stays a bad zone
|
|
792
|
+
} else if l == 2 {
|
|
793
|
+
u.w2 |= lead;
|
|
794
|
+
} else {
|
|
795
|
+
u.w3 |= lead;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
match l {
|
|
800
|
+
2 => u.lead2 |= lead,
|
|
801
|
+
3 => u.lead3 |= lead,
|
|
802
|
+
_ => u.lead4 |= lead,
|
|
803
|
+
}
|
|
804
|
+
u.cont |= chm & !lead;
|
|
805
|
+
m &= !chm;
|
|
806
|
+
}
|
|
807
|
+
u
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/// ASCII class masks the o200k algebra needs on top of
|
|
811
|
+
/// [`mask::AsciiMasks`]: strict-uppercase letters and slashes.
|
|
812
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
813
|
+
#[derive(Clone, Copy, Default)]
|
|
814
|
+
struct OAsciiExtra {
|
|
815
|
+
up: u64,
|
|
816
|
+
sl: u64,
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/// Slow(er) path for batches with non-ASCII in or just before them — the
|
|
820
|
+
/// o200k analogue of `cl100k_family::family_extended_masks`: carries walk
|
|
821
|
+
/// back through multi-byte chars with the o200k classifier, unicode chars
|
|
822
|
+
/// join the effective class masks, then the shared algebra applies.
|
|
823
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
824
|
+
#[cfg_attr(
|
|
825
|
+
target_arch = "x86_64",
|
|
826
|
+
target_feature(enable = "bmi1,bmi2,lzcnt,popcnt")
|
|
827
|
+
)]
|
|
828
|
+
#[inline(never)]
|
|
829
|
+
fn o200k_extended_masks<
|
|
830
|
+
const CONTRACTIONS: bool,
|
|
831
|
+
const DIGITS3: bool,
|
|
832
|
+
const SLASH: bool,
|
|
833
|
+
const HAN: bool,
|
|
834
|
+
>(
|
|
835
|
+
bytes: &[u8],
|
|
836
|
+
scan: usize,
|
|
837
|
+
am: AsciiMasks,
|
|
838
|
+
ax: OAsciiExtra,
|
|
839
|
+
) -> (u64, u64) {
|
|
840
|
+
use super::decode_cp_inbounds;
|
|
841
|
+
|
|
842
|
+
/// The char containing byte `pos - 1`: its scheme class (plus Han
|
|
843
|
+
/// flag), lead index, and end (exclusive) — [`mask::char_through`]
|
|
844
|
+
/// with the scheme classifier. Same safety contract (`pos > 0`,
|
|
845
|
+
/// `pos + 3 <= len` when `bytes[pos-1]` is non-ASCII; the batch guard
|
|
846
|
+
/// covers callers).
|
|
847
|
+
#[inline(always)]
|
|
848
|
+
unsafe fn char_through_o200k<const HAN: bool>(
|
|
849
|
+
bytes: &[u8],
|
|
850
|
+
pos: usize,
|
|
851
|
+
) -> (O200kCharClass, bool, usize, usize) {
|
|
852
|
+
let b = bytes[pos - 1];
|
|
853
|
+
if b < 0x80 {
|
|
854
|
+
let cls = if is_upper_ascii(b) {
|
|
855
|
+
O200kCharClass::Upper
|
|
856
|
+
} else if is_letter(b) {
|
|
857
|
+
O200kCharClass::Lower
|
|
858
|
+
} else if is_digit(b) {
|
|
859
|
+
O200kCharClass::Number
|
|
860
|
+
} else if is_ascii_ws(b) {
|
|
861
|
+
O200kCharClass::Whitespace
|
|
862
|
+
} else {
|
|
863
|
+
O200kCharClass::Other
|
|
864
|
+
};
|
|
865
|
+
return (cls, false, pos - 1, pos);
|
|
866
|
+
}
|
|
867
|
+
let mut j = pos - 1;
|
|
868
|
+
while j > 0 && bytes[j] & 0xC0 == 0x80 {
|
|
869
|
+
j -= 1;
|
|
870
|
+
}
|
|
871
|
+
// SAFETY: j < pos and pos + 3 <= len (contract), so j + 4 <= len.
|
|
872
|
+
let (cp, l) = unsafe { decode_cp_inbounds(bytes, j) };
|
|
873
|
+
let (cls, han) = family_class_of::<HAN>(cp);
|
|
874
|
+
(cls, han, j, j + l)
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
let mut cl = OUni::default();
|
|
878
|
+
let cr = if scan == 0 {
|
|
879
|
+
OCarries::default()
|
|
880
|
+
} else if bytes[scan - 1] < 0x80 && is_tail_byte::<SLASH>(bytes[scan - 1]) {
|
|
881
|
+
tail_carries::<SLASH, HAN>(bytes, scan)
|
|
882
|
+
} else if bytes[scan - 1] < 0x80 && (scan < 2 || bytes[scan - 2] < 0x80) {
|
|
883
|
+
ascii_carries::<SLASH, HAN>(bytes, scan)
|
|
884
|
+
} else {
|
|
885
|
+
// A multi-byte char within two bytes of the batch start.
|
|
886
|
+
// SAFETY: scan > 0, and the batch guard covers pos + 3 <= len.
|
|
887
|
+
let (c1, h1, j1, e1) = unsafe { char_through_o200k::<HAN>(bytes, scan) };
|
|
888
|
+
let chm = if e1 > scan { (1u64 << (e1 - scan)) - 1 } else { 0 };
|
|
889
|
+
cl.cont = chm;
|
|
890
|
+
let (c2v, c2_defer) = if j1 == 0 {
|
|
891
|
+
(0, false)
|
|
892
|
+
} else if SLASH && bytes[j1 - 1] == b'/' {
|
|
893
|
+
// An absorbed tail slash is a token end, not a punct-run char.
|
|
894
|
+
match prev_tail_absorbed::<SLASH, HAN>(bytes, j1) {
|
|
895
|
+
Some(abs) => (u64::from(!abs), false),
|
|
896
|
+
None => (0, true),
|
|
897
|
+
}
|
|
898
|
+
} else {
|
|
899
|
+
// SAFETY: j1 > 0, j1 < scan keeps the decode in the guard.
|
|
900
|
+
let (c2c, h2, _, _) = unsafe { char_through_o200k::<HAN>(bytes, j1) };
|
|
901
|
+
(
|
|
902
|
+
u64::from(
|
|
903
|
+
bytes[j1 - 1] == b' '
|
|
904
|
+
|| (matches!(c2c, O200kCharClass::Other | O200kCharClass::Mark) && !h2),
|
|
905
|
+
),
|
|
906
|
+
// A mark P2 makes the two-back test run-contextual; so
|
|
907
|
+
// does a Han symbol (punct-run member or Han-run char).
|
|
908
|
+
c2c == O200kCharClass::Mark || (h2 && c2c == O200kCharClass::Other),
|
|
909
|
+
)
|
|
910
|
+
};
|
|
911
|
+
let mut c = OCarries::default();
|
|
912
|
+
if e1 > scan {
|
|
913
|
+
c.b2b_in = c2v << (e1 - scan);
|
|
914
|
+
} else {
|
|
915
|
+
c.c2_os = c2v;
|
|
916
|
+
}
|
|
917
|
+
if c2_defer {
|
|
918
|
+
c.force_bad_lead = true;
|
|
919
|
+
}
|
|
920
|
+
c.pd = u64::from(c1 == O200kCharClass::Number);
|
|
921
|
+
match (c1, h1) {
|
|
922
|
+
// A Han letter: p_han carry; its in-batch bytes join the han
|
|
923
|
+
// mask so in-batch followers see char adjacency.
|
|
924
|
+
(O200kCharClass::Caseless, true) => {
|
|
925
|
+
cl.han |= chm;
|
|
926
|
+
c.phan = 1;
|
|
927
|
+
}
|
|
928
|
+
(O200kCharClass::Upper, _) => {
|
|
929
|
+
cl.l |= chm;
|
|
930
|
+
cl.u |= chm;
|
|
931
|
+
c.pl = 1;
|
|
932
|
+
c.pu = 1;
|
|
933
|
+
}
|
|
934
|
+
(O200kCharClass::Lower, _) => {
|
|
935
|
+
cl.l |= chm;
|
|
936
|
+
c.pl = 1;
|
|
937
|
+
}
|
|
938
|
+
(O200kCharClass::Caseless, _) => {
|
|
939
|
+
cl.l |= chm;
|
|
940
|
+
cl.cl |= chm;
|
|
941
|
+
c.pl = 1;
|
|
942
|
+
c.pcl = 1;
|
|
943
|
+
}
|
|
944
|
+
(O200kCharClass::Mark, _) | (O200kCharClass::Other, true) => {
|
|
945
|
+
// Contextual (marks; Kimi Han symbols): defer the batch
|
|
946
|
+
// front to the scalar path.
|
|
947
|
+
cl.o |= chm;
|
|
948
|
+
cl.mk |= chm | 1; // bit 0 seeds the ±4 smear even when
|
|
949
|
+
// the char sits entirely before the batch
|
|
950
|
+
c.po = 1;
|
|
951
|
+
}
|
|
952
|
+
(O200kCharClass::Number, h) => {
|
|
953
|
+
cl.n |= chm;
|
|
954
|
+
// A digit char straddling INTO the batch: the leading
|
|
955
|
+
// ASCII digit run's `\p{N}{1,3}` phase started before the
|
|
956
|
+
// batch, and the `pd` seed below can't see it (bit 0 is a
|
|
957
|
+
// continuation byte, not an ASCII digit). Defer via resid
|
|
958
|
+
// so the bad<<1 seed catches the run.
|
|
959
|
+
cl.resid |= chm;
|
|
960
|
+
if h {
|
|
961
|
+
// A Han numeral P1: a following Han char's boundary
|
|
962
|
+
// depends on whether P1 sat in a digit group or a Han
|
|
963
|
+
// run — defer the batch front even when P1 lies
|
|
964
|
+
// entirely before the batch.
|
|
965
|
+
cl.resid |= 1;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
(O200kCharClass::Other, _) => {
|
|
969
|
+
cl.o |= chm;
|
|
970
|
+
c.po = 1;
|
|
971
|
+
}
|
|
972
|
+
(O200kCharClass::Whitespace, _) => {
|
|
973
|
+
cl.ws |= chm;
|
|
974
|
+
if e1 > scan {
|
|
975
|
+
cl.resid |= chm;
|
|
976
|
+
}
|
|
977
|
+
let pb = bytes[scan - 1];
|
|
978
|
+
c.ps = u64::from(pb == b' ');
|
|
979
|
+
let nl = pb == b'\r' || pb == b'\n';
|
|
980
|
+
c.pwt = u64::from(pb < 0x80 && pb != b' ' && !nl || pb >= 0x80);
|
|
981
|
+
c.pws = 1;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
c
|
|
985
|
+
};
|
|
986
|
+
|
|
987
|
+
let mut uni = if am.hi != 0 {
|
|
988
|
+
// SAFETY: the batch guard is exactly `classify_uni_o200k`'s
|
|
989
|
+
// contract.
|
|
990
|
+
unsafe { classify_uni_o200k::<HAN>(bytes, scan, am.hi & !cl.cont) }
|
|
991
|
+
} else {
|
|
992
|
+
OUni::default()
|
|
993
|
+
};
|
|
994
|
+
uni.l |= cl.l;
|
|
995
|
+
uni.u |= cl.u;
|
|
996
|
+
uni.cl |= cl.cl;
|
|
997
|
+
uni.n |= cl.n;
|
|
998
|
+
uni.o |= cl.o;
|
|
999
|
+
uni.ws |= cl.ws;
|
|
1000
|
+
uni.cont |= cl.cont;
|
|
1001
|
+
uni.resid |= cl.resid;
|
|
1002
|
+
uni.mk |= cl.mk;
|
|
1003
|
+
uni.han |= cl.han;
|
|
1004
|
+
|
|
1005
|
+
o200k_algebra::<CONTRACTIONS, DIGITS3, SLASH, HAN>(bytes, scan, am, ax, cr, uni)
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/// The o200k family's shared u64 boundary algebra over per-byte class
|
|
1009
|
+
/// masks — `cl100k_family::family_algebra` with the o200k rules: casing
|
|
1010
|
+
/// boundaries inside letter runs, suffix contractions, `[\r\n/]*` punct
|
|
1011
|
+
/// tails. `uni` is all-zero on the pure-ASCII path.
|
|
1012
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
1013
|
+
#[inline(always)]
|
|
1014
|
+
fn o200k_algebra<
|
|
1015
|
+
const CONTRACTIONS: bool,
|
|
1016
|
+
const DIGITS3: bool,
|
|
1017
|
+
const SLASH: bool,
|
|
1018
|
+
const HAN: bool,
|
|
1019
|
+
>(
|
|
1020
|
+
bytes: &[u8],
|
|
1021
|
+
scan: usize,
|
|
1022
|
+
am: AsciiMasks,
|
|
1023
|
+
ax: OAsciiExtra,
|
|
1024
|
+
cr: OCarries,
|
|
1025
|
+
uni: OUni,
|
|
1026
|
+
) -> (u64, u64) {
|
|
1027
|
+
let OCarries {
|
|
1028
|
+
pl,
|
|
1029
|
+
pu,
|
|
1030
|
+
pcl,
|
|
1031
|
+
ps,
|
|
1032
|
+
pwt,
|
|
1033
|
+
po,
|
|
1034
|
+
pws,
|
|
1035
|
+
pd,
|
|
1036
|
+
phan,
|
|
1037
|
+
c2_os,
|
|
1038
|
+
b2b_in,
|
|
1039
|
+
p_abs,
|
|
1040
|
+
force_bad_lead,
|
|
1041
|
+
} = cr;
|
|
1042
|
+
let contm = uni.cont;
|
|
1043
|
+
|
|
1044
|
+
// Effective per-byte classes.
|
|
1045
|
+
let lb = am.l | uni.l;
|
|
1046
|
+
let ub = ax.up | uni.u;
|
|
1047
|
+
let clb = uni.cl;
|
|
1048
|
+
let sb = am.s;
|
|
1049
|
+
let wtb = am.wt | uni.ws;
|
|
1050
|
+
let ob = !(am.l | am.d | am.s | am.wt | am.n | am.hi) | uni.o;
|
|
1051
|
+
let ws_all = sb | wtb | am.n;
|
|
1052
|
+
|
|
1053
|
+
// --- Absorbed `[\r\n/]*` (Kimi `[\r\n]*`) tails -------------------------
|
|
1054
|
+
// Seed: a newline right after a punct byte (a slash after a punct run
|
|
1055
|
+
// is already a run member, so tails always begin with a newline), or
|
|
1056
|
+
// a tail continuing from before the batch. Smear through the tail
|
|
1057
|
+
// class.
|
|
1058
|
+
let tcls = if SLASH { am.n | ax.sl } else { am.n };
|
|
1059
|
+
let abs_seed = (am.n & ((ob << 1) | po)) | (u64::from(p_abs) & tcls);
|
|
1060
|
+
let abs_t = if abs_seed == 0 { 0 } else { smear_up(abs_seed, tcls) };
|
|
1061
|
+
// Absorbed bytes are no longer punct-run members for any boundary rule.
|
|
1062
|
+
let ob_eff = ob & !abs_t;
|
|
1063
|
+
|
|
1064
|
+
// --- Letters -------------------------------------------------------------
|
|
1065
|
+
let len1 = !(contm | uni.lead2 | uni.lead3 | uni.lead4);
|
|
1066
|
+
let c_test = ((ob_eff | sb) << 1) | po | ps; // bit 0: byte scan-1 in O|S
|
|
1067
|
+
let b2back = ((c_test & len1) << 1)
|
|
1068
|
+
| ((c_test & uni.lead2) << 2)
|
|
1069
|
+
| ((c_test & uni.lead3) << 3)
|
|
1070
|
+
| ((c_test & uni.lead4) << 4)
|
|
1071
|
+
| c2_os
|
|
1072
|
+
| b2b_in;
|
|
1073
|
+
let p_l = (lb << 1) | pl;
|
|
1074
|
+
let p_u = (ub << 1) | pu;
|
|
1075
|
+
let p_cl = (clb << 1) | pcl;
|
|
1076
|
+
let p_s = (sb << 1) | ps;
|
|
1077
|
+
let p_wt = (wtb << 1) | pwt;
|
|
1078
|
+
let p_o = (ob_eff << 1) | po;
|
|
1079
|
+
let absorb = p_o & !b2back;
|
|
1080
|
+
// Casing boundary: a strict-upper char after a strict-lower one. (For
|
|
1081
|
+
// ASCII text this is the whole rule; see the module docs.)
|
|
1082
|
+
let p_sl = p_l & !p_u & !p_cl;
|
|
1083
|
+
let b_su = ub & !contm & p_sl;
|
|
1084
|
+
let b_letters =
|
|
1085
|
+
(lb & !contm & !p_l & !p_s & !p_wt & !absorb) | b_su;
|
|
1086
|
+
|
|
1087
|
+
// --- Digits: `\p{N}{1,3}` or `\p{N}` -------------------------------------
|
|
1088
|
+
let b_digits = if DIGITS3 && am.d & (am.d >> 1) != 0 {
|
|
1089
|
+
mask::digit_run_splits3(am.d)
|
|
1090
|
+
} else {
|
|
1091
|
+
am.d
|
|
1092
|
+
};
|
|
1093
|
+
|
|
1094
|
+
// --- Punct: ` ?[^\s\p{L}\p{N}]+[\r\n/]*` ----------------------------------
|
|
1095
|
+
let b_punct = ob_eff & !contm & !p_o & !p_s;
|
|
1096
|
+
|
|
1097
|
+
// --- Bad zones ------------------------------------------------------------
|
|
1098
|
+
let resid = uni.resid;
|
|
1099
|
+
let mut bad = resid | resid << 1 | resid >> 1;
|
|
1100
|
+
// Marks are run-contextual: they, and anything whose boundary rules
|
|
1101
|
+
// can see them (up to two chars back — 4 bytes of lookahead for the
|
|
1102
|
+
// following leads), go to the scalar path.
|
|
1103
|
+
let mk = uni.mk;
|
|
1104
|
+
if mk != 0 {
|
|
1105
|
+
bad |= mk | mk << 1 | mk << 2 | mk << 3 | mk << 4 | mk >> 1;
|
|
1106
|
+
}
|
|
1107
|
+
// A strict-upper char after a caseless letter: phase- and
|
|
1108
|
+
// lookahead-dependent (see the module docs) — scalar.
|
|
1109
|
+
bad |= ub & !contm & ((clb << 1) | pcl);
|
|
1110
|
+
if force_bad_lead {
|
|
1111
|
+
// Unresolved carries: the leading tail-class run (plus the byte
|
|
1112
|
+
// after it) can't be trusted.
|
|
1113
|
+
bad |= smear_up(tcls & 1, tcls) << 1 | 0b11;
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
// --- Whitespace -----------------------------------------------------------
|
|
1117
|
+
let ws_eff = ws_all & !abs_t;
|
|
1118
|
+
|
|
1119
|
+
// Byte-64 lookahead: is the char at the next batch's first byte
|
|
1120
|
+
// non-ws? (See cl100k_family for the full reasoning.)
|
|
1121
|
+
let nb64 = bytes[scan + 64]; // in bounds: scan + 70 <= len
|
|
1122
|
+
let nn64 = if nb64 < 0x80 {
|
|
1123
|
+
!is_ascii_ws(nb64)
|
|
1124
|
+
} else {
|
|
1125
|
+
// SAFETY: the batch guard puts the decode at scan + 64 in bounds.
|
|
1126
|
+
bad >> 63 == 0 && unsafe { mask::nn_at_full(bytes, scan + 64) }
|
|
1127
|
+
};
|
|
1128
|
+
let nn64m = u64::from(nn64).wrapping_neg();
|
|
1129
|
+
|
|
1130
|
+
// An absorbed tail touching the batch end continues iff byte 64 is
|
|
1131
|
+
// tail-class; the next batch's `tail_carries` walkback re-derives the
|
|
1132
|
+
// context either way, so nothing defers here. A ws run touching the
|
|
1133
|
+
// batch end still defers when byte 64 is ws (its last newline may lie
|
|
1134
|
+
// beyond this batch).
|
|
1135
|
+
let nonws = !ws_eff;
|
|
1136
|
+
if ws_eff >> 63 != 0 && !nn64 {
|
|
1137
|
+
if nonws == 0 {
|
|
1138
|
+
return (0, u64::MAX); // whole batch one ws run
|
|
1139
|
+
}
|
|
1140
|
+
let h = 63 - nonws.leading_zeros(); // highest non-ws bit (< 63)
|
|
1141
|
+
bad |= u64::MAX << (h + 1);
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
// A digit run whose `\p{N}{1,3}` phase did not start inside this batch
|
|
1145
|
+
// (continuation from before it, or after a bad zone) defers.
|
|
1146
|
+
if DIGITS3 {
|
|
1147
|
+
let seed = (am.d & (bad << 1)) | (am.d & pd);
|
|
1148
|
+
if seed != 0 {
|
|
1149
|
+
bad |= smear_up(seed, am.d);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// Base rule (NL-free runs; NL runs are overridden below).
|
|
1154
|
+
let ws_leads1 = (am.s | am.wt | am.n) & ws_eff;
|
|
1155
|
+
let ws_leads = (ws_leads1 | uni.w2 | uni.w3) & !abs_t;
|
|
1156
|
+
let p_ws = (ws_eff << 1) | pws;
|
|
1157
|
+
let edge_last = (ws_leads1 & (1 << 63)) | (uni.w2 & (1 << 62)) | (uni.w3 & (1 << 61));
|
|
1158
|
+
let split_ok = (ws_leads1 & (nonws >> 1))
|
|
1159
|
+
| (uni.w2 & (nonws >> 2))
|
|
1160
|
+
| (uni.w3 & (nonws >> 3))
|
|
1161
|
+
| (edge_last & nn64m);
|
|
1162
|
+
let mut b_ws = ws_leads & (!p_ws | split_ok);
|
|
1163
|
+
|
|
1164
|
+
// Override every run containing a (non-absorbed) newline: one token
|
|
1165
|
+
// through the run's last newline, then tail rules.
|
|
1166
|
+
let mut runs_n = am.n & ws_eff & !bad;
|
|
1167
|
+
while runs_n != 0 {
|
|
1168
|
+
let f = runs_n.trailing_zeros();
|
|
1169
|
+
let below_gap = nonws & ((1u64 << f) - 1);
|
|
1170
|
+
let a = if below_gap == 0 { 0 } else { 64 - below_gap.leading_zeros() };
|
|
1171
|
+
let e = (nonws & (u64::MAX << f)).trailing_zeros();
|
|
1172
|
+
let run_mask = (u64::MAX << a) & !u64::MAX.unbounded_shl(e);
|
|
1173
|
+
b_ws &= !run_mask;
|
|
1174
|
+
b_ws |= 1u64 << a;
|
|
1175
|
+
let q = 63 - (am.n & run_mask).leading_zeros(); // last NL in run
|
|
1176
|
+
if (q + 1) < e {
|
|
1177
|
+
b_ws |= 1u64 << (q + 1);
|
|
1178
|
+
let tail = run_mask & (u64::MAX << (q + 1));
|
|
1179
|
+
let tail_leads = ws_leads & tail;
|
|
1180
|
+
b_ws |= 1u64 << (63 - tail_leads.leading_zeros());
|
|
1181
|
+
}
|
|
1182
|
+
runs_n &= !run_mask;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
// --- Han runs (Kimi): `[\p{Han}]+` --------------------------------------
|
|
1186
|
+
// A boundary at every Han-letter lead whose previous char is not a Han
|
|
1187
|
+
// letter. Han numerals/symbols sit in resid/mk bad zones, so any lead
|
|
1188
|
+
// adjacent to those resolves on the scalar path.
|
|
1189
|
+
let b_han = if HAN {
|
|
1190
|
+
uni.han_leads & !((uni.han << 1) | phan)
|
|
1191
|
+
} else {
|
|
1192
|
+
0
|
|
1193
|
+
};
|
|
1194
|
+
|
|
1195
|
+
let mut boundary = b_letters | b_digits | b_punct | b_ws | b_han;
|
|
1196
|
+
|
|
1197
|
+
// --- Contractions: suffix `(?i:'s|'t|'re|'ve|'m|'ll|'d)?` ----------------
|
|
1198
|
+
// An apostrophe right after a letter-run char merges the suffix into
|
|
1199
|
+
// that token and forces a boundary right after it. ('ſ is non-ASCII:
|
|
1200
|
+
// an apostrophe before any non-ASCII char defers.)
|
|
1201
|
+
if CONTRACTIONS {
|
|
1202
|
+
let mut cand = am.ap & boundary & p_l & !bad;
|
|
1203
|
+
let mut last_forced = usize::MAX;
|
|
1204
|
+
while cand != 0 {
|
|
1205
|
+
let i = cand.trailing_zeros() as usize;
|
|
1206
|
+
cand &= cand - 1;
|
|
1207
|
+
if i <= 2 {
|
|
1208
|
+
// The preceding letter could itself end an earlier
|
|
1209
|
+
// contraction that started before the batch — scalar.
|
|
1210
|
+
bad |= 0b111u64 << i;
|
|
1211
|
+
continue;
|
|
1212
|
+
}
|
|
1213
|
+
if i >= 61 {
|
|
1214
|
+
bad |= u64::MAX << i;
|
|
1215
|
+
break;
|
|
1216
|
+
}
|
|
1217
|
+
if i == last_forced {
|
|
1218
|
+
// "x'll'd": the letter before this apostrophe is a
|
|
1219
|
+
// consumed suffix's last char; a new (prefix) match
|
|
1220
|
+
// starts here instead.
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
// The letter before this apostrophe may itself be a consumed
|
|
1224
|
+
// suffix's last char resolved where last_forced can't see it
|
|
1225
|
+
// (a scalar-walked zone like 'ſ, or a fixup before the
|
|
1226
|
+
// batch): locally ambiguous, defer.
|
|
1227
|
+
let p = scan + i;
|
|
1228
|
+
let prev_suffix_possible = (bytes[p - 2] == b'\''
|
|
1229
|
+
&& matches!(bytes[p - 1] | 0x20, b's' | b'd' | b'm' | b't'))
|
|
1230
|
+
|| (p >= 3
|
|
1231
|
+
&& bytes[p - 3] == b'\''
|
|
1232
|
+
&& (matches!(
|
|
1233
|
+
(bytes[p - 2] | 0x20, bytes[p - 1] | 0x20),
|
|
1234
|
+
(b'l', b'l') | (b'v', b'e') | (b'r', b'e')
|
|
1235
|
+
) || (bytes[p - 2] == 0xC5 && bytes[p - 1] == 0xBF)));
|
|
1236
|
+
if prev_suffix_possible {
|
|
1237
|
+
bad |= 0b111u64 << i;
|
|
1238
|
+
continue;
|
|
1239
|
+
}
|
|
1240
|
+
let b1 = bytes[scan + i + 1];
|
|
1241
|
+
if b1 >= 0x80 {
|
|
1242
|
+
bad |= 0b111u64 << i;
|
|
1243
|
+
continue;
|
|
1244
|
+
}
|
|
1245
|
+
let k = match b1 | 0x20 {
|
|
1246
|
+
b's' | b'd' | b'm' | b't' => 2,
|
|
1247
|
+
b'l' if bytes[scan + i + 2] | 0x20 == b'l' => 3,
|
|
1248
|
+
b'v' if bytes[scan + i + 2] | 0x20 == b'e' => 3,
|
|
1249
|
+
b'r' if bytes[scan + i + 2] | 0x20 == b'e' => 3,
|
|
1250
|
+
_ => 0,
|
|
1251
|
+
};
|
|
1252
|
+
if k != 0 {
|
|
1253
|
+
boundary &= !(1u64 << i);
|
|
1254
|
+
boundary &= !(((1u64 << (k - 1)) - 1) << (i + 1));
|
|
1255
|
+
boundary |= 1u64 << (i + k);
|
|
1256
|
+
last_forced = i + k;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
(boundary & !bad, bad)
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
// -----------------------------------------------------------------------
|
|
1265
|
+
// Batch classifiers (per-arch front-ends)
|
|
1266
|
+
// -----------------------------------------------------------------------
|
|
1267
|
+
|
|
1268
|
+
/// Carries for a batch known to have only ASCII in and just before it:
|
|
1269
|
+
/// tail-class prev bytes route through the walkback, everything else
|
|
1270
|
+
/// through the branchless ASCII carries.
|
|
1271
|
+
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
|
1272
|
+
#[inline(always)]
|
|
1273
|
+
fn ascii_batch_carries<const SLASH: bool, const HAN: bool>(bytes: &[u8], scan: usize) -> OCarries {
|
|
1274
|
+
if scan == 0 {
|
|
1275
|
+
OCarries::default()
|
|
1276
|
+
} else if is_tail_byte::<SLASH>(bytes[scan - 1]) {
|
|
1277
|
+
tail_carries::<SLASH, HAN>(bytes, scan)
|
|
1278
|
+
} else {
|
|
1279
|
+
ascii_carries::<SLASH, HAN>(bytes, scan)
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
/// `(usable, bad)` for `bytes[scan..scan+64]` under the o200k-family
|
|
1284
|
+
/// rules — same contract as the cl100k family's `batch_masks`.
|
|
1285
|
+
///
|
|
1286
|
+
/// NEON front-end: classifies the ASCII classes (letter, upper, digit,
|
|
1287
|
+
/// space, whitespace, newline) with movemasks; apostrophe and slash sit
|
|
1288
|
+
/// behind horizontal any-tests. Batches with non-ASCII in or just before
|
|
1289
|
+
/// them take [`o200k_extended_masks`].
|
|
1290
|
+
#[cfg(target_arch = "aarch64")]
|
|
1291
|
+
#[inline]
|
|
1292
|
+
pub(crate) fn batch_masks<
|
|
1293
|
+
const CONTRACTIONS: bool,
|
|
1294
|
+
const DIGITS3: bool,
|
|
1295
|
+
const SLASH: bool,
|
|
1296
|
+
const HAN: bool,
|
|
1297
|
+
>(
|
|
1298
|
+
bytes: &[u8],
|
|
1299
|
+
scan: usize,
|
|
1300
|
+
) -> (u64, u64) {
|
|
1301
|
+
use std::arch::aarch64::*;
|
|
1302
|
+
let len = bytes.len();
|
|
1303
|
+
if scan + 70 > len {
|
|
1304
|
+
// Not enough lookahead for the batch-edge char classification.
|
|
1305
|
+
return (0, u64::MAX);
|
|
1306
|
+
}
|
|
1307
|
+
unsafe {
|
|
1308
|
+
let p = bytes.as_ptr().add(scan);
|
|
1309
|
+
let zero = vdupq_n_u8(0);
|
|
1310
|
+
let mut lv = [zero; 4];
|
|
1311
|
+
let mut uv = [zero; 4];
|
|
1312
|
+
let mut dv = [zero; 4];
|
|
1313
|
+
let mut sv = [zero; 4];
|
|
1314
|
+
let mut wsv = [zero; 4];
|
|
1315
|
+
let mut nv = [zero; 4];
|
|
1316
|
+
let mut hiv = [zero; 4];
|
|
1317
|
+
let mut apv = [zero; 4];
|
|
1318
|
+
let mut slv = [zero; 4];
|
|
1319
|
+
for i in 0..4 {
|
|
1320
|
+
let v = vld1q_u8(p.add(16 * i));
|
|
1321
|
+
let lowered = vorrq_u8(v, vdupq_n_u8(0x20));
|
|
1322
|
+
lv[i] = vcleq_u8(vsubq_u8(lowered, vdupq_n_u8(b'a')), vdupq_n_u8(25));
|
|
1323
|
+
uv[i] = vcleq_u8(vsubq_u8(v, vdupq_n_u8(b'A')), vdupq_n_u8(25));
|
|
1324
|
+
dv[i] = vcleq_u8(vsubq_u8(v, vdupq_n_u8(b'0')), vdupq_n_u8(9));
|
|
1325
|
+
sv[i] = vceqq_u8(v, vdupq_n_u8(b' '));
|
|
1326
|
+
wsv[i] = vorrq_u8(
|
|
1327
|
+
sv[i],
|
|
1328
|
+
vcleq_u8(vsubq_u8(v, vdupq_n_u8(9)), vdupq_n_u8(4)),
|
|
1329
|
+
);
|
|
1330
|
+
nv[i] = vorrq_u8(
|
|
1331
|
+
vceqq_u8(v, vdupq_n_u8(b'\r')),
|
|
1332
|
+
vceqq_u8(v, vdupq_n_u8(b'\n')),
|
|
1333
|
+
);
|
|
1334
|
+
hiv[i] = vcltzq_s8(vreinterpretq_s8_u8(v));
|
|
1335
|
+
apv[i] = vceqq_u8(v, vdupq_n_u8(b'\''));
|
|
1336
|
+
slv[i] = vceqq_u8(v, vdupq_n_u8(b'/'));
|
|
1337
|
+
}
|
|
1338
|
+
let l64 = mask::movemask64(lv[0], lv[1], lv[2], lv[3]);
|
|
1339
|
+
let u64_ = mask::movemask64(uv[0], uv[1], uv[2], uv[3]);
|
|
1340
|
+
let d64 = mask::movemask64(dv[0], dv[1], dv[2], dv[3]);
|
|
1341
|
+
let s64 = mask::movemask64(sv[0], sv[1], sv[2], sv[3]);
|
|
1342
|
+
let wsa = mask::movemask64(wsv[0], wsv[1], wsv[2], wsv[3]);
|
|
1343
|
+
let n64 = mask::movemask64(nv[0], nv[1], nv[2], nv[3]);
|
|
1344
|
+
|
|
1345
|
+
// Apostrophes only matter for the contraction fixup, slashes only
|
|
1346
|
+
// for the tail smear: movemask each lazily.
|
|
1347
|
+
let ap64 = if CONTRACTIONS {
|
|
1348
|
+
let ap_any = vorrq_u8(vorrq_u8(apv[0], apv[1]), vorrq_u8(apv[2], apv[3]));
|
|
1349
|
+
if vmaxvq_u8(ap_any) != 0 {
|
|
1350
|
+
mask::movemask64(apv[0], apv[1], apv[2], apv[3])
|
|
1351
|
+
} else {
|
|
1352
|
+
0
|
|
1353
|
+
}
|
|
1354
|
+
} else {
|
|
1355
|
+
0
|
|
1356
|
+
};
|
|
1357
|
+
let sl64 = if SLASH {
|
|
1358
|
+
let sl_any = vorrq_u8(vorrq_u8(slv[0], slv[1]), vorrq_u8(slv[2], slv[3]));
|
|
1359
|
+
if vmaxvq_u8(sl_any) != 0 {
|
|
1360
|
+
mask::movemask64(slv[0], slv[1], slv[2], slv[3])
|
|
1361
|
+
} else {
|
|
1362
|
+
0
|
|
1363
|
+
}
|
|
1364
|
+
} else {
|
|
1365
|
+
0
|
|
1366
|
+
};
|
|
1367
|
+
|
|
1368
|
+
let am = AsciiMasks {
|
|
1369
|
+
l: l64,
|
|
1370
|
+
d: d64,
|
|
1371
|
+
s: s64,
|
|
1372
|
+
wt: wsa & !s64 & !n64,
|
|
1373
|
+
n: n64,
|
|
1374
|
+
hi: 0,
|
|
1375
|
+
ap: ap64,
|
|
1376
|
+
};
|
|
1377
|
+
let ax = OAsciiExtra { up: u64_, sl: sl64 };
|
|
1378
|
+
|
|
1379
|
+
let hi_any = vorrq_u8(vorrq_u8(hiv[0], hiv[1]), vorrq_u8(hiv[2], hiv[3]));
|
|
1380
|
+
if vmaxvq_u8(hi_any) != 0
|
|
1381
|
+
|| (scan >= 1 && bytes[scan - 1] >= 0x80)
|
|
1382
|
+
|| (scan >= 2 && bytes[scan - 2] >= 0x80)
|
|
1383
|
+
{
|
|
1384
|
+
let mut am = am;
|
|
1385
|
+
am.hi = mask::movemask64(hiv[0], hiv[1], hiv[2], hiv[3]);
|
|
1386
|
+
return o200k_extended_masks::<CONTRACTIONS, DIGITS3, SLASH, HAN>(bytes, scan, am, ax);
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
let cr = ascii_batch_carries::<SLASH, HAN>(bytes, scan);
|
|
1390
|
+
o200k_algebra::<CONTRACTIONS, DIGITS3, SLASH, HAN>(bytes, scan, am, ax, cr, OUni::default())
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
/// x86-64 front-end: same contract as the NEON `batch_masks` above,
|
|
1395
|
+
/// monomorphized on the SIMD tier (see `MaskScheme::batch_masks_x86`,
|
|
1396
|
+
/// whose provided `batch_masks` supplies the runtime-dispatched form).
|
|
1397
|
+
/// `#[inline(always)]` (with no `target_feature` of its own) so the body
|
|
1398
|
+
/// fuses into whichever feature region calls it — LLVM's cost model
|
|
1399
|
+
/// declined to inline the previous `#[target_feature]` form into the
|
|
1400
|
+
/// tier-monomorphized fill wrappers and left a call per 64-byte batch.
|
|
1401
|
+
///
|
|
1402
|
+
/// # Safety
|
|
1403
|
+
///
|
|
1404
|
+
/// The selected tier must have been runtime-detected
|
|
1405
|
+
/// ([`mask::avx512_scanner_available`] /
|
|
1406
|
+
/// [`mask::avx2_scanner_available`]).
|
|
1407
|
+
#[cfg(target_arch = "x86_64")]
|
|
1408
|
+
#[inline(always)]
|
|
1409
|
+
pub(crate) unsafe fn batch_masks_x86<
|
|
1410
|
+
const AVX512: bool,
|
|
1411
|
+
const CONTRACTIONS: bool,
|
|
1412
|
+
const DIGITS3: bool,
|
|
1413
|
+
const SLASH: bool,
|
|
1414
|
+
const HAN: bool,
|
|
1415
|
+
>(
|
|
1416
|
+
bytes: &[u8],
|
|
1417
|
+
scan: usize,
|
|
1418
|
+
) -> (u64, u64) {
|
|
1419
|
+
let len = bytes.len();
|
|
1420
|
+
if scan + 70 > len {
|
|
1421
|
+
return (0, u64::MAX);
|
|
1422
|
+
}
|
|
1423
|
+
let (am, ax) = if AVX512 {
|
|
1424
|
+
// SAFETY: the caller detected the AVX-512 tier (fn contract).
|
|
1425
|
+
unsafe { (mask::ascii_masks_avx512(bytes, scan), ascii_extra_avx512(bytes, scan)) }
|
|
1426
|
+
} else {
|
|
1427
|
+
// SAFETY: the caller detected the AVX2 tier (fn contract).
|
|
1428
|
+
unsafe { (mask::ascii_masks_avx2(bytes, scan), ascii_extra_avx2(bytes, scan)) }
|
|
1429
|
+
};
|
|
1430
|
+
if am.hi != 0
|
|
1431
|
+
|| (scan >= 1 && bytes[scan - 1] >= 0x80)
|
|
1432
|
+
|| (scan >= 2 && bytes[scan - 2] >= 0x80)
|
|
1433
|
+
{
|
|
1434
|
+
// SAFETY: both detected tiers include the BMI1/BMI2/LZCNT/POPCNT
|
|
1435
|
+
// bit features `o200k_extended_masks` re-declares (fn contract).
|
|
1436
|
+
return unsafe {
|
|
1437
|
+
o200k_extended_masks::<CONTRACTIONS, DIGITS3, SLASH, HAN>(bytes, scan, am, ax)
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
let cr = ascii_batch_carries::<SLASH, HAN>(bytes, scan);
|
|
1441
|
+
o200k_algebra::<CONTRACTIONS, DIGITS3, SLASH, HAN>(bytes, scan, am, ax, cr, OUni::default())
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
/// The strict-uppercase and slash masks for `bytes[scan..scan+64]`,
|
|
1445
|
+
/// AVX-512 tier.
|
|
1446
|
+
#[cfg(target_arch = "x86_64")]
|
|
1447
|
+
#[target_feature(enable = "avx512f,avx512bw,avx512vl,bmi1,bmi2,lzcnt,popcnt")]
|
|
1448
|
+
#[inline]
|
|
1449
|
+
fn ascii_extra_avx512(bytes: &[u8], scan: usize) -> OAsciiExtra {
|
|
1450
|
+
use std::arch::x86_64::*;
|
|
1451
|
+
unsafe {
|
|
1452
|
+
let v = _mm512_loadu_si512(bytes.as_ptr().add(scan) as *const _);
|
|
1453
|
+
let up = _mm512_cmple_epu8_mask(
|
|
1454
|
+
_mm512_sub_epi8(v, _mm512_set1_epi8(b'A' as i8)),
|
|
1455
|
+
_mm512_set1_epi8(25),
|
|
1456
|
+
);
|
|
1457
|
+
let sl = _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8(b'/' as i8));
|
|
1458
|
+
OAsciiExtra { up, sl }
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
/// The strict-uppercase and slash masks for `bytes[scan..scan+64]`,
|
|
1463
|
+
/// AVX2 tier. `#[inline(never)]` for the same vector-domain reason as
|
|
1464
|
+
/// [`mask::ascii_masks_avx2`].
|
|
1465
|
+
#[cfg(target_arch = "x86_64")]
|
|
1466
|
+
#[target_feature(enable = "avx2,bmi1,bmi2,lzcnt,popcnt")]
|
|
1467
|
+
#[inline(never)]
|
|
1468
|
+
fn ascii_extra_avx2(bytes: &[u8], scan: usize) -> OAsciiExtra {
|
|
1469
|
+
use std::arch::x86_64::*;
|
|
1470
|
+
unsafe {
|
|
1471
|
+
let le = |v: __m256i, lim: __m256i| -> __m256i {
|
|
1472
|
+
_mm256_cmpeq_epi8(_mm256_min_epu8(v, lim), v)
|
|
1473
|
+
};
|
|
1474
|
+
let mm = |m0: __m256i, m1: __m256i| -> u64 {
|
|
1475
|
+
(_mm256_movemask_epi8(m0) as u32 as u64)
|
|
1476
|
+
| ((_mm256_movemask_epi8(m1) as u32 as u64) << 32)
|
|
1477
|
+
};
|
|
1478
|
+
let p = bytes.as_ptr().add(scan);
|
|
1479
|
+
let v0 = _mm256_loadu_si256(p as *const _);
|
|
1480
|
+
let v1 = _mm256_loadu_si256(p.add(32) as *const _);
|
|
1481
|
+
let ca = _mm256_set1_epi8(b'A' as i8);
|
|
1482
|
+
let c25 = _mm256_set1_epi8(25);
|
|
1483
|
+
let up = mm(
|
|
1484
|
+
le(_mm256_sub_epi8(v0, ca), c25),
|
|
1485
|
+
le(_mm256_sub_epi8(v1, ca), c25),
|
|
1486
|
+
);
|
|
1487
|
+
let slc = _mm256_set1_epi8(b'/' as i8);
|
|
1488
|
+
let sl = mm(_mm256_cmpeq_epi8(v0, slc), _mm256_cmpeq_epi8(v1, slc));
|
|
1489
|
+
OAsciiExtra { up, sl }
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
#[cfg(test)]
|
|
1494
|
+
mod tests {
|
|
1495
|
+
use crate::pretokenize::fast::kimi::KimiScheme;
|
|
1496
|
+
use crate::pretokenize::fast::mask::{MaskScheme, MaskState};
|
|
1497
|
+
use crate::pretokenize::fast::nemotron::NemotronScheme;
|
|
1498
|
+
use crate::pretokenize::fast::o200k::O200kScheme;
|
|
1499
|
+
|
|
1500
|
+
fn scalar_tokens<S: MaskScheme>(bytes: &[u8]) -> Vec<Vec<u8>> {
|
|
1501
|
+
let mut pos = 0;
|
|
1502
|
+
let mut out = vec![];
|
|
1503
|
+
while pos < bytes.len() {
|
|
1504
|
+
let e = S::advance(bytes, pos);
|
|
1505
|
+
out.push(bytes[pos..e].to_vec());
|
|
1506
|
+
pos = e;
|
|
1507
|
+
}
|
|
1508
|
+
out
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
fn mask_tokens<S: MaskScheme>(bytes: &[u8]) -> Vec<Vec<u8>> {
|
|
1512
|
+
let mut st = MaskState::new(0);
|
|
1513
|
+
let mut out = vec![];
|
|
1514
|
+
while let Some((s, e)) = st.next_span::<S>(bytes) {
|
|
1515
|
+
out.push(bytes[s..e].to_vec());
|
|
1516
|
+
}
|
|
1517
|
+
out
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
/// Scalar-vs-mask token streams for all family schemes.
|
|
1521
|
+
#[track_caller]
|
|
1522
|
+
fn check_all(buf: &[u8]) {
|
|
1523
|
+
for (name, a, b) in [
|
|
1524
|
+
("o200k", scalar_tokens::<O200kScheme>(buf), mask_tokens::<O200kScheme>(buf)),
|
|
1525
|
+
("nemotron", scalar_tokens::<NemotronScheme>(buf), mask_tokens::<NemotronScheme>(buf)),
|
|
1526
|
+
("kimi", scalar_tokens::<KimiScheme>(buf), mask_tokens::<KimiScheme>(buf)),
|
|
1527
|
+
] {
|
|
1528
|
+
if a != b {
|
|
1529
|
+
let i = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
|
|
1530
|
+
panic!(
|
|
1531
|
+
"{name} diverged at token {i} on {:?}\n scalar: {:?}\n mask: {:?}",
|
|
1532
|
+
String::from_utf8_lossy(buf),
|
|
1533
|
+
a.get(i).map(|t| String::from_utf8_lossy(t).into_owned()),
|
|
1534
|
+
b.get(i).map(|t| String::from_utf8_lossy(t).into_owned()),
|
|
1535
|
+
);
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
/// Alignment-preserving shrink: replace chars with 'a' and trim the
|
|
1541
|
+
/// tail while the buffer still diverges, then report the minimum.
|
|
1542
|
+
fn shrink_and_report(bytes: &[u8]) -> String {
|
|
1543
|
+
let fails = |b: &[u8]| {
|
|
1544
|
+
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check_all(b))).is_err()
|
|
1545
|
+
};
|
|
1546
|
+
let mut buf = bytes.to_vec();
|
|
1547
|
+
let mut changed = true;
|
|
1548
|
+
while changed {
|
|
1549
|
+
changed = false;
|
|
1550
|
+
let mut i = 0;
|
|
1551
|
+
while i < buf.len() {
|
|
1552
|
+
let mut l = 1;
|
|
1553
|
+
if buf[i] >= 0xC2 {
|
|
1554
|
+
l = if buf[i] < 0xE0 { 2 } else if buf[i] < 0xF0 { 3 } else { 4 };
|
|
1555
|
+
}
|
|
1556
|
+
let saved: Vec<u8> = buf[i..i + l].to_vec();
|
|
1557
|
+
if saved != vec![b'a'; l] {
|
|
1558
|
+
for j in 0..l {
|
|
1559
|
+
buf[i + j] = b'a';
|
|
1560
|
+
}
|
|
1561
|
+
if fails(&buf) {
|
|
1562
|
+
changed = true;
|
|
1563
|
+
} else {
|
|
1564
|
+
buf[i..i + l].copy_from_slice(&saved);
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
i += l;
|
|
1568
|
+
}
|
|
1569
|
+
while buf.len() > 1 && buf[buf.len() - 1] == b'a' && fails(&buf[..buf.len() - 1]) {
|
|
1570
|
+
buf.pop();
|
|
1571
|
+
changed = true;
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
let mut report = format!("(len {}) {:?}", buf.len(), String::from_utf8_lossy(&buf));
|
|
1575
|
+
for (name, a, b) in [
|
|
1576
|
+
("o200k", scalar_tokens::<O200kScheme>(&buf), mask_tokens::<O200kScheme>(&buf)),
|
|
1577
|
+
(
|
|
1578
|
+
"nemotron",
|
|
1579
|
+
scalar_tokens::<NemotronScheme>(&buf),
|
|
1580
|
+
mask_tokens::<NemotronScheme>(&buf),
|
|
1581
|
+
),
|
|
1582
|
+
("kimi", scalar_tokens::<KimiScheme>(&buf), mask_tokens::<KimiScheme>(&buf)),
|
|
1583
|
+
] {
|
|
1584
|
+
if a != b {
|
|
1585
|
+
let i = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
|
|
1586
|
+
report.push_str(&format!(
|
|
1587
|
+
"\n {name} token {i}: scalar {:?} mask {:?}",
|
|
1588
|
+
a.get(i).map(|t| String::from_utf8_lossy(t).into_owned()),
|
|
1589
|
+
b.get(i).map(|t| String::from_utf8_lossy(t).into_owned()),
|
|
1590
|
+
));
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
report
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
/// Crafted cases, padded so they cross the batch (not scalar-tail) path.
|
|
1597
|
+
#[test]
|
|
1598
|
+
fn o200k_family_mask_matches_scalar_padded_cases() {
|
|
1599
|
+
let pad = "The quick brown fox jumps over the lazy dog again and again. ";
|
|
1600
|
+
let cases = [
|
|
1601
|
+
"January 24, 2015 and 12345678 numbers 1 22 333 4444",
|
|
1602
|
+
"don't DON'T they'Ll 'sound 'lx x'y '' ' \u{2019}s x'll'd don't's",
|
|
1603
|
+
"camelCase HTTPResponse PascalCase aB ABc parseHTMLDocument iOS",
|
|
1604
|
+
"!hello !Hello !!hello ?!x a-b ... !!!\n\nnext",
|
|
1605
|
+
"paths /usr/bin/env a/b a//b http://x.com/y .\n//x !\n/\n/x",
|
|
1606
|
+
"//\n/ x/\n x\n/ \n/ don't\n don'\n",
|
|
1607
|
+
"tabs\tand\nnewlines\r\n mixed \n runs \n\n\n deep",
|
|
1608
|
+
"hi!\n\ndef hi !!\n\nabc \"quoted\" (paren)",
|
|
1609
|
+
"caf\u{e9} r\u{e9}sum\u{e9} \u{201c}word\u{201d} \u{2014}dash\u{2013} \u{00a0}nbsp",
|
|
1610
|
+
"CAF\u{c9} \u{2003}em \u{2009}thin\u{2028}ls x\u{e9}\u{e9}y \u{416}dz Z\u{5bf}\u{416}dz",
|
|
1611
|
+
"price: $5.99! 100,000.00 3.14159 2nd 3rd 4th",
|
|
1612
|
+
"a\u{2028}b a\u{2028}\n \n\n\t x \n\n ",
|
|
1613
|
+
"mixed 1\u{662}3x \u{661}\u{662}\u{663} arabic",
|
|
1614
|
+
"\u{65e5}\u{672c}\u{8a9e}ABC abc\u{65e5}\u{672c}Def \u{416}\u{416}dz",
|
|
1615
|
+
"e\u{301}f !!\u{301}x '\u{301}s x\u{301}'s A\u{301}B",
|
|
1616
|
+
// A mark's contextual class reaching a boundary past the ±4
|
|
1617
|
+
// bad smear (4-byte punct char in between): relies on the
|
|
1618
|
+
// walker's scalar-overrun masking.
|
|
1619
|
+
"a\u{301}\u{1f389}b !\u{301}\u{1f389}x a\u{301}\u{1f389}'s a\u{301}\n\n\n\n/x",
|
|
1620
|
+
];
|
|
1621
|
+
for case in cases {
|
|
1622
|
+
for lead in [0usize, 1, 37, 61, 62, 63, 64, 65] {
|
|
1623
|
+
let mut buf = pad.as_bytes().repeat(4)[..pad.len() * 2 + lead].to_vec();
|
|
1624
|
+
buf.extend_from_slice(case.as_bytes());
|
|
1625
|
+
buf.extend_from_slice(pad.as_bytes());
|
|
1626
|
+
buf.extend_from_slice(case.as_bytes());
|
|
1627
|
+
check_all(&buf);
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1632
|
+
/// Differential fuzz across both family schemes.
|
|
1633
|
+
#[test]
|
|
1634
|
+
fn o200k_family_mask_matches_scalar_fuzz() {
|
|
1635
|
+
let pieces: &[&str] = &[
|
|
1636
|
+
"a", "B", "z", "9", "0", " ", " ", "\n", "\t", "\r\n", "\r", "'", "'s", "'LL",
|
|
1637
|
+
"'t", "!", ".", ",", "(", "/", "//", "/\n", "\n/", "é", "É", "ß", "日", "🎉",
|
|
1638
|
+
"\u{00A0}", "\u{2003}", "word", "Word", "WORD", "camelCase", "12", "1234", "’",
|
|
1639
|
+
"“", "”", "–", "—", "…", "\u{2009}", "\u{200B}", "\u{2028}", "\u{202F}", "×",
|
|
1640
|
+
"÷", "«", "µ", "café", "éé", "naïve", "Α", "α", "а", "А", "Ж", "ж", "Dž", "\n\n",
|
|
1641
|
+
"!x", "!X", "\tx", " x", " X", "?!", "\u{301}", "ſ", "'ſ", "'\u{301}",
|
|
1642
|
+
"\u{661}\u{662}", "\u{FF11}", "क", "\u{940}", "\u{1D54F}", "€", "™",
|
|
1643
|
+
"…\u{2028}", "AxB", "ABc", "aB", "\u{416}dz", "x'", "n't",
|
|
1644
|
+
// Han classes (Kimi): letters, numerals (Nl), symbols (So/Mc)
|
|
1645
|
+
"中", "中文", "々", "〆", "𠀀", "〇", "〡", "㆒", "⼀", "⺀",
|
|
1646
|
+
"\u{16FF0}", "中's", "1〇", "中\n", "!⼀", "中⼀",
|
|
1647
|
+
];
|
|
1648
|
+
let mut state = 0x243F6A8885A308D3u64;
|
|
1649
|
+
let mut rng = move || {
|
|
1650
|
+
state ^= state << 13;
|
|
1651
|
+
state ^= state >> 7;
|
|
1652
|
+
state ^= state << 17;
|
|
1653
|
+
state
|
|
1654
|
+
};
|
|
1655
|
+
for round in 0..4000 {
|
|
1656
|
+
let target = 80 + (round % 400);
|
|
1657
|
+
let mut buf = Vec::new();
|
|
1658
|
+
while buf.len() < target {
|
|
1659
|
+
buf.extend_from_slice(pieces[(rng() % pieces.len() as u64) as usize].as_bytes());
|
|
1660
|
+
}
|
|
1661
|
+
let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check_all(&buf)))
|
|
1662
|
+
.is_ok();
|
|
1663
|
+
if !ok {
|
|
1664
|
+
panic!(
|
|
1665
|
+
"round {round} diverged; minimal case: {}",
|
|
1666
|
+
shrink_and_report(&buf)
|
|
1667
|
+
);
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
#[cfg(test)]
|
|
1674
|
+
mod owt_tests {
|
|
1675
|
+
use crate::pretokenize::fast::kimi::KimiScheme;
|
|
1676
|
+
use crate::pretokenize::fast::mask::{MaskScheme, MaskState};
|
|
1677
|
+
use crate::pretokenize::fast::nemotron::NemotronScheme;
|
|
1678
|
+
use crate::pretokenize::fast::o200k::O200kScheme;
|
|
1679
|
+
|
|
1680
|
+
fn check_streaming<S: MaskScheme>(bytes: &[u8], scheme: &str) {
|
|
1681
|
+
let mut st = MaskState::new(0);
|
|
1682
|
+
let mut pos = 0usize;
|
|
1683
|
+
let mut idx = 0usize;
|
|
1684
|
+
while pos < bytes.len() {
|
|
1685
|
+
let scalar_end = S::advance(bytes, pos);
|
|
1686
|
+
match st.next_span::<S>(bytes) {
|
|
1687
|
+
Some((s, e)) => assert!(
|
|
1688
|
+
s == pos && e == scalar_end,
|
|
1689
|
+
"{scheme} diverged at token {idx} (byte {pos}): scalar {pos}..{scalar_end} \
|
|
1690
|
+
mask {s}..{e}: {:?} vs {:?}",
|
|
1691
|
+
String::from_utf8_lossy(&bytes[pos..scalar_end]),
|
|
1692
|
+
String::from_utf8_lossy(&bytes[s..e]),
|
|
1693
|
+
),
|
|
1694
|
+
None => panic!("{scheme} ended early at token {idx} (byte {pos})"),
|
|
1695
|
+
}
|
|
1696
|
+
pos = scalar_end;
|
|
1697
|
+
idx += 1;
|
|
1698
|
+
}
|
|
1699
|
+
assert!(st.next_span::<S>(bytes).is_none(), "{scheme} produced extra tokens");
|
|
1700
|
+
eprintln!("{scheme}: all {idx} tokens match");
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
fn check_streaming_all(bytes: &[u8]) {
|
|
1704
|
+
check_streaming::<O200kScheme>(bytes, "o200k");
|
|
1705
|
+
check_streaming::<NemotronScheme>(bytes, "nemotron");
|
|
1706
|
+
check_streaming::<KimiScheme>(bytes, "kimi");
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
/// 100 MB of OWT, mask vs scalar.
|
|
1710
|
+
#[test]
|
|
1711
|
+
#[ignore]
|
|
1712
|
+
fn o200k_family_mask_matches_scalar_owt() {
|
|
1713
|
+
let path = std::env::home_dir().unwrap().join("data/owt_train.txt");
|
|
1714
|
+
use std::io::Read;
|
|
1715
|
+
let f = std::fs::File::open(&path).unwrap();
|
|
1716
|
+
let mut input = Vec::new();
|
|
1717
|
+
f.take(100_000_000).read_to_end(&mut input).unwrap();
|
|
1718
|
+
while !input.is_empty() && std::str::from_utf8(&input).is_err() {
|
|
1719
|
+
input.pop();
|
|
1720
|
+
}
|
|
1721
|
+
check_streaming_all(&input);
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/// Full-OWT (~12 GB) mask-vs-scalar differential for both schemes.
|
|
1725
|
+
#[test]
|
|
1726
|
+
#[ignore = "reads the full ~12 GB OWT file"]
|
|
1727
|
+
fn o200k_family_mask_matches_scalar_owt_full() {
|
|
1728
|
+
let path = std::env::home_dir().unwrap().join("data/owt_train.txt");
|
|
1729
|
+
let input = std::fs::read(&path).expect("Could not read ~/data/owt_train.txt");
|
|
1730
|
+
eprintln!("loaded {} bytes", input.len());
|
|
1731
|
+
check_streaming_all(&input);
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
|