Skip to content

Commit 212d3af

Browse files
committed
_sre: drive an all-ASCII str subject over its bytes
with_sre_str handed every str subject to the &Wtf8 drive, which answers count() by counting every code point and create_cursor(n) by stepping over the first n. Both run once per Request, so a scan that restarts at successive positions walked the subject again on every call: finditer over an ASCII subject of n tokens was quadratic in n. PyStr already records whether it is ASCII -- StrKind is decided when the string is built -- and for ASCII a character index is a byte index, so the &[u8] drive's cursor arithmetic already applies: count() is the byte length and create_cursor() is a pointer offset. Add AsciiStr, which delegates every StrDrive method to that impl and differs only in slice(), which reslices the span and returns str rather than bytes. Matching is unaffected: StrDrive carries no unicode semantics, because the engine keys every unicode decision on the compiled pattern's opcode rather than on the subject type. Also bind the subject once in with_sre_str, so callers passing a temporary (`&x.clone()`) build it once rather than per arm. finditer over an ASCII subject, n tokens, this machine: n before after 5000 41.60ms 1.37ms 10000 217.30ms 2.68ms 20000 1206.28ms 5.17ms 40000 5016.65ms 10.31ms Per-doubling x5.22/x5.55/x4.16 becomes x1.95/x1.93/x1.99. Collecting m.group(0) for every match goes 5061.02ms -> 17.80ms at n=40000. test.test_re is unchanged at 166 tests, OK (skipped=14, expected failures=6), and a 2731-line differential over the is_ascii() boundary -- findall, finditer spans and groups, sub, split, match, search, fullmatch across subjects that are empty, ASCII, non-ASCII, or mixed -- is byte-identical to CPython 3.14.6. Introducing an off-by-one in AsciiStr::slice moves 1224 of those lines, so the comparison reaches the new code. Assisted-by: Claude
1 parent 3a6aa9b commit 212d3af

1 file changed

Lines changed: 97 additions & 5 deletions

File tree

‎crates/vm/src/stdlib/_sre.rs‎

Lines changed: 97 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ mod _sre {
2222
use itertools::Itertools;
2323
use num_traits::ToPrimitive;
2424
use rustpython_sre_engine::{
25-
Request, SearchIter, SreFlag, State, StrDrive,
25+
Request, SearchIter, SreFlag, State, StrDrive, StringCursor,
2626
string::{lower_ascii, lower_unicode},
2727
};
2828

@@ -83,6 +83,72 @@ mod _sre {
8383
}
8484
}
8585

86+
/// An all-ASCII `str` subject, driven over its bytes.
87+
///
88+
/// For ASCII a character index *is* a byte index, so `&[u8]`'s cursor
89+
/// arithmetic is already the right arithmetic: `count` is the byte length
90+
/// and `create_cursor` is a pointer offset. The `&Wtf8` drive has to count
91+
/// code points from the start of the subject to answer either, once per
92+
/// `Request`, which makes a scan that restarts at successive positions --
93+
/// `finditer`, or `re` module functions called in a loop -- walk the
94+
/// subject again on every call.
95+
///
96+
/// Matching is unaffected: `StrDrive` carries no unicode semantics of its
97+
/// own, because the engine keys every unicode decision on the compiled
98+
/// pattern's opcode rather than on the subject type. Only `slice` differs
99+
/// from the `&[u8]` impl, to hand back `str` instead of `bytes`.
100+
#[derive(Clone, Copy)]
101+
struct AsciiStr<'a>(&'a [u8]);
102+
103+
impl StrDrive for AsciiStr<'_> {
104+
fn count(&self) -> usize {
105+
<&[u8] as StrDrive>::count(&self.0)
106+
}
107+
108+
fn create_cursor(&self, n: usize) -> StringCursor {
109+
<&[u8] as StrDrive>::create_cursor(&self.0, n)
110+
}
111+
112+
fn adjust_cursor(&self, cursor: &mut StringCursor, n: usize) {
113+
<&[u8] as StrDrive>::adjust_cursor(&self.0, cursor, n)
114+
}
115+
116+
fn advance(cursor: &mut StringCursor) -> u32 {
117+
<&[u8] as StrDrive>::advance(cursor)
118+
}
119+
120+
fn peek(cursor: &StringCursor) -> u32 {
121+
<&[u8] as StrDrive>::peek(cursor)
122+
}
123+
124+
fn skip(cursor: &mut StringCursor, n: usize) {
125+
<&[u8] as StrDrive>::skip(cursor, n)
126+
}
127+
128+
fn back_advance(cursor: &mut StringCursor) -> u32 {
129+
<&[u8] as StrDrive>::back_advance(cursor)
130+
}
131+
132+
fn back_peek(cursor: &StringCursor) -> u32 {
133+
<&[u8] as StrDrive>::back_peek(cursor)
134+
}
135+
136+
fn back_skip(cursor: &mut StringCursor, n: usize) {
137+
<&[u8] as StrDrive>::back_skip(cursor, n)
138+
}
139+
}
140+
141+
impl SreStr for AsciiStr<'_> {
142+
fn slice(&self, start: usize, end: usize, vm: &VirtualMachine) -> PyObjectRef {
143+
let end = end.min(self.0.len());
144+
let start = start.min(end);
145+
// The subject is ASCII, so any span of it is valid UTF-8 and the
146+
// span is a reslice rather than a walk from the subject's start.
147+
let s = str::from_utf8(&self.0[start..end]).expect("ascii subject");
148+
vm.ctx.new_str(s).into()
149+
}
150+
}
151+
86152
#[pyfunction]
87153
fn compile(
88154
pattern: PyObjectRef,
@@ -200,13 +266,18 @@ mod _sre {
200266
}
201267

202268
macro_rules! with_sre_str {
203-
($pattern:expr, $string:expr, $vm:expr, $f:expr) => {
269+
($pattern:expr, $string:expr, $vm:expr, $f:expr) => {{
270+
// Bind once: the branches only borrow the subject, and callers pass
271+
// a temporary (`&x.clone()`) that would otherwise be rebuilt per arm.
272+
let subject = $string;
204273
if $pattern.isbytes {
205-
Pattern::with_bytes($string, $vm, $f)
274+
Pattern::with_bytes(subject, $vm, $f)
275+
} else if Pattern::is_ascii_str(subject) {
276+
Pattern::with_ascii_str(subject, $vm, $f)
206277
} else {
207-
Pattern::with_str($string, $vm, $f)
278+
Pattern::with_str(subject, $vm, $f)
208279
}
209-
};
280+
}};
210281
}
211282

212283
#[pyclass(with(Hashable, Comparable, Representable), flags(HAS_WEAKREF))]
@@ -221,6 +292,27 @@ mod _sre {
221292
f(string.as_wtf8())
222293
}
223294

295+
/// Whether a `str` subject can take the [`AsciiStr`] drive.
296+
///
297+
/// `PyStr` already knows: `StrKind` is decided when the string is
298+
/// built, so this is a field load rather than a scan. A non-`str`
299+
/// argument answers `false` and is reported by [`Self::with_str`].
300+
fn is_ascii_str(string: &PyObject) -> bool {
301+
string
302+
.downcast_ref::<PyStr>()
303+
.is_some_and(|s| s.kind().is_ascii())
304+
}
305+
306+
fn with_ascii_str<F, R>(string: &PyObject, vm: &VirtualMachine, f: F) -> PyResult<R>
307+
where
308+
F: FnOnce(AsciiStr<'_>) -> PyResult<R>,
309+
{
310+
let string = string.downcast_ref::<PyStr>().ok_or_else(|| {
311+
vm.new_type_error(format!("expected string got '{}'", string.class()))
312+
})?;
313+
f(AsciiStr(string.as_wtf8().as_bytes()))
314+
}
315+
224316
fn with_bytes<F, R>(string: &PyObject, vm: &VirtualMachine, f: F) -> PyResult<R>
225317
where
226318
F: FnOnce(&[u8]) -> PyResult<R>,

0 commit comments

Comments
 (0)