Debian Codegraph @

third_party/rust/regex-automata/src/dfa/accel.rs

raw
1 // This module defines some core types for dealing with accelerated DFA states.
2 // Briefly, a DFA state can be "accelerated" if all of its transitions except
3 // for a few loop back to itself. This directly implies that the only way out
4 // of such a state is if a byte corresponding to one of those non-loopback
5 // transitions is found. Such states are often found in simple repetitions in
6 // non-Unicode regexes. For example, consider '(?-u)[^a]+a'. We can look at its
7 // DFA with regex-cli:
8 //
9 // $ regex-cli debug dfa dense '(?-u)[^a]+a' -BbC
10 // dense::DFA(
11 // D 000000:
12 // Q 000001:
13 // *000002:
14 // A 000003: \x00-` => 3, a => 5, b-\xFF => 3
15 // >000004: \x00-` => 3, a => 4, b-\xFF => 3
16 // 000005: \x00-\xFF => 2, EOI => 2
17 // )
18 //
19 // In particular, state 3 is accelerated (shown via the 'A' indicator) since
20 // the only way to leave that state once entered is to see an 'a' byte. If
21 // there is a long run of non-'a' bytes, then using something like 'memchr'
22 // to find the next 'a' byte can be significantly faster than just using the
23 // standard byte-at-a-time state machine.
24 //
25 // Unfortunately, this optimization rarely applies when Unicode is enabled.
26 // For example, patterns like '[^a]' don't actually match any byte that isn't
27 // 'a', but rather, any UTF-8 encoding of a Unicode scalar value that isn't
28 // 'a'. This makes the state machine much more complex---far beyond a single
29 // state---and removes the ability to easily accelerate it. (Because if the
30 // machine sees a non-UTF-8 sequence, then the machine won't match through it.)
31 //
32 // In practice, we only consider accelerating states that have 3 or fewer
33 // non-loop transitions. At a certain point, you get diminishing returns, but
34 // also because that's what the memchr crate supports. The structures below
35 // hard-code this assumption and provide (de)serialization APIs for use inside
36 // a DFA.
37 //
38 // And finally, note that there is some trickery involved in making it very
39 // fast to not only check whether a state is accelerated at search time, but
40 // also to access the bytes to search for to implement the acceleration itself.
41 // dfa/special.rs provides more detail, but the short story is that all
42 // accelerated states appear contiguously in a DFA. This means we can represent
43 // the ID space of all accelerated DFA states with a single range. So given
44 // a state ID, we can determine whether it's accelerated via
45 //
46 // min_accel_id <= id <= max_accel_id
47 //
48 // And find its corresponding accelerator with:
49 //
50 // accels.get((id - min_accel_id) / dfa_stride)
51
52 #[cfg(feature = "dfa-build")]
53 use alloc::{vec, vec::Vec};
54
55 use crate::util::{
56 int::Pointer,
57 memchr,
58 wire::{self, DeserializeError, Endian, SerializeError},
59 };
60
61 /// The base type used to represent a collection of accelerators.
62 ///
63 /// While an `Accel` is represented as a fixed size array of bytes, a
64 /// *collection* of `Accel`s (called `Accels`) is represented internally as a
65 /// slice of u32. While it's a bit unnatural to do this and costs us a bit of
66 /// fairly low-risk not-safe code, it lets us remove the need for a second type
67 /// parameter in the definition of dense::DFA. (Which really wants everything
68 /// to be a slice of u32.)
69 type AccelTy = u32;
70
71 /// The size of the unit of representation for accelerators.
72 ///
73 /// ACCEL_CAP *must* be a multiple of this size.
74 const ACCEL_TY_SIZE: usize = core::mem::size_of::<AccelTy>();
75
76 /// The maximum length in bytes that a single Accel can be. This is distinct
77 /// from the capacity of an accelerator in that the length represents only the
78 /// bytes that should be read.
79 const ACCEL_LEN: usize = 4;
80
81 /// The capacity of each accelerator, in bytes. We set this to 8 since it's a
82 /// multiple of 4 (our ID size) and because it gives us a little wiggle room
83 /// if we want to support more accel bytes in the future without a breaking
84 /// change.
85 ///
86 /// This MUST be a multiple of ACCEL_TY_SIZE.
87 const ACCEL_CAP: usize = 8;
88
89 /// Search for between 1 and 3 needle bytes in the given haystack, starting the
90 /// search at the given position. If `needles` has a length other than 1-3,
91 /// then this panics.
92 #[cfg_attr(feature = "perf-inline", inline(always))]
93 pub(crate) fn find_fwd(
94 needles: &[u8],
95 haystack: &[u8],
96 at: usize,
97 ) -> Option<usize> {
98 let bs = needles;
99 let i = match needles.len() {
100 1 => memchr::memchr(bs[0], &haystack[at..])?,
101 2 => memchr::memchr2(bs[0], bs[1], &haystack[at..])?,
102 3 => memchr::memchr3(bs[0], bs[1], bs[2], &haystack[at..])?,
103 0 => panic!("cannot find with empty needles"),
104 n => panic!("invalid needles length: {}", n),
105 };
106 Some(at + i)
107 }
108
109 /// Search for between 1 and 3 needle bytes in the given haystack in reverse,
110 /// starting the search at the given position. If `needles` has a length other
111 /// than 1-3, then this panics.
112 #[cfg_attr(feature = "perf-inline", inline(always))]
113 pub(crate) fn find_rev(
114 needles: &[u8],
115 haystack: &[u8],
116 at: usize,
117 ) -> Option<usize> {
118 let bs = needles;
119 match needles.len() {
120 1 => memchr::memrchr(bs[0], &haystack[..at]),
121 2 => memchr::memrchr2(bs[0], bs[1], &haystack[..at]),
122 3 => memchr::memrchr3(bs[0], bs[1], bs[2], &haystack[..at]),
123 0 => panic!("cannot find with empty needles"),
124 n => panic!("invalid needles length: {}", n),
125 }
126 }
127
128 /// Represents the accelerators for all accelerated states in a dense DFA.
129 ///
130 /// The `A` type parameter represents the type of the underlying bytes.
131 /// Generally, this is either `&[AccelTy]` or `Vec<AccelTy>`.
132 #[derive(Clone)]
133 pub(crate) struct Accels<A> {
134 /// A length prefixed slice of contiguous accelerators. See the top comment
135 /// in this module for more details on how we can jump from a DFA's state
136 /// ID to an accelerator in this list.
137 ///
138 /// The first 4 bytes always correspond to the number of accelerators
139 /// that follow.
140 accels: A,
141 }
142
143 #[cfg(feature = "dfa-build")]
144 impl Accels<Vec<AccelTy>> {
145 /// Create an empty sequence of accelerators for a DFA.
146 pub fn empty() -> Accels<Vec<AccelTy>> {
147 Accels { accels: vec![0] }
148 }
149
150 /// Add an accelerator to this sequence.
151 ///
152 /// This adds to the accelerator to the end of the sequence and therefore
153 /// should be done in correspondence with its state in the DFA.
154 ///
155 /// This panics if this results in more accelerators than AccelTy::MAX.
156 pub fn add(&mut self, accel: Accel) {
157 self.accels.extend_from_slice(&accel.as_accel_tys());
158 let len = self.len();
159 self.set_len(len + 1);
160 }
161
162 /// Set the number of accelerators in this sequence, which is encoded in
163 /// the first 4 bytes of the underlying bytes.
164 fn set_len(&mut self, new_len: usize) {
165 // The only way an accelerator gets added is if a state exists for
166 // it, and if a state exists, then its index is guaranteed to be
167 // representable by a AccelTy by virtue of the guarantees provided by
168 // StateID.
169 let new_len = AccelTy::try_from(new_len).unwrap();
170 self.accels[0] = new_len;
171 }
172 }
173
174 impl<'a> Accels<&'a [AccelTy]> {
175 /// Deserialize a sequence of accelerators from the given bytes. If there
176 /// was a problem deserializing, then an error is returned.
177 ///
178 /// This is guaranteed to run in constant time. This does not guarantee
179 /// that every accelerator in the returned collection is valid. Thus,
180 /// accessing one may panic, or not-safe code that relies on accelerators
181 /// being correct my result in UB.
182 ///
183 /// Callers may check the validity of every accelerator with the `validate`
184 /// method.
185 pub fn from_bytes_unchecked(
186 mut slice: &'a [u8],
187 ) -> Result<(Accels<&'a [AccelTy]>, usize), DeserializeError> {
188 let slice_start = slice.as_ptr().as_usize();
189
190 let (accel_len, _) =
191 wire::try_read_u32_as_usize(slice, "accelerators length")?;
192 // The accelerator length is part of the accel_tys slice that
193 // we deserialize. This is perhaps a bit idiosyncratic. It would
194 // probably be better to split out the length into a real field.
195
196 let accel_tys_len = wire::add(
197 wire::mul(accel_len, 2, "total number of accelerator accel_tys")?,
198 1,
199 "total number of accel_tys",
200 )?;
201 let accel_tys_bytes_len = wire::mul(
202 ACCEL_TY_SIZE,
203 accel_tys_len,
204 "total number of bytes in accelerators",
205 )?;
206 wire::check_slice_len(slice, accel_tys_bytes_len, "accelerators")?;
207 wire::check_alignment::<AccelTy>(slice)?;
208 let accel_tys = &slice[..accel_tys_bytes_len];
209 slice = &slice[accel_tys_bytes_len..];
210 // SAFETY: We've checked the length and alignment above, and since
211 // slice is just bytes and AccelTy is just a u32, we can safely cast to
212 // a slice of &[AccelTy].
213 let accels = unsafe {
214 core::slice::from_raw_parts(
215 accel_tys.as_ptr().cast::<AccelTy>(),
216 accel_tys_len,
217 )
218 };
219 Ok((Accels { accels }, slice.as_ptr().as_usize() - slice_start))
220 }
221 }
222
223 impl<A: AsRef<[AccelTy]>> Accels<A> {
224 /// Return an owned version of the accelerators.
225 #[cfg(feature = "alloc")]
226 pub fn to_owned(&self) -> Accels<alloc::vec::Vec<AccelTy>> {
227 Accels { accels: self.accels.as_ref().to_vec() }
228 }
229
230 /// Return a borrowed version of the accelerators.
231 pub fn as_ref(&self) -> Accels<&[AccelTy]> {
232 Accels { accels: self.accels.as_ref() }
233 }
234
235 /// Return the bytes representing the serialization of the accelerators.
236 pub fn as_bytes(&self) -> &[u8] {
237 let accels = self.accels.as_ref();
238 // SAFETY: This is safe because accels is a just a slice of AccelTy,
239 // and u8 always has a smaller alignment.
240 unsafe {
241 core::slice::from_raw_parts(
242 accels.as_ptr().cast::<u8>(),
243 accels.len() * ACCEL_TY_SIZE,
244 )
245 }
246 }
247
248 /// Returns the memory usage, in bytes, of these accelerators.
249 ///
250 /// The memory usage is computed based on the number of bytes used to
251 /// represent all of the accelerators.
252 ///
253 /// This does **not** include the stack size used by this value.
254 pub fn memory_usage(&self) -> usize {
255 self.as_bytes().len()
256 }
257
258 /// Return the bytes to search for corresponding to the accelerator in this
259 /// sequence at index `i`. If no such accelerator exists, then this panics.
260 ///
261 /// The significance of the index is that it should be in correspondence
262 /// with the index of the corresponding DFA. That is, accelerated DFA
263 /// states are stored contiguously in the DFA and have an ordering implied
264 /// by their respective state IDs. The state's index in that sequence
265 /// corresponds to the index of its corresponding accelerator.
266 #[cfg_attr(feature = "perf-inline", inline(always))]
267 pub fn needles(&self, i: usize) -> &[u8] {
268 if i >= self.len() {
269 panic!("invalid accelerator index {}", i);
270 }
271 let bytes = self.as_bytes();
272 let offset = ACCEL_TY_SIZE + i * ACCEL_CAP;
273 let len = usize::from(bytes[offset]);
274 &bytes[offset + 1..offset + 1 + len]
275 }
276
277 /// Return the total number of accelerators in this sequence.
278 pub fn len(&self) -> usize {
279 // This should never panic since deserialization checks that the
280 // length can fit into a usize.
281 usize::try_from(self.accels.as_ref()[0]).unwrap()
282 }
283
284 /// Return the accelerator in this sequence at index `i`. If no such
285 /// accelerator exists, then this returns None.
286 ///
287 /// See the docs for `needles` on the significance of the index.
288 fn get(&self, i: usize) -> Option<Accel> {
289 if i >= self.len() {
290 return None;
291 }
292 let offset = ACCEL_TY_SIZE + i * ACCEL_CAP;
293 let accel = Accel::from_slice(&self.as_bytes()[offset..])
294 .expect("Accels must contain valid accelerators");
295 Some(accel)
296 }
297
298 /// Returns an iterator of accelerators in this sequence.
299 fn iter(&self) -> IterAccels<'_, A> {
300 IterAccels { accels: self, i: 0 }
301 }
302
303 /// Writes these accelerators to the given byte buffer using the indicated
304 /// endianness. If the given buffer is too small, then an error is
305 /// returned. Upon success, the total number of bytes written is returned.
306 /// The number of bytes written is guaranteed to be a multiple of 8.
307 pub fn write_to<E: Endian>(
308 &self,
309 dst: &mut [u8],
310 ) -> Result<usize, SerializeError> {
311 let nwrite = self.write_to_len();
312 assert_eq!(
313 nwrite % ACCEL_TY_SIZE,
314 0,
315 "expected accelerator bytes written to be a multiple of {}",
316 ACCEL_TY_SIZE,
317 );
318 if dst.len() < nwrite {
319 return Err(SerializeError::buffer_too_small("accelerators"));
320 }
321
322 // The number of accelerators can never exceed AccelTy::MAX.
323 E::write_u32(AccelTy::try_from(self.len()).unwrap(), dst);
324 // The actual accelerators are just raw bytes and thus their endianness
325 // is irrelevant. So we can copy them as bytes.
326 dst[ACCEL_TY_SIZE..nwrite]
327 .copy_from_slice(&self.as_bytes()[ACCEL_TY_SIZE..nwrite]);
328 Ok(nwrite)
329 }
330
331 /// Validates that every accelerator in this collection can be successfully
332 /// deserialized as a valid accelerator.
333 pub fn validate(&self) -> Result<(), DeserializeError> {
334 for chunk in self.as_bytes()[ACCEL_TY_SIZE..].chunks(ACCEL_CAP) {
335 let _ = Accel::from_slice(chunk)?;
336 }
337 Ok(())
338 }
339
340 /// Returns the total number of bytes written by `write_to`.
341 pub fn write_to_len(&self) -> usize {
342 self.as_bytes().len()
343 }
344 }
345
346 impl<A: AsRef<[AccelTy]>> core::fmt::Debug for Accels<A> {
347 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
348 write!(f, "Accels(")?;
349 let mut list = f.debug_list();
350 for a in self.iter() {
351 list.entry(&a);
352 }
353 list.finish()?;
354 write!(f, ")")
355 }
356 }
357
358 #[derive(Debug)]
359 struct IterAccels<'a, A: AsRef<[AccelTy]>> {
360 accels: &'a Accels<A>,
361 i: usize,
362 }
363
364 impl<'a, A: AsRef<[AccelTy]>> Iterator for IterAccels<'a, A> {
365 type Item = Accel;
366
367 fn next(&mut self) -> Option<Accel> {
368 let accel = self.accels.get(self.i)?;
369 self.i += 1;
370 Some(accel)
371 }
372 }
373
374 /// Accel represents a structure for determining how to "accelerate" a DFA
375 /// state.
376 ///
377 /// Namely, it contains zero or more bytes that must be seen in order for the
378 /// DFA to leave the state it is associated with. In practice, the actual range
379 /// is 1 to 3 bytes.
380 ///
381 /// The purpose of acceleration is to identify states whose vast majority
382 /// of transitions are just loops back to the same state. For example,
383 /// in the regex `(?-u)^[^a]+b`, the corresponding DFA will have a state
384 /// (corresponding to `[^a]+`) where all transitions *except* for `a` and
385 /// `b` loop back to itself. Thus, this state can be "accelerated" by simply
386 /// looking for the next occurrence of either `a` or `b` instead of explicitly
387 /// following transitions. (In this case, `b` transitions to the next state
388 /// where as `a` would transition to the dead state.)
389 #[derive(Clone)]
390 pub(crate) struct Accel {
391 /// The first byte is the length. Subsequent bytes are the accelerated
392 /// bytes.
393 ///
394 /// Note that we make every accelerator 8 bytes as a slightly wasteful
395 /// way of making sure alignment is always correct for state ID sizes of
396 /// 1, 2, 4 and 8. This should be okay since accelerated states aren't
397 /// particularly common, especially when Unicode is enabled.
398 bytes: [u8; ACCEL_CAP],
399 }
400
401 impl Accel {
402 /// Returns an empty accel, where no bytes are accelerated.
403 #[cfg(feature = "dfa-build")]
404 pub fn new() -> Accel {
405 Accel { bytes: [0; ACCEL_CAP] }
406 }
407
408 /// Returns a verified accelerator derived from the beginning of the given
409 /// slice.
410 ///
411 /// If the slice is not long enough or contains invalid bytes for an
412 /// accelerator, then this returns an error.
413 pub fn from_slice(mut slice: &[u8]) -> Result<Accel, DeserializeError> {
414 slice = &slice[..core::cmp::min(ACCEL_LEN, slice.len())];
415 let bytes = slice
416 .try_into()
417 .map_err(|_| DeserializeError::buffer_too_small("accelerator"))?;
418 Accel::from_bytes(bytes)
419 }
420
421 /// Returns a verified accelerator derived from raw bytes.
422 ///
423 /// If the given bytes are invalid, then this returns an error.
424 fn from_bytes(bytes: [u8; 4]) -> Result<Accel, DeserializeError> {
425 if usize::from(bytes[0]) >= ACCEL_LEN {
426 return Err(DeserializeError::generic(
427 "accelerator bytes cannot have length more than 3",
428 ));
429 }
430 Ok(Accel::from_bytes_unchecked(bytes))
431 }
432
433 /// Returns an accelerator derived from raw bytes.
434 ///
435 /// This does not check whether the given bytes are valid. Invalid bytes
436 /// cannot sacrifice memory safety, but may result in panics or silent
437 /// logic bugs.
438 fn from_bytes_unchecked(bytes: [u8; 4]) -> Accel {
439 Accel { bytes: [bytes[0], bytes[1], bytes[2], bytes[3], 0, 0, 0, 0] }
440 }
441
442 /// Attempts to add the given byte to this accelerator. If the accelerator
443 /// is already full or thinks the byte is a poor accelerator, then this
444 /// returns false. Otherwise, returns true.
445 ///
446 /// If the given byte is already in this accelerator, then it panics.
447 #[cfg(feature = "dfa-build")]
448 pub fn add(&mut self, byte: u8) -> bool {
449 if self.len() >= 3 {
450 return false;
451 }
452 // As a special case, we totally reject trying to accelerate a state
453 // with an ASCII space. In most cases, it occurs very frequently, and
454 // tends to result in worse overall performance.
455 if byte == b' ' {
456 return false;
457 }
458 assert!(
459 !self.contains(byte),
460 "accelerator already contains {:?}",
461 crate::util::escape::DebugByte(byte)
462 );
463 self.bytes[self.len() + 1] = byte;
464 self.bytes[0] += 1;
465 true
466 }
467
468 /// Return the number of bytes in this accelerator.
469 pub fn len(&self) -> usize {
470 usize::from(self.bytes[0])
471 }
472
473 /// Returns true if and only if there are no bytes in this accelerator.
474 #[cfg(feature = "dfa-build")]
475 pub fn is_empty(&self) -> bool {
476 self.len() == 0
477 }
478
479 /// Returns the slice of bytes to accelerate.
480 ///
481 /// If this accelerator is empty, then this returns an empty slice.
482 fn needles(&self) -> &[u8] {
483 &self.bytes[1..1 + self.len()]
484 }
485
486 /// Returns true if and only if this accelerator will accelerate the given
487 /// byte.
488 #[cfg(feature = "dfa-build")]
489 fn contains(&self, byte: u8) -> bool {
490 self.needles().iter().position(|&b| b == byte).is_some()
491 }
492
493 /// Returns the accelerator bytes as an array of AccelTys.
494 #[cfg(feature = "dfa-build")]
495 fn as_accel_tys(&self) -> [AccelTy; 2] {
496 assert_eq!(ACCEL_CAP, 8);
497 // These unwraps are OK since ACCEL_CAP is set to 8.
498 let first =
499 AccelTy::from_ne_bytes(self.bytes[0..4].try_into().unwrap());
500 let second =
501 AccelTy::from_ne_bytes(self.bytes[4..8].try_into().unwrap());
502 [first, second]
503 }
504 }
505
506 impl core::fmt::Debug for Accel {
507 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
508 write!(f, "Accel(")?;
509 let mut set = f.debug_set();
510 for &b in self.needles() {
511 set.entry(&crate::util::escape::DebugByte(b));
512 }
513 set.finish()?;
514 write!(f, ")")
515 }
516 }