Debian Codegraph @

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

raw
1 /*!
2 Types and routines specific to sparse DFAs.
3
4 This module is the home of [`sparse::DFA`](DFA).
5
6 Unlike the [`dense`](super::dense) module, this module does not contain a
7 builder or configuration specific for sparse DFAs. Instead, the intended
8 way to build a sparse DFA is either by using a default configuration with
9 its constructor [`sparse::DFA::new`](DFA::new), or by first configuring the
10 construction of a dense DFA with [`dense::Builder`](super::dense::Builder)
11 and then calling [`dense::DFA::to_sparse`](super::dense::DFA::to_sparse). For
12 example, this configures a sparse DFA to do an overlapping search:
13
14 ```
15 use regex_automata::{
16 dfa::{Automaton, OverlappingState, dense},
17 HalfMatch, Input, MatchKind,
18 };
19
20 let dense_re = dense::Builder::new()
21 .configure(dense::Config::new().match_kind(MatchKind::All))
22 .build(r"Samwise|Sam")?;
23 let sparse_re = dense_re.to_sparse()?;
24
25 // Setup our haystack and initial start state.
26 let input = Input::new("Samwise");
27 let mut state = OverlappingState::start();
28
29 // First, 'Sam' will match.
30 sparse_re.try_search_overlapping_fwd(&input, &mut state)?;
31 assert_eq!(Some(HalfMatch::must(0, 3)), state.get_match());
32
33 // And now 'Samwise' will match.
34 sparse_re.try_search_overlapping_fwd(&input, &mut state)?;
35 assert_eq!(Some(HalfMatch::must(0, 7)), state.get_match());
36 # Ok::<(), Box<dyn std::error::Error>>(())
37 ```
38 */
39
40 #[cfg(feature = "dfa-build")]
41 use core::iter;
42 use core::{
43 convert::{TryFrom, TryInto},
44 fmt,
45 mem::size_of,
46 };
47
48 #[cfg(feature = "dfa-build")]
49 use alloc::{vec, vec::Vec};
50
51 #[cfg(feature = "dfa-build")]
52 use crate::dfa::dense::{self, BuildError};
53 use crate::{
54 dfa::{
55 automaton::{fmt_state_indicator, Automaton},
56 dense::Flags,
57 special::Special,
58 StartKind, DEAD,
59 },
60 util::{
61 alphabet::{ByteClasses, ByteSet},
62 escape::DebugByte,
63 int::{Pointer, Usize, U16, U32},
64 prefilter::Prefilter,
65 primitives::{PatternID, StateID},
66 search::{Anchored, Input, MatchError},
67 start::{Start, StartByteMap},
68 wire::{self, DeserializeError, Endian, SerializeError},
69 },
70 };
71
72 const LABEL: &str = "rust-regex-automata-dfa-sparse";
73 const VERSION: u32 = 2;
74
75 /// A sparse deterministic finite automaton (DFA) with variable sized states.
76 ///
77 /// In contrast to a [dense::DFA](crate::dfa::dense::DFA), a sparse DFA uses
78 /// a more space efficient representation for its transitions. Consequently,
79 /// sparse DFAs may use much less memory than dense DFAs, but this comes at a
80 /// price. In particular, reading the more space efficient transitions takes
81 /// more work, and consequently, searching using a sparse DFA is typically
82 /// slower than a dense DFA.
83 ///
84 /// A sparse DFA can be built using the default configuration via the
85 /// [`DFA::new`] constructor. Otherwise, one can configure various aspects
86 /// of a dense DFA via [`dense::Builder`](crate::dfa::dense::Builder),
87 /// and then convert a dense DFA to a sparse DFA using
88 /// [`dense::DFA::to_sparse`](crate::dfa::dense::DFA::to_sparse).
89 ///
90 /// In general, a sparse DFA supports all the same search operations as a dense
91 /// DFA.
92 ///
93 /// Making the choice between a dense and sparse DFA depends on your specific
94 /// work load. If you can sacrifice a bit of search time performance, then a
95 /// sparse DFA might be the best choice. In particular, while sparse DFAs are
96 /// probably always slower than dense DFAs, you may find that they are easily
97 /// fast enough for your purposes!
98 ///
99 /// # Type parameters
100 ///
101 /// A `DFA` has one type parameter, `T`, which is used to represent the parts
102 /// of a sparse DFA. `T` is typically a `Vec<u8>` or a `&[u8]`.
103 ///
104 /// # The `Automaton` trait
105 ///
106 /// This type implements the [`Automaton`] trait, which means it can be used
107 /// for searching. For example:
108 ///
109 /// ```
110 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
111 ///
112 /// let dfa = DFA::new("foo[0-9]+")?;
113 /// let expected = Some(HalfMatch::must(0, 8));
114 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
115 /// # Ok::<(), Box<dyn std::error::Error>>(())
116 /// ```
117 #[derive(Clone)]
118 pub struct DFA<T> {
119 // When compared to a dense DFA, a sparse DFA *looks* a lot simpler
120 // representation-wise. In reality, it is perhaps more complicated. Namely,
121 // in a dense DFA, all information needs to be very cheaply accessible
122 // using only state IDs. In a sparse DFA however, each state uses a
123 // variable amount of space because each state encodes more information
124 // than just its transitions. Each state also includes an accelerator if
125 // one exists, along with the matching pattern IDs if the state is a match
126 // state.
127 //
128 // That is, a lot of the complexity is pushed down into how each state
129 // itself is represented.
130 tt: Transitions<T>,
131 st: StartTable<T>,
132 special: Special,
133 pre: Option<Prefilter>,
134 quitset: ByteSet,
135 flags: Flags,
136 }
137
138 #[cfg(feature = "dfa-build")]
139 impl DFA<Vec<u8>> {
140 /// Parse the given regular expression using a default configuration and
141 /// return the corresponding sparse DFA.
142 ///
143 /// If you want a non-default configuration, then use
144 /// the [`dense::Builder`](crate::dfa::dense::Builder)
145 /// to set your own configuration, and then call
146 /// [`dense::DFA::to_sparse`](crate::dfa::dense::DFA::to_sparse) to create
147 /// a sparse DFA.
148 ///
149 /// # Example
150 ///
151 /// ```
152 /// use regex_automata::{dfa::{Automaton, sparse}, HalfMatch, Input};
153 ///
154 /// let dfa = sparse::DFA::new("foo[0-9]+bar")?;
155 ///
156 /// let expected = Some(HalfMatch::must(0, 11));
157 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345bar"))?);
158 /// # Ok::<(), Box<dyn std::error::Error>>(())
159 /// ```
160 #[cfg(feature = "syntax")]
161 pub fn new(pattern: &str) -> Result<DFA<Vec<u8>>, BuildError> {
162 dense::Builder::new()
163 .build(pattern)
164 .and_then(|dense| dense.to_sparse())
165 }
166
167 /// Parse the given regular expressions using a default configuration and
168 /// return the corresponding multi-DFA.
169 ///
170 /// If you want a non-default configuration, then use
171 /// the [`dense::Builder`](crate::dfa::dense::Builder)
172 /// to set your own configuration, and then call
173 /// [`dense::DFA::to_sparse`](crate::dfa::dense::DFA::to_sparse) to create
174 /// a sparse DFA.
175 ///
176 /// # Example
177 ///
178 /// ```
179 /// use regex_automata::{dfa::{Automaton, sparse}, HalfMatch, Input};
180 ///
181 /// let dfa = sparse::DFA::new_many(&["[0-9]+", "[a-z]+"])?;
182 /// let expected = Some(HalfMatch::must(1, 3));
183 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345bar"))?);
184 /// # Ok::<(), Box<dyn std::error::Error>>(())
185 /// ```
186 #[cfg(feature = "syntax")]
187 pub fn new_many<P: AsRef<str>>(
188 patterns: &[P],
189 ) -> Result<DFA<Vec<u8>>, BuildError> {
190 dense::Builder::new()
191 .build_many(patterns)
192 .and_then(|dense| dense.to_sparse())
193 }
194 }
195
196 #[cfg(feature = "dfa-build")]
197 impl DFA<Vec<u8>> {
198 /// Create a new DFA that matches every input.
199 ///
200 /// # Example
201 ///
202 /// ```
203 /// use regex_automata::{
204 /// dfa::{Automaton, sparse},
205 /// HalfMatch, Input,
206 /// };
207 ///
208 /// let dfa = sparse::DFA::always_match()?;
209 ///
210 /// let expected = Some(HalfMatch::must(0, 0));
211 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new(""))?);
212 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo"))?);
213 /// # Ok::<(), Box<dyn std::error::Error>>(())
214 /// ```
215 pub fn always_match() -> Result<DFA<Vec<u8>>, BuildError> {
216 dense::DFA::always_match()?.to_sparse()
217 }
218
219 /// Create a new sparse DFA that never matches any input.
220 ///
221 /// # Example
222 ///
223 /// ```
224 /// use regex_automata::{dfa::{Automaton, sparse}, Input};
225 ///
226 /// let dfa = sparse::DFA::never_match()?;
227 /// assert_eq!(None, dfa.try_search_fwd(&Input::new(""))?);
228 /// assert_eq!(None, dfa.try_search_fwd(&Input::new("foo"))?);
229 /// # Ok::<(), Box<dyn std::error::Error>>(())
230 /// ```
231 pub fn never_match() -> Result<DFA<Vec<u8>>, BuildError> {
232 dense::DFA::never_match()?.to_sparse()
233 }
234
235 /// The implementation for constructing a sparse DFA from a dense DFA.
236 pub(crate) fn from_dense<T: AsRef<[u32]>>(
237 dfa: &dense::DFA<T>,
238 ) -> Result<DFA<Vec<u8>>, BuildError> {
239 // In order to build the transition table, we need to be able to write
240 // state identifiers for each of the "next" transitions in each state.
241 // Our state identifiers correspond to the byte offset in the
242 // transition table at which the state is encoded. Therefore, we do not
243 // actually know what the state identifiers are until we've allocated
244 // exactly as much space as we need for each state. Thus, construction
245 // of the transition table happens in two passes.
246 //
247 // In the first pass, we fill out the shell of each state, which
248 // includes the transition length, the input byte ranges and
249 // zero-filled space for the transitions and accelerators, if present.
250 // In this first pass, we also build up a map from the state identifier
251 // index of the dense DFA to the state identifier in this sparse DFA.
252 //
253 // In the second pass, we fill in the transitions based on the map
254 // built in the first pass.
255
256 // The capacity given here reflects a minimum. (Well, the true minimum
257 // is likely even bigger, but hopefully this saves a few reallocs.)
258 let mut sparse = Vec::with_capacity(StateID::SIZE * dfa.state_len());
259 // This maps state indices from the dense DFA to StateIDs in the sparse
260 // DFA. We build out this map on the first pass, and then use it in the
261 // second pass to back-fill our transitions.
262 let mut remap: Vec<StateID> = vec![DEAD; dfa.state_len()];
263 for state in dfa.states() {
264 let pos = sparse.len();
265
266 remap[dfa.to_index(state.id())] = StateID::new(pos)
267 .map_err(|_| BuildError::too_many_states())?;
268 // zero-filled space for the transition length
269 sparse.push(0);
270 sparse.push(0);
271
272 let mut transition_len = 0;
273 for (unit1, unit2, _) in state.sparse_transitions() {
274 match (unit1.as_u8(), unit2.as_u8()) {
275 (Some(b1), Some(b2)) => {
276 transition_len += 1;
277 sparse.push(b1);
278 sparse.push(b2);
279 }
280 (None, None) => {}
281 (Some(_), None) | (None, Some(_)) => {
282 // can never occur because sparse_transitions never
283 // groups EOI with any other transition.
284 unreachable!()
285 }
286 }
287 }
288 // Add dummy EOI transition. This is never actually read while
289 // searching, but having space equivalent to the total number
290 // of transitions is convenient. Otherwise, we'd need to track
291 // a different number of transitions for the byte ranges as for
292 // the 'next' states.
293 //
294 // N.B. The loop above is not guaranteed to yield the EOI
295 // transition, since it may point to a DEAD state. By putting
296 // it here, we always write the EOI transition, and thus
297 // guarantee that our transition length is >0. Why do we always
298 // need the EOI transition? Because in order to implement
299 // Automaton::next_eoi_state, this lets us just ask for the last
300 // transition. There are probably other/better ways to do this.
301 transition_len += 1;
302 sparse.push(0);
303 sparse.push(0);
304
305 // Check some assumptions about transition length.
306 assert_ne!(
307 transition_len, 0,
308 "transition length should be non-zero",
309 );
310 assert!(
311 transition_len <= 257,
312 "expected transition length {} to be <= 257",
313 transition_len,
314 );
315
316 // Fill in the transition length.
317 // Since transition length is always <= 257, we use the most
318 // significant bit to indicate whether this is a match state or
319 // not.
320 let ntrans = if dfa.is_match_state(state.id()) {
321 transition_len | (1 << 15)
322 } else {
323 transition_len
324 };
325 wire::NE::write_u16(ntrans, &mut sparse[pos..]);
326
327 // zero-fill the actual transitions.
328 // Unwraps are OK since transition_length <= 257 and our minimum
329 // support usize size is 16-bits.
330 let zeros = usize::try_from(transition_len)
331 .unwrap()
332 .checked_mul(StateID::SIZE)
333 .unwrap();
334 sparse.extend(iter::repeat(0).take(zeros));
335
336 // If this is a match state, write the pattern IDs matched by this
337 // state.
338 if dfa.is_match_state(state.id()) {
339 let plen = dfa.match_pattern_len(state.id());
340 // Write the actual pattern IDs with a u32 length prefix.
341 // First, zero-fill space.
342 let mut pos = sparse.len();
343 // Unwraps are OK since it's guaranteed that plen <=
344 // PatternID::LIMIT, which is in turn guaranteed to fit into a
345 // u32.
346 let zeros = size_of::<u32>()
347 .checked_mul(plen)
348 .unwrap()
349 .checked_add(size_of::<u32>())
350 .unwrap();
351 sparse.extend(iter::repeat(0).take(zeros));
352
353 // Now write the length prefix.
354 wire::NE::write_u32(
355 // Will never fail since u32::MAX is invalid pattern ID.
356 // Thus, the number of pattern IDs is representable by a
357 // u32.
358 plen.try_into().expect("pattern ID length fits in u32"),
359 &mut sparse[pos..],
360 );
361 pos += size_of::<u32>();
362
363 // Now write the pattern IDs.
364 for &pid in dfa.pattern_id_slice(state.id()) {
365 pos += wire::write_pattern_id::<wire::NE>(
366 pid,
367 &mut sparse[pos..],
368 );
369 }
370 }
371
372 // And now add the accelerator, if one exists. An accelerator is
373 // at most 4 bytes and at least 1 byte. The first byte is the
374 // length, N. N bytes follow the length. The set of bytes that
375 // follow correspond (exhaustively) to the bytes that must be seen
376 // to leave this state.
377 let accel = dfa.accelerator(state.id());
378 sparse.push(accel.len().try_into().unwrap());
379 sparse.extend_from_slice(accel);
380 }
381
382 let mut new = DFA {
383 tt: Transitions {
384 sparse,
385 classes: dfa.byte_classes().clone(),
386 state_len: dfa.state_len(),
387 pattern_len: dfa.pattern_len(),
388 },
389 st: StartTable::from_dense_dfa(dfa, &remap)?,
390 special: dfa.special().remap(|id| remap[dfa.to_index(id)]),
391 pre: dfa.get_prefilter().map(|p| p.clone()),
392 quitset: dfa.quitset().clone(),
393 flags: dfa.flags().clone(),
394 };
395 // And here's our second pass. Iterate over all of the dense states
396 // again, and update the transitions in each of the states in the
397 // sparse DFA.
398 for old_state in dfa.states() {
399 let new_id = remap[dfa.to_index(old_state.id())];
400 let mut new_state = new.tt.state_mut(new_id);
401 let sparse = old_state.sparse_transitions();
402 for (i, (_, _, next)) in sparse.enumerate() {
403 let next = remap[dfa.to_index(next)];
404 new_state.set_next_at(i, next);
405 }
406 }
407 debug!(
408 "created sparse DFA, memory usage: {} (dense memory usage: {})",
409 new.memory_usage(),
410 dfa.memory_usage(),
411 );
412 Ok(new)
413 }
414 }
415
416 impl<T: AsRef<[u8]>> DFA<T> {
417 /// Cheaply return a borrowed version of this sparse DFA. Specifically, the
418 /// DFA returned always uses `&[u8]` for its transitions.
419 pub fn as_ref<'a>(&'a self) -> DFA<&'a [u8]> {
420 DFA {
421 tt: self.tt.as_ref(),
422 st: self.st.as_ref(),
423 special: self.special,
424 pre: self.pre.clone(),
425 quitset: self.quitset,
426 flags: self.flags,
427 }
428 }
429
430 /// Return an owned version of this sparse DFA. Specifically, the DFA
431 /// returned always uses `Vec<u8>` for its transitions.
432 ///
433 /// Effectively, this returns a sparse DFA whose transitions live on the
434 /// heap.
435 #[cfg(feature = "alloc")]
436 pub fn to_owned(&self) -> DFA<alloc::vec::Vec<u8>> {
437 DFA {
438 tt: self.tt.to_owned(),
439 st: self.st.to_owned(),
440 special: self.special,
441 pre: self.pre.clone(),
442 quitset: self.quitset,
443 flags: self.flags,
444 }
445 }
446
447 /// Returns the starting state configuration for this DFA.
448 ///
449 /// The default is [`StartKind::Both`], which means the DFA supports both
450 /// unanchored and anchored searches. However, this can generally lead to
451 /// bigger DFAs. Therefore, a DFA might be compiled with support for just
452 /// unanchored or anchored searches. In that case, running a search with
453 /// an unsupported configuration will panic.
454 pub fn start_kind(&self) -> StartKind {
455 self.st.kind
456 }
457
458 /// Returns true only if this DFA has starting states for each pattern.
459 ///
460 /// When a DFA has starting states for each pattern, then a search with the
461 /// DFA can be configured to only look for anchored matches of a specific
462 /// pattern. Specifically, APIs like [`Automaton::try_search_fwd`] can
463 /// accept a [`Anchored::Pattern`] if and only if this method returns true.
464 /// Otherwise, an error will be returned.
465 ///
466 /// Note that if the DFA is empty, this always returns false.
467 pub fn starts_for_each_pattern(&self) -> bool {
468 self.st.pattern_len.is_some()
469 }
470
471 /// Returns the equivalence classes that make up the alphabet for this DFA.
472 ///
473 /// Unless [`dense::Config::byte_classes`] was disabled, it is possible
474 /// that multiple distinct bytes are grouped into the same equivalence
475 /// class if it is impossible for them to discriminate between a match and
476 /// a non-match. This has the effect of reducing the overall alphabet size
477 /// and in turn potentially substantially reducing the size of the DFA's
478 /// transition table.
479 ///
480 /// The downside of using equivalence classes like this is that every state
481 /// transition will automatically use this map to convert an arbitrary
482 /// byte to its corresponding equivalence class. In practice this has a
483 /// negligible impact on performance.
484 pub fn byte_classes(&self) -> &ByteClasses {
485 &self.tt.classes
486 }
487
488 /// Returns the memory usage, in bytes, of this DFA.
489 ///
490 /// The memory usage is computed based on the number of bytes used to
491 /// represent this DFA.
492 ///
493 /// This does **not** include the stack size used up by this DFA. To
494 /// compute that, use `std::mem::size_of::<sparse::DFA>()`.
495 pub fn memory_usage(&self) -> usize {
496 self.tt.memory_usage() + self.st.memory_usage()
497 }
498 }
499
500 /// Routines for converting a sparse DFA to other representations, such as raw
501 /// bytes suitable for persistent storage.
502 impl<T: AsRef<[u8]>> DFA<T> {
503 /// Serialize this DFA as raw bytes to a `Vec<u8>` in little endian
504 /// format.
505 ///
506 /// The written bytes are guaranteed to be deserialized correctly and
507 /// without errors in a semver compatible release of this crate by a
508 /// `DFA`'s deserialization APIs (assuming all other criteria for the
509 /// deserialization APIs has been satisfied):
510 ///
511 /// * [`DFA::from_bytes`]
512 /// * [`DFA::from_bytes_unchecked`]
513 ///
514 /// Note that unlike a [`dense::DFA`](crate::dfa::dense::DFA)'s
515 /// serialization methods, this does not add any initial padding to the
516 /// returned bytes. Padding isn't required for sparse DFAs since they have
517 /// no alignment requirements.
518 ///
519 /// # Example
520 ///
521 /// This example shows how to serialize and deserialize a DFA:
522 ///
523 /// ```
524 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
525 ///
526 /// // Compile our original DFA.
527 /// let original_dfa = DFA::new("foo[0-9]+")?;
528 ///
529 /// // N.B. We use native endianness here to make the example work, but
530 /// // using to_bytes_little_endian would work on a little endian target.
531 /// let buf = original_dfa.to_bytes_native_endian();
532 /// // Even if buf has initial padding, DFA::from_bytes will automatically
533 /// // ignore it.
534 /// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf)?.0;
535 ///
536 /// let expected = Some(HalfMatch::must(0, 8));
537 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
538 /// # Ok::<(), Box<dyn std::error::Error>>(())
539 /// ```
540 #[cfg(feature = "dfa-build")]
541 pub fn to_bytes_little_endian(&self) -> Vec<u8> {
542 self.to_bytes::<wire::LE>()
543 }
544
545 /// Serialize this DFA as raw bytes to a `Vec<u8>` in big endian
546 /// format.
547 ///
548 /// The written bytes are guaranteed to be deserialized correctly and
549 /// without errors in a semver compatible release of this crate by a
550 /// `DFA`'s deserialization APIs (assuming all other criteria for the
551 /// deserialization APIs has been satisfied):
552 ///
553 /// * [`DFA::from_bytes`]
554 /// * [`DFA::from_bytes_unchecked`]
555 ///
556 /// Note that unlike a [`dense::DFA`](crate::dfa::dense::DFA)'s
557 /// serialization methods, this does not add any initial padding to the
558 /// returned bytes. Padding isn't required for sparse DFAs since they have
559 /// no alignment requirements.
560 ///
561 /// # Example
562 ///
563 /// This example shows how to serialize and deserialize a DFA:
564 ///
565 /// ```
566 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
567 ///
568 /// // Compile our original DFA.
569 /// let original_dfa = DFA::new("foo[0-9]+")?;
570 ///
571 /// // N.B. We use native endianness here to make the example work, but
572 /// // using to_bytes_big_endian would work on a big endian target.
573 /// let buf = original_dfa.to_bytes_native_endian();
574 /// // Even if buf has initial padding, DFA::from_bytes will automatically
575 /// // ignore it.
576 /// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf)?.0;
577 ///
578 /// let expected = Some(HalfMatch::must(0, 8));
579 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
580 /// # Ok::<(), Box<dyn std::error::Error>>(())
581 /// ```
582 #[cfg(feature = "dfa-build")]
583 pub fn to_bytes_big_endian(&self) -> Vec<u8> {
584 self.to_bytes::<wire::BE>()
585 }
586
587 /// Serialize this DFA as raw bytes to a `Vec<u8>` in native endian
588 /// format.
589 ///
590 /// The written bytes are guaranteed to be deserialized correctly and
591 /// without errors in a semver compatible release of this crate by a
592 /// `DFA`'s deserialization APIs (assuming all other criteria for the
593 /// deserialization APIs has been satisfied):
594 ///
595 /// * [`DFA::from_bytes`]
596 /// * [`DFA::from_bytes_unchecked`]
597 ///
598 /// Note that unlike a [`dense::DFA`](crate::dfa::dense::DFA)'s
599 /// serialization methods, this does not add any initial padding to the
600 /// returned bytes. Padding isn't required for sparse DFAs since they have
601 /// no alignment requirements.
602 ///
603 /// Generally speaking, native endian format should only be used when
604 /// you know that the target you're compiling the DFA for matches the
605 /// endianness of the target on which you're compiling DFA. For example,
606 /// if serialization and deserialization happen in the same process or on
607 /// the same machine. Otherwise, when serializing a DFA for use in a
608 /// portable environment, you'll almost certainly want to serialize _both_
609 /// a little endian and a big endian version and then load the correct one
610 /// based on the target's configuration.
611 ///
612 /// # Example
613 ///
614 /// This example shows how to serialize and deserialize a DFA:
615 ///
616 /// ```
617 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
618 ///
619 /// // Compile our original DFA.
620 /// let original_dfa = DFA::new("foo[0-9]+")?;
621 ///
622 /// let buf = original_dfa.to_bytes_native_endian();
623 /// // Even if buf has initial padding, DFA::from_bytes will automatically
624 /// // ignore it.
625 /// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf)?.0;
626 ///
627 /// let expected = Some(HalfMatch::must(0, 8));
628 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
629 /// # Ok::<(), Box<dyn std::error::Error>>(())
630 /// ```
631 #[cfg(feature = "dfa-build")]
632 pub fn to_bytes_native_endian(&self) -> Vec<u8> {
633 self.to_bytes::<wire::NE>()
634 }
635
636 /// The implementation of the public `to_bytes` serialization methods,
637 /// which is generic over endianness.
638 #[cfg(feature = "dfa-build")]
639 fn to_bytes<E: Endian>(&self) -> Vec<u8> {
640 let mut buf = vec![0; self.write_to_len()];
641 // This should always succeed since the only possible serialization
642 // error is providing a buffer that's too small, but we've ensured that
643 // `buf` is big enough here.
644 self.write_to::<E>(&mut buf).unwrap();
645 buf
646 }
647
648 /// Serialize this DFA as raw bytes to the given slice, in little endian
649 /// format. Upon success, the total number of bytes written to `dst` is
650 /// returned.
651 ///
652 /// The written bytes are guaranteed to be deserialized correctly and
653 /// without errors in a semver compatible release of this crate by a
654 /// `DFA`'s deserialization APIs (assuming all other criteria for the
655 /// deserialization APIs has been satisfied):
656 ///
657 /// * [`DFA::from_bytes`]
658 /// * [`DFA::from_bytes_unchecked`]
659 ///
660 /// # Errors
661 ///
662 /// This returns an error if the given destination slice is not big enough
663 /// to contain the full serialized DFA. If an error occurs, then nothing
664 /// is written to `dst`.
665 ///
666 /// # Example
667 ///
668 /// This example shows how to serialize and deserialize a DFA without
669 /// dynamic memory allocation.
670 ///
671 /// ```
672 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
673 ///
674 /// // Compile our original DFA.
675 /// let original_dfa = DFA::new("foo[0-9]+")?;
676 ///
677 /// // Create a 4KB buffer on the stack to store our serialized DFA.
678 /// let mut buf = [0u8; 4 * (1<<10)];
679 /// // N.B. We use native endianness here to make the example work, but
680 /// // using write_to_little_endian would work on a little endian target.
681 /// let written = original_dfa.write_to_native_endian(&mut buf)?;
682 /// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf[..written])?.0;
683 ///
684 /// let expected = Some(HalfMatch::must(0, 8));
685 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
686 /// # Ok::<(), Box<dyn std::error::Error>>(())
687 /// ```
688 pub fn write_to_little_endian(
689 &self,
690 dst: &mut [u8],
691 ) -> Result<usize, SerializeError> {
692 self.write_to::<wire::LE>(dst)
693 }
694
695 /// Serialize this DFA as raw bytes to the given slice, in big endian
696 /// format. Upon success, the total number of bytes written to `dst` is
697 /// returned.
698 ///
699 /// The written bytes are guaranteed to be deserialized correctly and
700 /// without errors in a semver compatible release of this crate by a
701 /// `DFA`'s deserialization APIs (assuming all other criteria for the
702 /// deserialization APIs has been satisfied):
703 ///
704 /// * [`DFA::from_bytes`]
705 /// * [`DFA::from_bytes_unchecked`]
706 ///
707 /// # Errors
708 ///
709 /// This returns an error if the given destination slice is not big enough
710 /// to contain the full serialized DFA. If an error occurs, then nothing
711 /// is written to `dst`.
712 ///
713 /// # Example
714 ///
715 /// This example shows how to serialize and deserialize a DFA without
716 /// dynamic memory allocation.
717 ///
718 /// ```
719 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
720 ///
721 /// // Compile our original DFA.
722 /// let original_dfa = DFA::new("foo[0-9]+")?;
723 ///
724 /// // Create a 4KB buffer on the stack to store our serialized DFA.
725 /// let mut buf = [0u8; 4 * (1<<10)];
726 /// // N.B. We use native endianness here to make the example work, but
727 /// // using write_to_big_endian would work on a big endian target.
728 /// let written = original_dfa.write_to_native_endian(&mut buf)?;
729 /// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf[..written])?.0;
730 ///
731 /// let expected = Some(HalfMatch::must(0, 8));
732 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
733 /// # Ok::<(), Box<dyn std::error::Error>>(())
734 /// ```
735 pub fn write_to_big_endian(
736 &self,
737 dst: &mut [u8],
738 ) -> Result<usize, SerializeError> {
739 self.write_to::<wire::BE>(dst)
740 }
741
742 /// Serialize this DFA as raw bytes to the given slice, in native endian
743 /// format. Upon success, the total number of bytes written to `dst` is
744 /// returned.
745 ///
746 /// The written bytes are guaranteed to be deserialized correctly and
747 /// without errors in a semver compatible release of this crate by a
748 /// `DFA`'s deserialization APIs (assuming all other criteria for the
749 /// deserialization APIs has been satisfied):
750 ///
751 /// * [`DFA::from_bytes`]
752 /// * [`DFA::from_bytes_unchecked`]
753 ///
754 /// Generally speaking, native endian format should only be used when
755 /// you know that the target you're compiling the DFA for matches the
756 /// endianness of the target on which you're compiling DFA. For example,
757 /// if serialization and deserialization happen in the same process or on
758 /// the same machine. Otherwise, when serializing a DFA for use in a
759 /// portable environment, you'll almost certainly want to serialize _both_
760 /// a little endian and a big endian version and then load the correct one
761 /// based on the target's configuration.
762 ///
763 /// # Errors
764 ///
765 /// This returns an error if the given destination slice is not big enough
766 /// to contain the full serialized DFA. If an error occurs, then nothing
767 /// is written to `dst`.
768 ///
769 /// # Example
770 ///
771 /// This example shows how to serialize and deserialize a DFA without
772 /// dynamic memory allocation.
773 ///
774 /// ```
775 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
776 ///
777 /// // Compile our original DFA.
778 /// let original_dfa = DFA::new("foo[0-9]+")?;
779 ///
780 /// // Create a 4KB buffer on the stack to store our serialized DFA.
781 /// let mut buf = [0u8; 4 * (1<<10)];
782 /// let written = original_dfa.write_to_native_endian(&mut buf)?;
783 /// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf[..written])?.0;
784 ///
785 /// let expected = Some(HalfMatch::must(0, 8));
786 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
787 /// # Ok::<(), Box<dyn std::error::Error>>(())
788 /// ```
789 pub fn write_to_native_endian(
790 &self,
791 dst: &mut [u8],
792 ) -> Result<usize, SerializeError> {
793 self.write_to::<wire::NE>(dst)
794 }
795
796 /// The implementation of the public `write_to` serialization methods,
797 /// which is generic over endianness.
798 fn write_to<E: Endian>(
799 &self,
800 dst: &mut [u8],
801 ) -> Result<usize, SerializeError> {
802 let mut nw = 0;
803 nw += wire::write_label(LABEL, &mut dst[nw..])?;
804 nw += wire::write_endianness_check::<E>(&mut dst[nw..])?;
805 nw += wire::write_version::<E>(VERSION, &mut dst[nw..])?;
806 nw += {
807 // Currently unused, intended for future flexibility
808 E::write_u32(0, &mut dst[nw..]);
809 size_of::<u32>()
810 };
811 nw += self.flags.write_to::<E>(&mut dst[nw..])?;
812 nw += self.tt.write_to::<E>(&mut dst[nw..])?;
813 nw += self.st.write_to::<E>(&mut dst[nw..])?;
814 nw += self.special.write_to::<E>(&mut dst[nw..])?;
815 nw += self.quitset.write_to::<E>(&mut dst[nw..])?;
816 Ok(nw)
817 }
818
819 /// Return the total number of bytes required to serialize this DFA.
820 ///
821 /// This is useful for determining the size of the buffer required to pass
822 /// to one of the serialization routines:
823 ///
824 /// * [`DFA::write_to_little_endian`]
825 /// * [`DFA::write_to_big_endian`]
826 /// * [`DFA::write_to_native_endian`]
827 ///
828 /// Passing a buffer smaller than the size returned by this method will
829 /// result in a serialization error.
830 ///
831 /// # Example
832 ///
833 /// This example shows how to dynamically allocate enough room to serialize
834 /// a sparse DFA.
835 ///
836 /// ```
837 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
838 ///
839 /// // Compile our original DFA.
840 /// let original_dfa = DFA::new("foo[0-9]+")?;
841 ///
842 /// let mut buf = vec![0; original_dfa.write_to_len()];
843 /// let written = original_dfa.write_to_native_endian(&mut buf)?;
844 /// let dfa: DFA<&[u8]> = DFA::from_bytes(&buf[..written])?.0;
845 ///
846 /// let expected = Some(HalfMatch::must(0, 8));
847 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
848 /// # Ok::<(), Box<dyn std::error::Error>>(())
849 /// ```
850 pub fn write_to_len(&self) -> usize {
851 wire::write_label_len(LABEL)
852 + wire::write_endianness_check_len()
853 + wire::write_version_len()
854 + size_of::<u32>() // unused, intended for future flexibility
855 + self.flags.write_to_len()
856 + self.tt.write_to_len()
857 + self.st.write_to_len()
858 + self.special.write_to_len()
859 + self.quitset.write_to_len()
860 }
861 }
862
863 impl<'a> DFA<&'a [u8]> {
864 /// Safely deserialize a sparse DFA with a specific state identifier
865 /// representation. Upon success, this returns both the deserialized DFA
866 /// and the number of bytes read from the given slice. Namely, the contents
867 /// of the slice beyond the DFA are not read.
868 ///
869 /// Deserializing a DFA using this routine will never allocate heap memory.
870 /// For safety purposes, the DFA's transitions will be verified such that
871 /// every transition points to a valid state. If this verification is too
872 /// costly, then a [`DFA::from_bytes_unchecked`] API is provided, which
873 /// will always execute in constant time.
874 ///
875 /// The bytes given must be generated by one of the serialization APIs
876 /// of a `DFA` using a semver compatible release of this crate. Those
877 /// include:
878 ///
879 /// * [`DFA::to_bytes_little_endian`]
880 /// * [`DFA::to_bytes_big_endian`]
881 /// * [`DFA::to_bytes_native_endian`]
882 /// * [`DFA::write_to_little_endian`]
883 /// * [`DFA::write_to_big_endian`]
884 /// * [`DFA::write_to_native_endian`]
885 ///
886 /// The `to_bytes` methods allocate and return a `Vec<u8>` for you. The
887 /// `write_to` methods do not allocate and write to an existing slice
888 /// (which may be on the stack). Since deserialization always uses the
889 /// native endianness of the target platform, the serialization API you use
890 /// should match the endianness of the target platform. (It's often a good
891 /// idea to generate serialized DFAs for both forms of endianness and then
892 /// load the correct one based on endianness.)
893 ///
894 /// # Errors
895 ///
896 /// Generally speaking, it's easier to state the conditions in which an
897 /// error is _not_ returned. All of the following must be true:
898 ///
899 /// * The bytes given must be produced by one of the serialization APIs
900 /// on this DFA, as mentioned above.
901 /// * The endianness of the target platform matches the endianness used to
902 /// serialized the provided DFA.
903 ///
904 /// If any of the above are not true, then an error will be returned.
905 ///
906 /// Note that unlike deserializing a
907 /// [`dense::DFA`](crate::dfa::dense::DFA), deserializing a sparse DFA has
908 /// no alignment requirements. That is, an alignment of `1` is valid.
909 ///
910 /// # Panics
911 ///
912 /// This routine will never panic for any input.
913 ///
914 /// # Example
915 ///
916 /// This example shows how to serialize a DFA to raw bytes, deserialize it
917 /// and then use it for searching.
918 ///
919 /// ```
920 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
921 ///
922 /// let initial = DFA::new("foo[0-9]+")?;
923 /// let bytes = initial.to_bytes_native_endian();
924 /// let dfa: DFA<&[u8]> = DFA::from_bytes(&bytes)?.0;
925 ///
926 /// let expected = Some(HalfMatch::must(0, 8));
927 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
928 /// # Ok::<(), Box<dyn std::error::Error>>(())
929 /// ```
930 ///
931 /// # Example: loading a DFA from static memory
932 ///
933 /// One use case this library supports is the ability to serialize a
934 /// DFA to disk and then use `include_bytes!` to store it in a compiled
935 /// Rust program. Those bytes can then be cheaply deserialized into a
936 /// `DFA` structure at runtime and used for searching without having to
937 /// re-compile the DFA (which can be quite costly).
938 ///
939 /// We can show this in two parts. The first part is serializing the DFA to
940 /// a file:
941 ///
942 /// ```no_run
943 /// use regex_automata::dfa::sparse::DFA;
944 ///
945 /// let dfa = DFA::new("foo[0-9]+")?;
946 ///
947 /// // Write a big endian serialized version of this DFA to a file.
948 /// let bytes = dfa.to_bytes_big_endian();
949 /// std::fs::write("foo.bigendian.dfa", &bytes)?;
950 ///
951 /// // Do it again, but this time for little endian.
952 /// let bytes = dfa.to_bytes_little_endian();
953 /// std::fs::write("foo.littleendian.dfa", &bytes)?;
954 /// # Ok::<(), Box<dyn std::error::Error>>(())
955 /// ```
956 ///
957 /// And now the second part is embedding the DFA into the compiled program
958 /// and deserializing it at runtime on first use. We use conditional
959 /// compilation to choose the correct endianness. We do not need to employ
960 /// any special tricks to ensure a proper alignment, since a sparse DFA has
961 /// no alignment requirements.
962 ///
963 /// ```no_run
964 /// use regex_automata::{
965 /// dfa::{Automaton, sparse::DFA},
966 /// util::lazy::Lazy,
967 /// HalfMatch, Input,
968 /// };
969 ///
970 /// // This crate provides its own "lazy" type, kind of like
971 /// // lazy_static! or once_cell::sync::Lazy. But it works in no-alloc
972 /// // no-std environments and let's us write this using completely
973 /// // safe code.
974 /// static RE: Lazy<DFA<&'static [u8]>> = Lazy::new(|| {
975 /// # const _: &str = stringify! {
976 /// #[cfg(target_endian = "big")]
977 /// static BYTES: &[u8] = include_bytes!("foo.bigendian.dfa");
978 /// #[cfg(target_endian = "little")]
979 /// static BYTES: &[u8] = include_bytes!("foo.littleendian.dfa");
980 /// # };
981 /// # static BYTES: &[u8] = b"";
982 ///
983 /// let (dfa, _) = DFA::from_bytes(BYTES)
984 /// .expect("serialized DFA should be valid");
985 /// dfa
986 /// });
987 ///
988 /// let expected = Ok(Some(HalfMatch::must(0, 8)));
989 /// assert_eq!(expected, RE.try_search_fwd(&Input::new("foo12345")));
990 /// ```
991 ///
992 /// Alternatively, consider using
993 /// [`lazy_static`](https://crates.io/crates/lazy_static)
994 /// or
995 /// [`once_cell`](https://crates.io/crates/once_cell),
996 /// which will guarantee safety for you.
997 pub fn from_bytes(
998 slice: &'a [u8],
999 ) -> Result<(DFA<&'a [u8]>, usize), DeserializeError> {
1000 // SAFETY: This is safe because we validate both the sparse transitions
1001 // (by trying to decode every state) and start state ID list below. If
1002 // either validation fails, then we return an error.
1003 let (dfa, nread) = unsafe { DFA::from_bytes_unchecked(slice)? };
1004 dfa.tt.validate(&dfa.special)?;
1005 dfa.st.validate(&dfa.special, &dfa.tt)?;
1006 // N.B. dfa.special doesn't have a way to do unchecked deserialization,
1007 // so it has already been validated.
1008 Ok((dfa, nread))
1009 }
1010
1011 /// Deserialize a DFA with a specific state identifier representation in
1012 /// constant time by omitting the verification of the validity of the
1013 /// sparse transitions.
1014 ///
1015 /// This is just like [`DFA::from_bytes`], except it can potentially return
1016 /// a DFA that exhibits undefined behavior if its transitions contains
1017 /// invalid state identifiers.
1018 ///
1019 /// This routine is useful if you need to deserialize a DFA cheaply and
1020 /// cannot afford the transition validation performed by `from_bytes`.
1021 ///
1022 /// # Safety
1023 ///
1024 /// This routine is not safe because it permits callers to provide
1025 /// arbitrary transitions with possibly incorrect state identifiers. While
1026 /// the various serialization routines will never return an incorrect
1027 /// DFA, there is no guarantee that the bytes provided here are correct.
1028 /// While `from_bytes_unchecked` will still do several forms of basic
1029 /// validation, this routine does not check that the transitions themselves
1030 /// are correct. Given an incorrect transition table, it is possible for
1031 /// the search routines to access out-of-bounds memory because of explicit
1032 /// bounds check elision.
1033 ///
1034 /// # Example
1035 ///
1036 /// ```
1037 /// use regex_automata::{dfa::{Automaton, sparse::DFA}, HalfMatch, Input};
1038 ///
1039 /// let initial = DFA::new("foo[0-9]+")?;
1040 /// let bytes = initial.to_bytes_native_endian();
1041 /// // SAFETY: This is guaranteed to be safe since the bytes given come
1042 /// // directly from a compatible serialization routine.
1043 /// let dfa: DFA<&[u8]> = unsafe { DFA::from_bytes_unchecked(&bytes)?.0 };
1044 ///
1045 /// let expected = Some(HalfMatch::must(0, 8));
1046 /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
1047 /// # Ok::<(), Box<dyn std::error::Error>>(())
1048 /// ```
1049 pub unsafe fn from_bytes_unchecked(
1050 slice: &'a [u8],
1051 ) -> Result<(DFA<&'a [u8]>, usize), DeserializeError> {
1052 let mut nr = 0;
1053
1054 nr += wire::read_label(&slice[nr..], LABEL)?;
1055 nr += wire::read_endianness_check(&slice[nr..])?;
1056 nr += wire::read_version(&slice[nr..], VERSION)?;
1057
1058 let _unused = wire::try_read_u32(&slice[nr..], "unused space")?;
1059 nr += size_of::<u32>();
1060
1061 let (flags, nread) = Flags::from_bytes(&slice[nr..])?;
1062 nr += nread;
1063
1064 let (tt, nread) = Transitions::from_bytes_unchecked(&slice[nr..])?;
1065 nr += nread;
1066
1067 let (st, nread) = StartTable::from_bytes_unchecked(&slice[nr..])?;
1068 nr += nread;
1069
1070 let (special, nread) = Special::from_bytes(&slice[nr..])?;
1071 nr += nread;
1072 if special.max.as_usize() >= tt.sparse().len() {
1073 return Err(DeserializeError::generic(
1074 "max should not be greater than or equal to sparse bytes",
1075 ));
1076 }
1077
1078 let (quitset, nread) = ByteSet::from_bytes(&slice[nr..])?;
1079 nr += nread;
1080
1081 // Prefilters don't support serialization, so they're always absent.
1082 let pre = None;
1083 Ok((DFA { tt, st, special, pre, quitset, flags }, nr))
1084 }
1085 }
1086
1087 impl<T: AsRef<[u8]>> fmt::Debug for DFA<T> {
1088 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1089 writeln!(f, "sparse::DFA(")?;
1090 for state in self.tt.states() {
1091 fmt_state_indicator(f, self, state.id())?;
1092 writeln!(f, "{:06?}: {:?}", state.id().as_usize(), state)?;
1093 }
1094 writeln!(f, "")?;
1095 for (i, (start_id, anchored, sty)) in self.st.iter().enumerate() {
1096 if i % self.st.stride == 0 {
1097 match anchored {
1098 Anchored::No => writeln!(f, "START-GROUP(unanchored)")?,
1099 Anchored::Yes => writeln!(f, "START-GROUP(anchored)")?,
1100 Anchored::Pattern(pid) => writeln!(
1101 f,
1102 "START_GROUP(pattern: {:?})",
1103 pid.as_usize()
1104 )?,
1105 }
1106 }
1107 writeln!(f, " {:?} => {:06?}", sty, start_id.as_usize())?;
1108 }
1109 writeln!(f, "state length: {:?}", self.tt.state_len)?;
1110 writeln!(f, "pattern length: {:?}", self.pattern_len())?;
1111 writeln!(f, "flags: {:?}", self.flags)?;
1112 writeln!(f, ")")?;
1113 Ok(())
1114 }
1115 }
1116
1117 // SAFETY: We assert that our implementation of each method is correct.
1118 unsafe impl<T: AsRef<[u8]>> Automaton for DFA<T> {
1119 #[inline]
1120 fn is_special_state(&self, id: StateID) -> bool {
1121 self.special.is_special_state(id)
1122 }
1123
1124 #[inline]
1125 fn is_dead_state(&self, id: StateID) -> bool {
1126 self.special.is_dead_state(id)
1127 }
1128
1129 #[inline]
1130 fn is_quit_state(&self, id: StateID) -> bool {
1131 self.special.is_quit_state(id)
1132 }
1133
1134 #[inline]
1135 fn is_match_state(&self, id: StateID) -> bool {
1136 self.special.is_match_state(id)
1137 }
1138
1139 #[inline]
1140 fn is_start_state(&self, id: StateID) -> bool {
1141 self.special.is_start_state(id)
1142 }
1143
1144 #[inline]
1145 fn is_accel_state(&self, id: StateID) -> bool {
1146 self.special.is_accel_state(id)
1147 }
1148
1149 // This is marked as inline to help dramatically boost sparse searching,
1150 // which decodes each state it enters to follow the next transition.
1151 #[cfg_attr(feature = "perf-inline", inline(always))]
1152 fn next_state(&self, current: StateID, input: u8) -> StateID {
1153 let input = self.tt.classes.get(input);
1154 self.tt.state(current).next(input)
1155 }
1156
1157 #[inline]
1158 unsafe fn next_state_unchecked(
1159 &self,
1160 current: StateID,
1161 input: u8,
1162 ) -> StateID {
1163 self.next_state(current, input)
1164 }
1165
1166 #[inline]
1167 fn next_eoi_state(&self, current: StateID) -> StateID {
1168 self.tt.state(current).next_eoi()
1169 }
1170
1171 #[inline]
1172 fn pattern_len(&self) -> usize {
1173 self.tt.pattern_len
1174 }
1175
1176 #[inline]
1177 fn match_len(&self, id: StateID) -> usize {
1178 self.tt.state(id).pattern_len()
1179 }
1180
1181 #[inline]
1182 fn match_pattern(&self, id: StateID, match_index: usize) -> PatternID {
1183 // This is an optimization for the very common case of a DFA with a
1184 // single pattern. This conditional avoids a somewhat more costly path
1185 // that finds the pattern ID from the state machine, which requires
1186 // a bit of slicing/pointer-chasing. This optimization tends to only
1187 // matter when matches are frequent.
1188 if self.tt.pattern_len == 1 {
1189 return PatternID::ZERO;
1190 }
1191 self.tt.state(id).pattern_id(match_index)
1192 }
1193
1194 #[inline]
1195 fn has_empty(&self) -> bool {
1196 self.flags.has_empty
1197 }
1198
1199 #[inline]
1200 fn is_utf8(&self) -> bool {
1201 self.flags.is_utf8
1202 }
1203
1204 #[inline]
1205 fn is_always_start_anchored(&self) -> bool {
1206 self.flags.is_always_start_anchored
1207 }
1208
1209 #[inline]
1210 fn start_state_forward(
1211 &self,
1212 input: &Input<'_>,
1213 ) -> Result<StateID, MatchError> {
1214 if !self.quitset.is_empty() && input.start() > 0 {
1215 let offset = input.start() - 1;
1216 let byte = input.haystack()[offset];
1217 if self.quitset.contains(byte) {
1218 return Err(MatchError::quit(byte, offset));
1219 }
1220 }
1221 let start = self.st.start_map.fwd(&input);
1222 self.st.start(input, start)
1223 }
1224
1225 #[inline]
1226 fn start_state_reverse(
1227 &self,
1228 input: &Input<'_>,
1229 ) -> Result<StateID, MatchError> {
1230 if !self.quitset.is_empty() && input.end() < input.haystack().len() {
1231 let offset = input.end();
1232 let byte = input.haystack()[offset];
1233 if self.quitset.contains(byte) {
1234 return Err(MatchError::quit(byte, offset));
1235 }
1236 }
1237 let start = self.st.start_map.rev(&input);
1238 self.st.start(input, start)
1239 }
1240
1241 #[inline]
1242 fn universal_start_state(&self, mode: Anchored) -> Option<StateID> {
1243 match mode {
1244 Anchored::No => self.st.universal_start_unanchored,
1245 Anchored::Yes => self.st.universal_start_anchored,
1246 Anchored::Pattern(_) => None,
1247 }
1248 }
1249
1250 #[inline]
1251 fn accelerator(&self, id: StateID) -> &[u8] {
1252 self.tt.state(id).accelerator()
1253 }
1254
1255 #[inline]
1256 fn get_prefilter(&self) -> Option<&Prefilter> {
1257 self.pre.as_ref()
1258 }
1259 }
1260
1261 /// The transition table portion of a sparse DFA.
1262 ///
1263 /// The transition table is the core part of the DFA in that it describes how
1264 /// to move from one state to another based on the input sequence observed.
1265 ///
1266 /// Unlike a typical dense table based DFA, states in a sparse transition
1267 /// table have variable size. That is, states with more transitions use more
1268 /// space than states with fewer transitions. This means that finding the next
1269 /// transition takes more work than with a dense DFA, but also typically uses
1270 /// much less space.
1271 #[derive(Clone)]
1272 struct Transitions<T> {
1273 /// The raw encoding of each state in this DFA.
1274 ///
1275 /// Each state has the following information:
1276 ///
1277 /// * A set of transitions to subsequent states. Transitions to the dead
1278 /// state are omitted.
1279 /// * If the state can be accelerated, then any additional accelerator
1280 /// information.
1281 /// * If the state is a match state, then the state contains all pattern
1282 /// IDs that match when in that state.
1283 ///
1284 /// To decode a state, use Transitions::state.
1285 ///
1286 /// In practice, T is either Vec<u8> or &[u8].
1287 sparse: T,
1288 /// A set of equivalence classes, where a single equivalence class
1289 /// represents a set of bytes that never discriminate between a match
1290 /// and a non-match in the DFA. Each equivalence class corresponds to a
1291 /// single character in this DFA's alphabet, where the maximum number of
1292 /// characters is 257 (each possible value of a byte plus the special
1293 /// EOI transition). Consequently, the number of equivalence classes
1294 /// corresponds to the number of transitions for each DFA state. Note
1295 /// though that the *space* used by each DFA state in the transition table
1296 /// may be larger. The total space used by each DFA state is known as the
1297 /// stride and is documented above.
1298 ///
1299 /// The only time the number of equivalence classes is fewer than 257 is
1300 /// if the DFA's kind uses byte classes which is the default. Equivalence
1301 /// classes should generally only be disabled when debugging, so that
1302 /// the transitions themselves aren't obscured. Disabling them has no
1303 /// other benefit, since the equivalence class map is always used while
1304 /// searching. In the vast majority of cases, the number of equivalence
1305 /// classes is substantially smaller than 257, particularly when large
1306 /// Unicode classes aren't used.
1307 ///
1308 /// N.B. Equivalence classes aren't particularly useful in a sparse DFA
1309 /// in the current implementation, since equivalence classes generally tend
1310 /// to correspond to continuous ranges of bytes that map to the same
1311 /// transition. So in a sparse DFA, equivalence classes don't really lead
1312 /// to a space savings. In the future, it would be good to try and remove
1313 /// them from sparse DFAs entirely, but requires a bit of work since sparse
1314 /// DFAs are built from dense DFAs, which are in turn built on top of
1315 /// equivalence classes.
1316 classes: ByteClasses,
1317 /// The total number of states in this DFA. Note that a DFA always has at
1318 /// least one state---the dead state---even the empty DFA. In particular,
1319 /// the dead state always has ID 0 and is correspondingly always the first
1320 /// state. The dead state is never a match state.
1321 state_len: usize,
1322 /// The total number of unique patterns represented by these match states.
1323 pattern_len: usize,
1324 }
1325
1326 impl<'a> Transitions<&'a [u8]> {
1327 unsafe fn from_bytes_unchecked(
1328 mut slice: &'a [u8],
1329 ) -> Result<(Transitions<&'a [u8]>, usize), DeserializeError> {
1330 let slice_start = slice.as_ptr().as_usize();
1331
1332 let (state_len, nr) =
1333 wire::try_read_u32_as_usize(&slice, "state length")?;
1334 slice = &slice[nr..];
1335
1336 let (pattern_len, nr) =
1337 wire::try_read_u32_as_usize(&slice, "pattern length")?;
1338 slice = &slice[nr..];
1339
1340 let (classes, nr) = ByteClasses::from_bytes(&slice)?;
1341 slice = &slice[nr..];
1342
1343 let (len, nr) =
1344 wire::try_read_u32_as_usize(&slice, "sparse transitions length")?;
1345 slice = &slice[nr..];
1346
1347 wire::check_slice_len(slice, len, "sparse states byte length")?;
1348 let sparse = &slice[..len];
1349 slice = &slice[len..];
1350
1351 let trans = Transitions { sparse, classes, state_len, pattern_len };
1352 Ok((trans, slice.as_ptr().as_usize() - slice_start))
1353 }
1354 }
1355
1356 impl<T: AsRef<[u8]>> Transitions<T> {
1357 /// Writes a serialized form of this transition table to the buffer given.
1358 /// If the buffer is too small, then an error is returned. To determine
1359 /// how big the buffer must be, use `write_to_len`.
1360 fn write_to<E: Endian>(
1361 &self,
1362 mut dst: &mut [u8],
1363 ) -> Result<usize, SerializeError> {
1364 let nwrite = self.write_to_len();
1365 if dst.len() < nwrite {
1366 return Err(SerializeError::buffer_too_small(
1367 "sparse transition table",
1368 ));
1369 }
1370 dst = &mut dst[..nwrite];
1371
1372 // write state length
1373 E::write_u32(u32::try_from(self.state_len).unwrap(), dst);
1374 dst = &mut dst[size_of::<u32>()..];
1375
1376 // write pattern length
1377 E::write_u32(u32::try_from(self.pattern_len).unwrap(), dst);
1378 dst = &mut dst[size_of::<u32>()..];
1379
1380 // write byte class map
1381 let n = self.classes.write_to(dst)?;
1382 dst = &mut dst[n..];
1383
1384 // write number of bytes in sparse transitions
1385 E::write_u32(u32::try_from(self.sparse().len()).unwrap(), dst);
1386 dst = &mut dst[size_of::<u32>()..];
1387
1388 // write actual transitions
1389 let mut id = DEAD;
1390 while id.as_usize() < self.sparse().len() {
1391 let state = self.state(id);
1392 let n = state.write_to::<E>(&mut dst)?;
1393 dst = &mut dst[n..];
1394 // The next ID is the offset immediately following `state`.
1395 id = StateID::new(id.as_usize() + state.write_to_len()).unwrap();
1396 }
1397 Ok(nwrite)
1398 }
1399
1400 /// Returns the number of bytes the serialized form of this transition
1401 /// table will use.
1402 fn write_to_len(&self) -> usize {
1403 size_of::<u32>() // state length
1404 + size_of::<u32>() // pattern length
1405 + self.classes.write_to_len()
1406 + size_of::<u32>() // sparse transitions length
1407 + self.sparse().len()
1408 }
1409
1410 /// Validates that every state ID in this transition table is valid.
1411 ///
1412 /// That is, every state ID can be used to correctly index a state in this
1413 /// table.
1414 fn validate(&self, sp: &Special) -> Result<(), DeserializeError> {
1415 // In order to validate everything, we not only need to make sure we
1416 // can decode every state, but that every transition in every state
1417 // points to a valid state. There are many duplicative transitions, so
1418 // we record state IDs that we've verified so that we don't redo the
1419 // decoding work.
1420 //
1421 // Except, when in no_std mode, we don't have dynamic memory allocation
1422 // available to us, so we skip this optimization. It's not clear
1423 // whether doing something more clever is worth it just yet. If you're
1424 // profiling this code and need it to run faster, please file an issue.
1425 //
1426 // OK, so we also use this to record the set of valid state IDs. Since
1427 // it is possible for a transition to point to an invalid state ID that
1428 // still (somehow) deserializes to a valid state. So we need to make
1429 // sure our transitions are limited to actually correct state IDs.
1430 // The problem is, I'm not sure how to do this verification step in
1431 // no-std no-alloc mode. I think we'd *have* to store the set of valid
1432 // state IDs in the DFA itself. For now, we don't do this verification
1433 // in no-std no-alloc mode. The worst thing that can happen is an
1434 // incorrect result. But no panics or memory safety problems should
1435 // result. Because we still do validate that the state itself is
1436 // "valid" in the sense that everything it points to actually exists.
1437 //
1438 // ---AG
1439 struct Seen {
1440 #[cfg(feature = "alloc")]
1441 set: alloc::collections::BTreeSet<StateID>,
1442 #[cfg(not(feature = "alloc"))]
1443 set: core::marker::PhantomData<StateID>,
1444 }
1445
1446 #[cfg(feature = "alloc")]
1447 impl Seen {
1448 fn new() -> Seen {
1449 Seen { set: alloc::collections::BTreeSet::new() }
1450 }
1451 fn insert(&mut self, id: StateID) {
1452 self.set.insert(id);
1453 }
1454 fn contains(&self, id: &StateID) -> bool {
1455 self.set.contains(id)
1456 }
1457 }
1458
1459 #[cfg(not(feature = "alloc"))]
1460 impl Seen {
1461 fn new() -> Seen {
1462 Seen { set: core::marker::PhantomData }
1463 }
1464 fn insert(&mut self, _id: StateID) {}
1465 fn contains(&self, _id: &StateID) -> bool {
1466 false
1467 }
1468 }
1469
1470 let mut verified: Seen = Seen::new();
1471 // We need to make sure that we decode the correct number of states.
1472 // Otherwise, an empty set of transitions would validate even if the
1473 // recorded state length is non-empty.
1474 let mut len = 0;
1475 // We can't use the self.states() iterator because it assumes the state
1476 // encodings are valid. It could panic if they aren't.
1477 let mut id = DEAD;
1478 while id.as_usize() < self.sparse().len() {
1479 // Before we even decode the state, we check that the ID itself
1480 // is well formed. That is, if it's a special state then it must
1481 // actually be a quit, dead, accel, match or start state.
1482 if sp.is_special_state(id) {
1483 let is_actually_special = sp.is_dead_state(id)
1484 || sp.is_quit_state(id)
1485 || sp.is_match_state(id)
1486 || sp.is_start_state(id)
1487 || sp.is_accel_state(id);
1488 if !is_actually_special {
1489 // This is kind of a cryptic error message...
1490 return Err(DeserializeError::generic(
1491 "found sparse state tagged as special but \
1492 wasn't actually special",
1493 ));
1494 }
1495 }
1496 let state = self.try_state(sp, id)?;
1497 verified.insert(id);
1498 // The next ID should be the offset immediately following `state`.
1499 id = StateID::new(wire::add(
1500 id.as_usize(),
1501 state.write_to_len(),
1502 "next state ID offset",
1503 )?)
1504 .map_err(|err| {
1505 DeserializeError::state_id_error(err, "next state ID offset")
1506 })?;
1507 len += 1;
1508 }
1509 // Now that we've checked that all top-level states are correct and
1510 // importantly, collected a set of valid state IDs, we have all the
1511 // information we need to check that all transitions are correct too.
1512 //
1513 // Note that we can't use `valid_ids` to iterate because it will
1514 // be empty in no-std no-alloc contexts. (And yes, that means our
1515 // verification isn't quite as good.) We can use `self.states()`
1516 // though at least, since we know that all states can at least be
1517 // decoded and traversed correctly.
1518 for state in self.states() {
1519 // Check that all transitions in this state are correct.
1520 for i in 0..state.ntrans {
1521 let to = state.next_at(i);
1522 // For no-alloc, we just check that the state can decode. It is
1523 // technically possible that the state ID could still point to
1524 // a non-existent state even if it decodes (fuzzing proved this
1525 // to be true), but it shouldn't result in any memory unsafety
1526 // or panics in non-debug mode.
1527 #[cfg(not(feature = "alloc"))]
1528 {
1529 let _ = self.try_state(sp, to)?;
1530 }
1531 #[cfg(feature = "alloc")]
1532 {
1533 if !verified.contains(&to) {
1534 return Err(DeserializeError::generic(
1535 "found transition that points to a \
1536 non-existent state",
1537 ));
1538 }
1539 }
1540 }
1541 }
1542 if len != self.state_len {
1543 return Err(DeserializeError::generic(
1544 "mismatching sparse state length",
1545 ));
1546 }
1547 Ok(())
1548 }
1549
1550 /// Converts these transitions to a borrowed value.
1551 fn as_ref(&self) -> Transitions<&'_ [u8]> {
1552 Transitions {
1553 sparse: self.sparse(),
1554 classes: self.classes.clone(),
1555 state_len: self.state_len,
1556 pattern_len: self.pattern_len,
1557 }
1558 }
1559
1560 /// Converts these transitions to an owned value.
1561 #[cfg(feature = "alloc")]
1562 fn to_owned(&self) -> Transitions<alloc::vec::Vec<u8>> {
1563 Transitions {
1564 sparse: self.sparse().to_vec(),
1565 classes: self.classes.clone(),
1566 state_len: self.state_len,
1567 pattern_len: self.pattern_len,
1568 }
1569 }
1570
1571 /// Return a convenient representation of the given state.
1572 ///
1573 /// This panics if the state is invalid.
1574 ///
1575 /// This is marked as inline to help dramatically boost sparse searching,
1576 /// which decodes each state it enters to follow the next transition. Other
1577 /// functions involved are also inlined, which should hopefully eliminate
1578 /// a lot of the extraneous decoding that is never needed just to follow
1579 /// the next transition.
1580 #[cfg_attr(feature = "perf-inline", inline(always))]
1581 fn state(&self, id: StateID) -> State<'_> {
1582 let mut state = &self.sparse()[id.as_usize()..];
1583 let mut ntrans = wire::read_u16(&state).as_usize();
1584 let is_match = (1 << 15) & ntrans != 0;
1585 ntrans &= !(1 << 15);
1586 state = &state[2..];
1587
1588 let (input_ranges, state) = state.split_at(ntrans * 2);
1589 let (next, state) = state.split_at(ntrans * StateID::SIZE);
1590 let (pattern_ids, state) = if is_match {
1591 let npats = wire::read_u32(&state).as_usize();
1592 state[4..].split_at(npats * 4)
1593 } else {
1594 (&[][..], state)
1595 };
1596
1597 let accel_len = usize::from(state[0]);
1598 let accel = &state[1..accel_len + 1];
1599 State { id, is_match, ntrans, input_ranges, next, pattern_ids, accel }
1600 }
1601
1602 /// Like `state`, but will return an error if the state encoding is
1603 /// invalid. This is useful for verifying states after deserialization,
1604 /// which is required for a safe deserialization API.
1605 ///
1606 /// Note that this only verifies that this state is decodable and that
1607 /// all of its data is consistent. It does not verify that its state ID
1608 /// transitions point to valid states themselves, nor does it verify that
1609 /// every pattern ID is valid.
1610 fn try_state(
1611 &self,
1612 sp: &Special,
1613 id: StateID,
1614 ) -> Result<State<'_>, DeserializeError> {
1615 if id.as_usize() > self.sparse().len() {
1616 return Err(DeserializeError::generic(
1617 "invalid caller provided sparse state ID",
1618 ));
1619 }
1620 let mut state = &self.sparse()[id.as_usize()..];
1621 // Encoding format starts with a u16 that stores the total number of
1622 // transitions in this state.
1623 let (mut ntrans, _) =
1624 wire::try_read_u16_as_usize(state, "state transition length")?;
1625 let is_match = ((1 << 15) & ntrans) != 0;
1626 ntrans &= !(1 << 15);
1627 state = &state[2..];
1628 if ntrans > 257 || ntrans == 0 {
1629 return Err(DeserializeError::generic(
1630 "invalid transition length",
1631 ));
1632 }
1633 if is_match && !sp.is_match_state(id) {
1634 return Err(DeserializeError::generic(
1635 "state marked as match but not in match ID range",
1636 ));
1637 } else if !is_match && sp.is_match_state(id) {
1638 return Err(DeserializeError::generic(
1639 "state in match ID range but not marked as match state",
1640 ));
1641 }
1642
1643 // Each transition has two pieces: an inclusive range of bytes on which
1644 // it is defined, and the state ID that those bytes transition to. The
1645 // pairs come first, followed by a corresponding sequence of state IDs.
1646 let input_ranges_len = ntrans.checked_mul(2).unwrap();
1647 wire::check_slice_len(state, input_ranges_len, "sparse byte pairs")?;
1648 let (input_ranges, state) = state.split_at(input_ranges_len);
1649 // Every range should be of the form A-B, where A<=B.
1650 for pair in input_ranges.chunks(2) {
1651 let (start, end) = (pair[0], pair[1]);
1652 if start > end {
1653 return Err(DeserializeError::generic("invalid input range"));
1654 }
1655 }
1656
1657 // And now extract the corresponding sequence of state IDs. We leave
1658 // this sequence as a &[u8] instead of a &[S] because sparse DFAs do
1659 // not have any alignment requirements.
1660 let next_len = ntrans
1661 .checked_mul(self.id_len())
1662 .expect("state size * #trans should always fit in a usize");
1663 wire::check_slice_len(state, next_len, "sparse trans state IDs")?;
1664 let (next, state) = state.split_at(next_len);
1665 // We can at least verify that every state ID is in bounds.
1666 for idbytes in next.chunks(self.id_len()) {
1667 let (id, _) =
1668 wire::read_state_id(idbytes, "sparse state ID in try_state")?;
1669 wire::check_slice_len(
1670 self.sparse(),
1671 id.as_usize(),
1672 "invalid sparse state ID",
1673 )?;
1674 }
1675
1676 // If this is a match state, then read the pattern IDs for this state.
1677 // Pattern IDs is a u32-length prefixed sequence of native endian
1678 // encoded 32-bit integers.
1679 let (pattern_ids, state) = if is_match {
1680 let (npats, nr) =
1681 wire::try_read_u32_as_usize(state, "pattern ID length")?;
1682 let state = &state[nr..];
1683 if npats == 0 {
1684 return Err(DeserializeError::generic(
1685 "state marked as a match, but has no pattern IDs",
1686 ));
1687 }
1688
1689 let pattern_ids_len =
1690 wire::mul(npats, 4, "sparse pattern ID byte length")?;
1691 wire::check_slice_len(
1692 state,
1693 pattern_ids_len,
1694 "sparse pattern IDs",
1695 )?;
1696 let (pattern_ids, state) = state.split_at(pattern_ids_len);
1697 for patbytes in pattern_ids.chunks(PatternID::SIZE) {
1698 wire::read_pattern_id(
1699 patbytes,
1700 "sparse pattern ID in try_state",
1701 )?;
1702 }
1703 (pattern_ids, state)
1704 } else {
1705 (&[][..], state)
1706 };
1707
1708 // Now read this state's accelerator info. The first byte is the length
1709 // of the accelerator, which is typically 0 (for no acceleration) but
1710 // is no bigger than 3. The length indicates the number of bytes that
1711 // follow, where each byte corresponds to a transition out of this
1712 // state.
1713 if state.is_empty() {
1714 return Err(DeserializeError::generic("no accelerator length"));
1715 }
1716 let (accel_len, state) = (usize::from(state[0]), &state[1..]);
1717
1718 if accel_len > 3 {
1719 return Err(DeserializeError::generic(
1720 "sparse invalid accelerator length",
1721 ));
1722 } else if accel_len == 0 && sp.is_accel_state(id) {
1723 return Err(DeserializeError::generic(
1724 "got no accelerators in state, but in accelerator ID range",
1725 ));
1726 } else if accel_len > 0 && !sp.is_accel_state(id) {
1727 return Err(DeserializeError::generic(
1728 "state in accelerator ID range, but has no accelerators",
1729 ));
1730 }
1731
1732 wire::check_slice_len(
1733 state,
1734 accel_len,
1735 "sparse corrupt accelerator length",
1736 )?;
1737 let (accel, _) = (&state[..accel_len], &state[accel_len..]);
1738
1739 let state = State {
1740 id,
1741 is_match,
1742 ntrans,
1743 input_ranges,
1744 next,
1745 pattern_ids,
1746 accel,
1747 };
1748 if sp.is_quit_state(state.next_at(state.ntrans - 1)) {
1749 return Err(DeserializeError::generic(
1750 "state with EOI transition to quit state is illegal",
1751 ));
1752 }
1753 Ok(state)
1754 }
1755
1756 /// Return an iterator over all of the states in this DFA.
1757 ///
1758 /// The iterator returned yields tuples, where the first element is the
1759 /// state ID and the second element is the state itself.
1760 fn states(&self) -> StateIter<'_, T> {
1761 StateIter { trans: self, id: DEAD.as_usize() }
1762 }
1763
1764 /// Returns the sparse transitions as raw bytes.
1765 fn sparse(&self) -> &[u8] {
1766 self.sparse.as_ref()
1767 }
1768
1769 /// Returns the number of bytes represented by a single state ID.
1770 fn id_len(&self) -> usize {
1771 StateID::SIZE
1772 }
1773
1774 /// Return the memory usage, in bytes, of these transitions.
1775 ///
1776 /// This does not include the size of a `Transitions` value itself.
1777 fn memory_usage(&self) -> usize {
1778 self.sparse().len()
1779 }
1780 }
1781
1782 #[cfg(feature = "dfa-build")]
1783 impl<T: AsMut<[u8]>> Transitions<T> {
1784 /// Return a convenient mutable representation of the given state.
1785 /// This panics if the state is invalid.
1786 fn state_mut(&mut self, id: StateID) -> StateMut<'_> {
1787 let mut state = &mut self.sparse_mut()[id.as_usize()..];
1788 let mut ntrans = wire::read_u16(&state).as_usize();
1789 let is_match = (1 << 15) & ntrans != 0;
1790 ntrans &= !(1 << 15);
1791 state = &mut state[2..];
1792
1793 let (input_ranges, state) = state.split_at_mut(ntrans * 2);
1794 let (next, state) = state.split_at_mut(ntrans * StateID::SIZE);
1795 let (pattern_ids, state) = if is_match {
1796 let npats = wire::read_u32(&state).as_usize();
1797 state[4..].split_at_mut(npats * 4)
1798 } else {
1799 (&mut [][..], state)
1800 };
1801
1802 let accel_len = usize::from(state[0]);
1803 let accel = &mut state[1..accel_len + 1];
1804 StateMut {
1805 id,
1806 is_match,
1807 ntrans,
1808 input_ranges,
1809 next,
1810 pattern_ids,
1811 accel,
1812 }
1813 }
1814
1815 /// Returns the sparse transitions as raw mutable bytes.
1816 fn sparse_mut(&mut self) -> &mut [u8] {
1817 self.sparse.as_mut()
1818 }
1819 }
1820
1821 /// The set of all possible starting states in a DFA.
1822 ///
1823 /// See the eponymous type in the `dense` module for more details. This type
1824 /// is very similar to `dense::StartTable`, except that its underlying
1825 /// representation is `&[u8]` instead of `&[S]`. (The latter would require
1826 /// sparse DFAs to be aligned, which is explicitly something we do not require
1827 /// because we don't really need it.)
1828 #[derive(Clone)]
1829 struct StartTable<T> {
1830 /// The initial start state IDs as a contiguous table of native endian
1831 /// encoded integers, represented by `S`.
1832 ///
1833 /// In practice, T is either Vec<u8> or &[u8] and has no alignment
1834 /// requirements.
1835 ///
1836 /// The first `2 * stride` (currently always 8) entries always correspond
1837 /// to the starts states for the entire DFA, with the first 4 entries being
1838 /// for unanchored searches and the second 4 entries being for anchored
1839 /// searches. To keep things simple, we always use 8 entries even if the
1840 /// `StartKind` is not both.
1841 ///
1842 /// After that, there are `stride * patterns` state IDs, where `patterns`
1843 /// may be zero in the case of a DFA with no patterns or in the case where
1844 /// the DFA was built without enabling starting states for each pattern.
1845 table: T,
1846 /// The starting state configuration supported. When 'both', both
1847 /// unanchored and anchored searches work. When 'unanchored', anchored
1848 /// searches panic. When 'anchored', unanchored searches panic.
1849 kind: StartKind,
1850 /// The start state configuration for every possible byte.
1851 start_map: StartByteMap,
1852 /// The number of starting state IDs per pattern.
1853 stride: usize,
1854 /// The total number of patterns for which starting states are encoded.
1855 /// This is `None` for DFAs that were built without start states for each
1856 /// pattern. Thus, one cannot use this field to say how many patterns
1857 /// are in the DFA in all cases. It is specific to how many patterns are
1858 /// represented in this start table.
1859 pattern_len: Option<usize>,
1860 /// The universal starting state for unanchored searches. This is only
1861 /// present when the DFA supports unanchored searches and when all starting
1862 /// state IDs for an unanchored search are equivalent.
1863 universal_start_unanchored: Option<StateID>,
1864 /// The universal starting state for anchored searches. This is only
1865 /// present when the DFA supports anchored searches and when all starting
1866 /// state IDs for an anchored search are equivalent.
1867 universal_start_anchored: Option<StateID>,
1868 }
1869
1870 #[cfg(feature = "dfa-build")]
1871 impl StartTable<Vec<u8>> {
1872 fn new<T: AsRef<[u32]>>(
1873 dfa: &dense::DFA<T>,
1874 pattern_len: Option<usize>,
1875 ) -> StartTable<Vec<u8>> {
1876 let stride = Start::len();
1877 // This is OK since the only way we're here is if a dense DFA could be
1878 // constructed successfully, which uses the same space.
1879 let len = stride
1880 .checked_mul(pattern_len.unwrap_or(0))
1881 .unwrap()
1882 .checked_add(stride.checked_mul(2).unwrap())
1883 .unwrap()
1884 .checked_mul(StateID::SIZE)
1885 .unwrap();
1886 StartTable {
1887 table: vec![0; len],
1888 kind: dfa.start_kind(),
1889 start_map: dfa.start_map().clone(),
1890 stride,
1891 pattern_len,
1892 universal_start_unanchored: dfa
1893 .universal_start_state(Anchored::No),
1894 universal_start_anchored: dfa.universal_start_state(Anchored::Yes),
1895 }
1896 }
1897
1898 fn from_dense_dfa<T: AsRef<[u32]>>(
1899 dfa: &dense::DFA<T>,
1900 remap: &[StateID],
1901 ) -> Result<StartTable<Vec<u8>>, BuildError> {
1902 // Unless the DFA has start states compiled for each pattern, then
1903 // as far as the starting state table is concerned, there are zero
1904 // patterns to account for. It will instead only store starting states
1905 // for the entire DFA.
1906 let start_pattern_len = if dfa.starts_for_each_pattern() {
1907 Some(dfa.pattern_len())
1908 } else {
1909 None
1910 };
1911 let mut sl = StartTable::new(dfa, start_pattern_len);
1912 for (old_start_id, anchored, sty) in dfa.starts() {
1913 let new_start_id = remap[dfa.to_index(old_start_id)];
1914 sl.set_start(anchored, sty, new_start_id);
1915 }
1916 Ok(sl)
1917 }
1918 }
1919
1920 impl<'a> StartTable<&'a [u8]> {
1921 unsafe fn from_bytes_unchecked(
1922 mut slice: &'a [u8],
1923 ) -> Result<(StartTable<&'a [u8]>, usize), DeserializeError> {
1924 let slice_start = slice.as_ptr().as_usize();
1925
1926 let (kind, nr) = StartKind::from_bytes(slice)?;
1927 slice = &slice[nr..];
1928
1929 let (start_map, nr) = StartByteMap::from_bytes(slice)?;
1930 slice = &slice[nr..];
1931
1932 let (stride, nr) =
1933 wire::try_read_u32_as_usize(slice, "sparse start table stride")?;
1934 slice = &slice[nr..];
1935 if stride != Start::len() {
1936 return Err(DeserializeError::generic(
1937 "invalid sparse starting table stride",
1938 ));
1939 }
1940
1941 let (maybe_pattern_len, nr) =
1942 wire::try_read_u32_as_usize(slice, "sparse start table patterns")?;
1943 slice = &slice[nr..];
1944 let pattern_len = if maybe_pattern_len.as_u32() == u32::MAX {
1945 None
1946 } else {
1947 Some(maybe_pattern_len)
1948 };
1949 if pattern_len.map_or(false, |len| len > PatternID::LIMIT) {
1950 return Err(DeserializeError::generic(
1951 "sparse invalid number of patterns",
1952 ));
1953 }
1954
1955 let (universal_unanchored, nr) =
1956 wire::try_read_u32(slice, "universal unanchored start")?;
1957 slice = &slice[nr..];
1958 let universal_start_unanchored = if universal_unanchored == u32::MAX {
1959 None
1960 } else {
1961 Some(StateID::try_from(universal_unanchored).map_err(|e| {
1962 DeserializeError::state_id_error(
1963 e,
1964 "universal unanchored start",
1965 )
1966 })?)
1967 };
1968
1969 let (universal_anchored, nr) =
1970 wire::try_read_u32(slice, "universal anchored start")?;
1971 slice = &slice[nr..];
1972 let universal_start_anchored = if universal_anchored == u32::MAX {
1973 None
1974 } else {
1975 Some(StateID::try_from(universal_anchored).map_err(|e| {
1976 DeserializeError::state_id_error(e, "universal anchored start")
1977 })?)
1978 };
1979
1980 let pattern_table_size = wire::mul(
1981 stride,
1982 pattern_len.unwrap_or(0),
1983 "sparse invalid pattern length",
1984 )?;
1985 // Our start states always start with a single stride of start states
1986 // for the entire automaton which permit it to match any pattern. What
1987 // follows it are an optional set of start states for each pattern.
1988 let start_state_len = wire::add(
1989 wire::mul(2, stride, "start state stride too big")?,
1990 pattern_table_size,
1991 "sparse invalid 'any' pattern starts size",
1992 )?;
1993 let table_bytes_len = wire::mul(
1994 start_state_len,
1995 StateID::SIZE,
1996 "sparse pattern table bytes length",
1997 )?;
1998 wire::check_slice_len(
1999 slice,
2000 table_bytes_len,
2001 "sparse start ID table",
2002 )?;
2003 let table = &slice[..table_bytes_len];
2004 slice = &slice[table_bytes_len..];
2005
2006 let sl = StartTable {
2007 table,
2008 kind,
2009 start_map,
2010 stride,
2011 pattern_len,
2012 universal_start_unanchored,
2013 universal_start_anchored,
2014 };
2015 Ok((sl, slice.as_ptr().as_usize() - slice_start))
2016 }
2017 }
2018
2019 impl<T: AsRef<[u8]>> StartTable<T> {
2020 fn write_to<E: Endian>(
2021 &self,
2022 mut dst: &mut [u8],
2023 ) -> Result<usize, SerializeError> {
2024 let nwrite = self.write_to_len();
2025 if dst.len() < nwrite {
2026 return Err(SerializeError::buffer_too_small(
2027 "sparse starting table ids",
2028 ));
2029 }
2030 dst = &mut dst[..nwrite];
2031
2032 // write start kind
2033 let nw = self.kind.write_to::<E>(dst)?;
2034 dst = &mut dst[nw..];
2035 // write start byte map
2036 let nw = self.start_map.write_to(dst)?;
2037 dst = &mut dst[nw..];
2038 // write stride
2039 E::write_u32(u32::try_from(self.stride).unwrap(), dst);
2040 dst = &mut dst[size_of::<u32>()..];
2041 // write pattern length
2042 E::write_u32(
2043 u32::try_from(self.pattern_len.unwrap_or(0xFFFF_FFFF)).unwrap(),
2044 dst,
2045 );
2046 dst = &mut dst[size_of::<u32>()..];
2047 // write universal start unanchored state id, u32::MAX if absent
2048 E::write_u32(
2049 self.universal_start_unanchored
2050 .map_or(u32::MAX, |sid| sid.as_u32()),
2051 dst,
2052 );
2053 dst = &mut dst[size_of::<u32>()..];
2054 // write universal start anchored state id, u32::MAX if absent
2055 E::write_u32(
2056 self.universal_start_anchored.map_or(u32::MAX, |sid| sid.as_u32()),
2057 dst,
2058 );
2059 dst = &mut dst[size_of::<u32>()..];
2060 // write start IDs
2061 for (sid, _, _) in self.iter() {
2062 E::write_u32(sid.as_u32(), dst);
2063 dst = &mut dst[StateID::SIZE..];
2064 }
2065 Ok(nwrite)
2066 }
2067
2068 /// Returns the number of bytes the serialized form of this transition
2069 /// table will use.
2070 fn write_to_len(&self) -> usize {
2071 self.kind.write_to_len()
2072 + self.start_map.write_to_len()
2073 + size_of::<u32>() // stride
2074 + size_of::<u32>() // # patterns
2075 + size_of::<u32>() // universal unanchored start
2076 + size_of::<u32>() // universal anchored start
2077 + self.table().len()
2078 }
2079
2080 /// Validates that every starting state ID in this table is valid.
2081 ///
2082 /// That is, every starting state ID can be used to correctly decode a
2083 /// state in the DFA's sparse transitions.
2084 fn validate(
2085 &self,
2086 sp: &Special,
2087 trans: &Transitions<T>,
2088 ) -> Result<(), DeserializeError> {
2089 for (id, _, _) in self.iter() {
2090 if sp.is_match_state(id) {
2091 return Err(DeserializeError::generic(
2092 "start states cannot be match states",
2093 ));
2094 }
2095 // Confirm that the start state points to a valid state.
2096 let state = trans.try_state(sp, id)?;
2097 // And like for the transition table, confirm that the transitions
2098 // on all start states themselves point to a valid state.
2099 //
2100 // It'd probably be better to integrate this validation with the
2101 // transition table, or otherwise store a sorted sequence of all
2102 // valid state IDs in the sparse DFA itself. That way, we could
2103 // check that every pointer to a state corresponds precisely to a
2104 // correct and valid state.
2105 for i in 0..state.ntrans {
2106 let to = state.next_at(i);
2107 let _ = trans.try_state(sp, to)?;
2108 }
2109 }
2110 Ok(())
2111 }
2112
2113 /// Converts this start list to a borrowed value.
2114 fn as_ref(&self) -> StartTable<&'_ [u8]> {
2115 StartTable {
2116 table: self.table(),
2117 kind: self.kind,
2118 start_map: self.start_map.clone(),
2119 stride: self.stride,
2120 pattern_len: self.pattern_len,
2121 universal_start_unanchored: self.universal_start_unanchored,
2122 universal_start_anchored: self.universal_start_anchored,
2123 }
2124 }
2125
2126 /// Converts this start list to an owned value.
2127 #[cfg(feature = "alloc")]
2128 fn to_owned(&self) -> StartTable<alloc::vec::Vec<u8>> {
2129 StartTable {
2130 table: self.table().to_vec(),
2131 kind: self.kind,
2132 start_map: self.start_map.clone(),
2133 stride: self.stride,
2134 pattern_len: self.pattern_len,
2135 universal_start_unanchored: self.universal_start_unanchored,
2136 universal_start_anchored: self.universal_start_anchored,
2137 }
2138 }
2139
2140 /// Return the start state for the given index and pattern ID. If the
2141 /// pattern ID is None, then the corresponding start state for the entire
2142 /// DFA is returned. If the pattern ID is not None, then the corresponding
2143 /// starting state for the given pattern is returned. If this start table
2144 /// does not have individual starting states for each pattern, then this
2145 /// panics.
2146 fn start(
2147 &self,
2148 input: &Input<'_>,
2149 start: Start,
2150 ) -> Result<StateID, MatchError> {
2151 let start_index = start.as_usize();
2152 let mode = input.get_anchored();
2153 let index = match mode {
2154 Anchored::No => {
2155 if !self.kind.has_unanchored() {
2156 return Err(MatchError::unsupported_anchored(mode));
2157 }
2158 start_index
2159 }
2160 Anchored::Yes => {
2161 if !self.kind.has_anchored() {
2162 return Err(MatchError::unsupported_anchored(mode));
2163 }
2164 self.stride + start_index
2165 }
2166 Anchored::Pattern(pid) => {
2167 let len = match self.pattern_len {
2168 None => {
2169 return Err(MatchError::unsupported_anchored(mode))
2170 }
2171 Some(len) => len,
2172 };
2173 if pid.as_usize() >= len {
2174 return Ok(DEAD);
2175 }
2176 (2 * self.stride)
2177 + (self.stride * pid.as_usize())
2178 + start_index
2179 }
2180 };
2181 let start = index * StateID::SIZE;
2182 // This OK since we're allowed to assume that the start table contains
2183 // valid StateIDs.
2184 Ok(wire::read_state_id_unchecked(&self.table()[start..]).0)
2185 }
2186
2187 /// Return an iterator over all start IDs in this table.
2188 fn iter(&self) -> StartStateIter<'_, T> {
2189 StartStateIter { st: self, i: 0 }
2190 }
2191
2192 /// Returns the total number of start state IDs in this table.
2193 fn len(&self) -> usize {
2194 self.table().len() / StateID::SIZE
2195 }
2196
2197 /// Returns the table as a raw slice of bytes.
2198 fn table(&self) -> &[u8] {
2199 self.table.as_ref()
2200 }
2201
2202 /// Return the memory usage, in bytes, of this start list.
2203 ///
2204 /// This does not include the size of a `StartTable` value itself.
2205 fn memory_usage(&self) -> usize {
2206 self.table().len()
2207 }
2208 }
2209
2210 #[cfg(feature = "dfa-build")]
2211 impl<T: AsMut<[u8]>> StartTable<T> {
2212 /// Set the start state for the given index and pattern.
2213 ///
2214 /// If the pattern ID or state ID are not valid, then this will panic.
2215 fn set_start(&mut self, anchored: Anchored, start: Start, id: StateID) {
2216 let start_index = start.as_usize();
2217 let index = match anchored {
2218 Anchored::No => start_index,
2219 Anchored::Yes => self.stride + start_index,
2220 Anchored::Pattern(pid) => {
2221 let pid = pid.as_usize();
2222 let len = self
2223 .pattern_len
2224 .expect("start states for each pattern enabled");
2225 assert!(pid < len, "invalid pattern ID {:?}", pid);
2226 self.stride
2227 .checked_mul(pid)
2228 .unwrap()
2229 .checked_add(self.stride.checked_mul(2).unwrap())
2230 .unwrap()
2231 .checked_add(start_index)
2232 .unwrap()
2233 }
2234 };
2235 let start = index * StateID::SIZE;
2236 let end = start + StateID::SIZE;
2237 wire::write_state_id::<wire::NE>(
2238 id,
2239 &mut self.table.as_mut()[start..end],
2240 );
2241 }
2242 }
2243
2244 /// An iterator over all state state IDs in a sparse DFA.
2245 struct StartStateIter<'a, T> {
2246 st: &'a StartTable<T>,
2247 i: usize,
2248 }
2249
2250 impl<'a, T: AsRef<[u8]>> Iterator for StartStateIter<'a, T> {
2251 type Item = (StateID, Anchored, Start);
2252
2253 fn next(&mut self) -> Option<(StateID, Anchored, Start)> {
2254 let i = self.i;
2255 if i >= self.st.len() {
2256 return None;
2257 }
2258 self.i += 1;
2259
2260 // This unwrap is okay since the stride of any DFA must always match
2261 // the number of start state types.
2262 let start_type = Start::from_usize(i % self.st.stride).unwrap();
2263 let anchored = if i < self.st.stride {
2264 Anchored::No
2265 } else if i < (2 * self.st.stride) {
2266 Anchored::Yes
2267 } else {
2268 let pid = (i - (2 * self.st.stride)) / self.st.stride;
2269 Anchored::Pattern(PatternID::new(pid).unwrap())
2270 };
2271 let start = i * StateID::SIZE;
2272 let end = start + StateID::SIZE;
2273 let bytes = self.st.table()[start..end].try_into().unwrap();
2274 // This is OK since we're allowed to assume that any IDs in this start
2275 // table are correct and valid for this DFA.
2276 let id = StateID::from_ne_bytes_unchecked(bytes);
2277 Some((id, anchored, start_type))
2278 }
2279 }
2280
2281 impl<'a, T> fmt::Debug for StartStateIter<'a, T> {
2282 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2283 f.debug_struct("StartStateIter").field("i", &self.i).finish()
2284 }
2285 }
2286
2287 /// An iterator over all states in a sparse DFA.
2288 ///
2289 /// This iterator yields tuples, where the first element is the state ID and
2290 /// the second element is the state itself.
2291 struct StateIter<'a, T> {
2292 trans: &'a Transitions<T>,
2293 id: usize,
2294 }
2295
2296 impl<'a, T: AsRef<[u8]>> Iterator for StateIter<'a, T> {
2297 type Item = State<'a>;
2298
2299 fn next(&mut self) -> Option<State<'a>> {
2300 if self.id >= self.trans.sparse().len() {
2301 return None;
2302 }
2303 let state = self.trans.state(StateID::new_unchecked(self.id));
2304 self.id = self.id + state.write_to_len();
2305 Some(state)
2306 }
2307 }
2308
2309 impl<'a, T> fmt::Debug for StateIter<'a, T> {
2310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2311 f.debug_struct("StateIter").field("id", &self.id).finish()
2312 }
2313 }
2314
2315 /// A representation of a sparse DFA state that can be cheaply materialized
2316 /// from a state identifier.
2317 #[derive(Clone)]
2318 struct State<'a> {
2319 /// The identifier of this state.
2320 id: StateID,
2321 /// Whether this is a match state or not.
2322 is_match: bool,
2323 /// The number of transitions in this state.
2324 ntrans: usize,
2325 /// Pairs of input ranges, where there is one pair for each transition.
2326 /// Each pair specifies an inclusive start and end byte range for the
2327 /// corresponding transition.
2328 input_ranges: &'a [u8],
2329 /// Transitions to the next state. This slice contains native endian
2330 /// encoded state identifiers, with `S` as the representation. Thus, there
2331 /// are `ntrans * size_of::<S>()` bytes in this slice.
2332 next: &'a [u8],
2333 /// If this is a match state, then this contains the pattern IDs that match
2334 /// when the DFA is in this state.
2335 ///
2336 /// This is a contiguous sequence of 32-bit native endian encoded integers.
2337 pattern_ids: &'a [u8],
2338 /// An accelerator for this state, if present. If this state has no
2339 /// accelerator, then this is an empty slice. When non-empty, this slice
2340 /// has length at most 3 and corresponds to the exhaustive set of bytes
2341 /// that must be seen in order to transition out of this state.
2342 accel: &'a [u8],
2343 }
2344
2345 impl<'a> State<'a> {
2346 /// Searches for the next transition given an input byte. If no such
2347 /// transition could be found, then a dead state is returned.
2348 ///
2349 /// This is marked as inline to help dramatically boost sparse searching,
2350 /// which decodes each state it enters to follow the next transition.
2351 #[cfg_attr(feature = "perf-inline", inline(always))]
2352 fn next(&self, input: u8) -> StateID {
2353 // This straight linear search was observed to be much better than
2354 // binary search on ASCII haystacks, likely because a binary search
2355 // visits the ASCII case last but a linear search sees it first. A
2356 // binary search does do a little better on non-ASCII haystacks, but
2357 // not by much. There might be a better trade off lurking here.
2358 for i in 0..(self.ntrans - 1) {
2359 let (start, end) = self.range(i);
2360 if start <= input && input <= end {
2361 return self.next_at(i);
2362 }
2363 // We could bail early with an extra branch: if input < b1, then
2364 // we know we'll never find a matching transition. Interestingly,
2365 // this extra branch seems to not help performance, or will even
2366 // hurt it. It's likely very dependent on the DFA itself and what
2367 // is being searched.
2368 }
2369 DEAD
2370 }
2371
2372 /// Returns the next state ID for the special EOI transition.
2373 fn next_eoi(&self) -> StateID {
2374 self.next_at(self.ntrans - 1)
2375 }
2376
2377 /// Returns the identifier for this state.
2378 fn id(&self) -> StateID {
2379 self.id
2380 }
2381
2382 /// Returns the inclusive input byte range for the ith transition in this
2383 /// state.
2384 fn range(&self, i: usize) -> (u8, u8) {
2385 (self.input_ranges[i * 2], self.input_ranges[i * 2 + 1])
2386 }
2387
2388 /// Returns the next state for the ith transition in this state.
2389 fn next_at(&self, i: usize) -> StateID {
2390 let start = i * StateID::SIZE;
2391 let end = start + StateID::SIZE;
2392 let bytes = self.next[start..end].try_into().unwrap();
2393 StateID::from_ne_bytes_unchecked(bytes)
2394 }
2395
2396 /// Returns the pattern ID for the given match index. If the match index
2397 /// is invalid, then this panics.
2398 fn pattern_id(&self, match_index: usize) -> PatternID {
2399 let start = match_index * PatternID::SIZE;
2400 wire::read_pattern_id_unchecked(&self.pattern_ids[start..]).0
2401 }
2402
2403 /// Returns the total number of pattern IDs for this state. This is always
2404 /// zero when `is_match` is false.
2405 fn pattern_len(&self) -> usize {
2406 assert_eq!(0, self.pattern_ids.len() % 4);
2407 self.pattern_ids.len() / 4
2408 }
2409
2410 /// Return an accelerator for this state.
2411 fn accelerator(&self) -> &'a [u8] {
2412 self.accel
2413 }
2414
2415 /// Write the raw representation of this state to the given buffer using
2416 /// the given endianness.
2417 fn write_to<E: Endian>(
2418 &self,
2419 mut dst: &mut [u8],
2420 ) -> Result<usize, SerializeError> {
2421 let nwrite = self.write_to_len();
2422 if dst.len() < nwrite {
2423 return Err(SerializeError::buffer_too_small(
2424 "sparse state transitions",
2425 ));
2426 }
2427
2428 let ntrans =
2429 if self.is_match { self.ntrans | (1 << 15) } else { self.ntrans };
2430 E::write_u16(u16::try_from(ntrans).unwrap(), dst);
2431 dst = &mut dst[size_of::<u16>()..];
2432
2433 dst[..self.input_ranges.len()].copy_from_slice(self.input_ranges);
2434 dst = &mut dst[self.input_ranges.len()..];
2435
2436 for i in 0..self.ntrans {
2437 E::write_u32(self.next_at(i).as_u32(), dst);
2438 dst = &mut dst[StateID::SIZE..];
2439 }
2440
2441 if self.is_match {
2442 E::write_u32(u32::try_from(self.pattern_len()).unwrap(), dst);
2443 dst = &mut dst[size_of::<u32>()..];
2444 for i in 0..self.pattern_len() {
2445 let pid = self.pattern_id(i);
2446 E::write_u32(pid.as_u32(), dst);
2447 dst = &mut dst[PatternID::SIZE..];
2448 }
2449 }
2450
2451 dst[0] = u8::try_from(self.accel.len()).unwrap();
2452 dst[1..][..self.accel.len()].copy_from_slice(self.accel);
2453
2454 Ok(nwrite)
2455 }
2456
2457 /// Return the total number of bytes that this state consumes in its
2458 /// encoded form.
2459 fn write_to_len(&self) -> usize {
2460 let mut len = 2
2461 + (self.ntrans * 2)
2462 + (self.ntrans * StateID::SIZE)
2463 + (1 + self.accel.len());
2464 if self.is_match {
2465 len += size_of::<u32>() + self.pattern_ids.len();
2466 }
2467 len
2468 }
2469 }
2470
2471 impl<'a> fmt::Debug for State<'a> {
2472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2473 let mut printed = false;
2474 for i in 0..(self.ntrans - 1) {
2475 let next = self.next_at(i);
2476 if next == DEAD {
2477 continue;
2478 }
2479
2480 if printed {
2481 write!(f, ", ")?;
2482 }
2483 let (start, end) = self.range(i);
2484 if start == end {
2485 write!(f, "{:?} => {:?}", DebugByte(start), next.as_usize())?;
2486 } else {
2487 write!(
2488 f,
2489 "{:?}-{:?} => {:?}",
2490 DebugByte(start),
2491 DebugByte(end),
2492 next.as_usize(),
2493 )?;
2494 }
2495 printed = true;
2496 }
2497 let eoi = self.next_at(self.ntrans - 1);
2498 if eoi != DEAD {
2499 if printed {
2500 write!(f, ", ")?;
2501 }
2502 write!(f, "EOI => {:?}", eoi.as_usize())?;
2503 }
2504 Ok(())
2505 }
2506 }
2507
2508 /// A representation of a mutable sparse DFA state that can be cheaply
2509 /// materialized from a state identifier.
2510 #[cfg(feature = "dfa-build")]
2511 struct StateMut<'a> {
2512 /// The identifier of this state.
2513 id: StateID,
2514 /// Whether this is a match state or not.
2515 is_match: bool,
2516 /// The number of transitions in this state.
2517 ntrans: usize,
2518 /// Pairs of input ranges, where there is one pair for each transition.
2519 /// Each pair specifies an inclusive start and end byte range for the
2520 /// corresponding transition.
2521 input_ranges: &'a mut [u8],
2522 /// Transitions to the next state. This slice contains native endian
2523 /// encoded state identifiers, with `S` as the representation. Thus, there
2524 /// are `ntrans * size_of::<S>()` bytes in this slice.
2525 next: &'a mut [u8],
2526 /// If this is a match state, then this contains the pattern IDs that match
2527 /// when the DFA is in this state.
2528 ///
2529 /// This is a contiguous sequence of 32-bit native endian encoded integers.
2530 pattern_ids: &'a [u8],
2531 /// An accelerator for this state, if present. If this state has no
2532 /// accelerator, then this is an empty slice. When non-empty, this slice
2533 /// has length at most 3 and corresponds to the exhaustive set of bytes
2534 /// that must be seen in order to transition out of this state.
2535 accel: &'a mut [u8],
2536 }
2537
2538 #[cfg(feature = "dfa-build")]
2539 impl<'a> StateMut<'a> {
2540 /// Sets the ith transition to the given state.
2541 fn set_next_at(&mut self, i: usize, next: StateID) {
2542 let start = i * StateID::SIZE;
2543 let end = start + StateID::SIZE;
2544 wire::write_state_id::<wire::NE>(next, &mut self.next[start..end]);
2545 }
2546 }
2547
2548 #[cfg(feature = "dfa-build")]
2549 impl<'a> fmt::Debug for StateMut<'a> {
2550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2551 let state = State {
2552 id: self.id,
2553 is_match: self.is_match,
2554 ntrans: self.ntrans,
2555 input_ranges: self.input_ranges,
2556 next: self.next,
2557 pattern_ids: self.pattern_ids,
2558 accel: self.accel,
2559 };
2560 fmt::Debug::fmt(&state, f)
2561 }
2562 }
2563
2564 /*
2565 /// A binary search routine specialized specifically to a sparse DFA state's
2566 /// transitions. Specifically, the transitions are defined as a set of pairs
2567 /// of input bytes that delineate an inclusive range of bytes. If the input
2568 /// byte is in the range, then the corresponding transition is a match.
2569 ///
2570 /// This binary search accepts a slice of these pairs and returns the position
2571 /// of the matching pair (the ith transition), or None if no matching pair
2572 /// could be found.
2573 ///
2574 /// Note that this routine is not currently used since it was observed to
2575 /// either decrease performance when searching ASCII, or did not provide enough
2576 /// of a boost on non-ASCII haystacks to be worth it. However, we leave it here
2577 /// for posterity in case we can find a way to use it.
2578 ///
2579 /// In theory, we could use the standard library's search routine if we could
2580 /// cast a `&[u8]` to a `&[(u8, u8)]`, but I don't believe this is currently
2581 /// guaranteed to be safe and is thus UB (since I don't think the in-memory
2582 /// representation of `(u8, u8)` has been nailed down). One could define a
2583 /// repr(C) type, but the casting doesn't seem justified.
2584 #[cfg_attr(feature = "perf-inline", inline(always))]
2585 fn binary_search_ranges(ranges: &[u8], needle: u8) -> Option<usize> {
2586 debug_assert!(ranges.len() % 2 == 0, "ranges must have even length");
2587 debug_assert!(ranges.len() <= 512, "ranges should be short");
2588
2589 let (mut left, mut right) = (0, ranges.len() / 2);
2590 while left < right {
2591 let mid = (left + right) / 2;
2592 let (b1, b2) = (ranges[mid * 2], ranges[mid * 2 + 1]);
2593 if needle < b1 {
2594 right = mid;
2595 } else if needle > b2 {
2596 left = mid + 1;
2597 } else {
2598 return Some(mid);
2599 }
2600 }
2601 None
2602 }
2603 */
2604
2605 #[cfg(all(test, feature = "syntax", feature = "dfa-build"))]
2606 mod tests {
2607 use crate::{
2608 dfa::{dense::DFA, Automaton},
2609 nfa::thompson,
2610 Input, MatchError,
2611 };
2612
2613 // See the analogous test in src/hybrid/dfa.rs and src/dfa/dense.rs.
2614 #[test]
2615 fn heuristic_unicode_forward() {
2616 let dfa = DFA::builder()
2617 .configure(DFA::config().unicode_word_boundary(true))
2618 .thompson(thompson::Config::new().reverse(true))
2619 .build(r"\b[0-9]+\b")
2620 .unwrap()
2621 .to_sparse()
2622 .unwrap();
2623
2624 let input = Input::new("β123").range(2..);
2625 let expected = MatchError::quit(0xB2, 1);
2626 let got = dfa.try_search_fwd(&input);
2627 assert_eq!(Err(expected), got);
2628
2629 let input = Input::new("123β").range(..3);
2630 let expected = MatchError::quit(0xCE, 3);
2631 let got = dfa.try_search_fwd(&input);
2632 assert_eq!(Err(expected), got);
2633 }
2634
2635 // See the analogous test in src/hybrid/dfa.rs and src/dfa/dense.rs.
2636 #[test]
2637 fn heuristic_unicode_reverse() {
2638 let dfa = DFA::builder()
2639 .configure(DFA::config().unicode_word_boundary(true))
2640 .thompson(thompson::Config::new().reverse(true))
2641 .build(r"\b[0-9]+\b")
2642 .unwrap()
2643 .to_sparse()
2644 .unwrap();
2645
2646 let input = Input::new("β123").range(2..);
2647 let expected = MatchError::quit(0xB2, 1);
2648 let got = dfa.try_search_rev(&input);
2649 assert_eq!(Err(expected), got);
2650
2651 let input = Input::new("123β").range(..3);
2652 let expected = MatchError::quit(0xCE, 3);
2653 let got = dfa.try_search_rev(&input);
2654 assert_eq!(Err(expected), got);
2655 }
2656 }