Coverage Report

Created: 2026-09-14 07:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/regex/regex-automata/src/dfa/dense.rs
Line
Count
Source
1
/*!
2
Types and routines specific to dense DFAs.
3
4
This module is the home of [`dense::DFA`](DFA).
5
6
This module also contains a [`dense::Builder`](Builder) and a
7
[`dense::Config`](Config) for building and configuring a dense DFA.
8
*/
9
10
#[cfg(feature = "dfa-build")]
11
use core::cmp;
12
use core::{fmt, iter, mem::size_of, slice};
13
14
#[cfg(feature = "dfa-build")]
15
use alloc::{
16
    collections::{BTreeMap, BTreeSet},
17
    vec,
18
    vec::Vec,
19
};
20
21
#[cfg(feature = "dfa-build")]
22
use crate::{
23
    dfa::{
24
        accel::Accel, determinize, minimize::Minimizer, remapper::Remapper,
25
        sparse,
26
    },
27
    nfa::thompson,
28
    util::{look::LookMatcher, search::MatchKind},
29
};
30
use crate::{
31
    dfa::{
32
        accel::Accels,
33
        automaton::{fmt_state_indicator, Automaton, StartError},
34
        special::Special,
35
        start::StartKind,
36
        DEAD,
37
    },
38
    util::{
39
        alphabet::{self, ByteClasses, ByteSet},
40
        int::{Pointer, Usize},
41
        prefilter::Prefilter,
42
        primitives::{PatternID, StateID},
43
        search::Anchored,
44
        start::{self, Start, StartByteMap},
45
        wire::{self, DeserializeError, Endian, SerializeError},
46
    },
47
};
48
49
/// The label that is pre-pended to a serialized DFA.
50
const LABEL: &str = "rust-regex-automata-dfa-dense";
51
52
/// The format version of dense regexes. This version gets incremented when a
53
/// change occurs. A change may not necessarily be a breaking change, but the
54
/// version does permit good error messages in the case where a breaking change
55
/// is made.
56
const VERSION: u32 = 2;
57
58
/// The configuration used for compiling a dense DFA.
59
///
60
/// As a convenience, [`DFA::config`] is an alias for [`Config::new`]. The
61
/// advantage of the former is that it often lets you avoid importing the
62
/// `Config` type directly.
63
///
64
/// A dense DFA configuration is a simple data object that is typically used
65
/// with [`dense::Builder::configure`](self::Builder::configure).
66
///
67
/// The default configuration guarantees that a search will never return
68
/// a "quit" error, although it is possible for a search to fail if
69
/// [`Config::starts_for_each_pattern`] wasn't enabled (which it is
70
/// not by default) and an [`Anchored::Pattern`] mode is requested via
71
/// [`Input`](crate::Input).
72
#[cfg(feature = "dfa-build")]
73
#[derive(Clone, Debug, Default)]
74
pub struct Config {
75
    // As with other configuration types in this crate, we put all our knobs
76
    // in options so that we can distinguish between "default" and "not set."
77
    // This makes it possible to easily combine multiple configurations
78
    // without default values overwriting explicitly specified values. See the
79
    // 'overwrite' method.
80
    //
81
    // For docs on the fields below, see the corresponding method setters.
82
    accelerate: Option<bool>,
83
    pre: Option<Option<Prefilter>>,
84
    minimize: Option<bool>,
85
    match_kind: Option<MatchKind>,
86
    start_kind: Option<StartKind>,
87
    starts_for_each_pattern: Option<bool>,
88
    byte_classes: Option<bool>,
89
    unicode_word_boundary: Option<bool>,
90
    quitset: Option<ByteSet>,
91
    specialize_start_states: Option<bool>,
92
    dfa_size_limit: Option<Option<usize>>,
93
    determinize_size_limit: Option<Option<usize>>,
94
}
95
96
#[cfg(feature = "dfa-build")]
97
impl Config {
98
    /// Return a new default dense DFA compiler configuration.
99
43.4k
    pub fn new() -> Config {
100
43.4k
        Config::default()
101
43.4k
    }
102
103
    /// Enable state acceleration.
104
    ///
105
    /// When enabled, DFA construction will analyze each state to determine
106
    /// whether it is eligible for simple acceleration. Acceleration typically
107
    /// occurs when most of a state's transitions loop back to itself, leaving
108
    /// only a select few bytes that will exit the state. When this occurs,
109
    /// other routines like `memchr` can be used to look for those bytes which
110
    /// may be much faster than traversing the DFA.
111
    ///
112
    /// Callers may elect to disable this if consistent performance is more
113
    /// desirable than variable performance. Namely, acceleration can sometimes
114
    /// make searching slower than it otherwise would be if the transitions
115
    /// that leave accelerated states are traversed frequently.
116
    ///
117
    /// See [`Automaton::accelerator`] for an example.
118
    ///
119
    /// This is enabled by default.
120
3.00k
    pub fn accelerate(mut self, yes: bool) -> Config {
121
3.00k
        self.accelerate = Some(yes);
122
3.00k
        self
123
3.00k
    }
124
125
    /// Set a prefilter to be used whenever a start state is entered.
126
    ///
127
    /// A [`Prefilter`] in this context is meant to accelerate searches by
128
    /// looking for literal prefixes that every match for the corresponding
129
    /// pattern (or patterns) must start with. Once a prefilter produces a
130
    /// match, the underlying search routine continues on to try and confirm
131
    /// the match.
132
    ///
133
    /// Be warned that setting a prefilter does not guarantee that the search
134
    /// will be faster. While it's usually a good bet, if the prefilter
135
    /// produces a lot of false positive candidates (i.e., positions matched
136
    /// by the prefilter but not by the regex), then the overall result can
137
    /// be slower than if you had just executed the regex engine without any
138
    /// prefilters.
139
    ///
140
    /// Note that unless [`Config::specialize_start_states`] has been
141
    /// explicitly set, then setting this will also enable (when `pre` is
142
    /// `Some`) or disable (when `pre` is `None`) start state specialization.
143
    /// This occurs because without start state specialization, a prefilter
144
    /// is likely to be less effective. And without a prefilter, start state
145
    /// specialization is usually pointless.
146
    ///
147
    /// **WARNING:** Note that prefilters are not preserved as part of
148
    /// serialization. Serializing a DFA will drop its prefilter.
149
    ///
150
    /// By default no prefilter is set.
151
    ///
152
    /// # Example
153
    ///
154
    /// ```
155
    /// use regex_automata::{
156
    ///     dfa::{dense::DFA, Automaton},
157
    ///     util::prefilter::Prefilter,
158
    ///     Input, HalfMatch, MatchKind,
159
    /// };
160
    ///
161
    /// let pre = Prefilter::new(MatchKind::LeftmostFirst, &["foo", "bar"]);
162
    /// let re = DFA::builder()
163
    ///     .configure(DFA::config().prefilter(pre))
164
    ///     .build(r"(foo|bar)[a-z]+")?;
165
    /// let input = Input::new("foo1 barfox bar");
166
    /// assert_eq!(
167
    ///     Some(HalfMatch::must(0, 11)),
168
    ///     re.try_search_fwd(&input)?,
169
    /// );
170
    ///
171
    /// # Ok::<(), Box<dyn std::error::Error>>(())
172
    /// ```
173
    ///
174
    /// Be warned though that an incorrect prefilter can lead to incorrect
175
    /// results!
176
    ///
177
    /// ```
178
    /// use regex_automata::{
179
    ///     dfa::{dense::DFA, Automaton},
180
    ///     util::prefilter::Prefilter,
181
    ///     Input, HalfMatch, MatchKind,
182
    /// };
183
    ///
184
    /// let pre = Prefilter::new(MatchKind::LeftmostFirst, &["foo", "car"]);
185
    /// let re = DFA::builder()
186
    ///     .configure(DFA::config().prefilter(pre))
187
    ///     .build(r"(foo|bar)[a-z]+")?;
188
    /// let input = Input::new("foo1 barfox bar");
189
    /// assert_eq!(
190
    ///     // No match reported even though there clearly is one!
191
    ///     None,
192
    ///     re.try_search_fwd(&input)?,
193
    /// );
194
    ///
195
    /// # Ok::<(), Box<dyn std::error::Error>>(())
196
    /// ```
197
82.1k
    pub fn prefilter(mut self, pre: Option<Prefilter>) -> Config {
198
82.1k
        self.pre = Some(pre);
199
82.1k
        if self.specialize_start_states.is_none() {
200
43.4k
            self.specialize_start_states =
201
43.4k
                Some(self.get_prefilter().is_some());
202
43.4k
        }
203
82.1k
        self
204
82.1k
    }
205
206
    /// Minimize the DFA.
207
    ///
208
    /// When enabled, the DFA built will be minimized such that it is as small
209
    /// as possible.
210
    ///
211
    /// Whether one enables minimization or not depends on the types of costs
212
    /// you're willing to pay and how much you care about its benefits. In
213
    /// particular, minimization has worst case `O(n*k*logn)` time and `O(k*n)`
214
    /// space, where `n` is the number of DFA states and `k` is the alphabet
215
    /// size. In practice, minimization can be quite costly in terms of both
216
    /// space and time, so it should only be done if you're willing to wait
217
    /// longer to produce a DFA. In general, you might want a minimal DFA in
218
    /// the following circumstances:
219
    ///
220
    /// 1. You would like to optimize for the size of the automaton. This can
221
    ///    manifest in one of two ways. Firstly, if you're converting the
222
    ///    DFA into Rust code (or a table embedded in the code), then a minimal
223
    ///    DFA will translate into a corresponding reduction in code  size, and
224
    ///    thus, also the final compiled binary size. Secondly, if you are
225
    ///    building many DFAs and putting them on the heap, you'll be able to
226
    ///    fit more if they are smaller. Note though that building a minimal
227
    ///    DFA itself requires additional space; you only realize the space
228
    ///    savings once the minimal DFA is constructed (at which point, the
229
    ///    space used for minimization is freed).
230
    /// 2. You've observed that a smaller DFA results in faster match
231
    ///    performance. Naively, this isn't guaranteed since there is no
232
    ///    inherent difference between matching with a bigger-than-minimal
233
    ///    DFA and a minimal DFA. However, a smaller DFA may make use of your
234
    ///    CPU's cache more efficiently.
235
    /// 3. You are trying to establish an equivalence between regular
236
    ///    languages. The standard method for this is to build a minimal DFA
237
    ///    for each language and then compare them. If the DFAs are equivalent
238
    ///    (up to state renaming), then the languages are equivalent.
239
    ///
240
    /// Typically, minimization only makes sense as an offline process. That
241
    /// is, one might minimize a DFA before serializing it to persistent
242
    /// storage. In practical terms, minimization can take around an order of
243
    /// magnitude more time than compiling the initial DFA via determinization.
244
    ///
245
    /// This option is disabled by default.
246
0
    pub fn minimize(mut self, yes: bool) -> Config {
247
0
        self.minimize = Some(yes);
248
0
        self
249
0
    }
250
251
    /// Set the desired match semantics.
252
    ///
253
    /// The default is [`MatchKind::LeftmostFirst`], which corresponds to the
254
    /// match semantics of Perl-like regex engines. That is, when multiple
255
    /// patterns would match at the same leftmost position, the pattern that
256
    /// appears first in the concrete syntax is chosen.
257
    ///
258
    /// Currently, the only other kind of match semantics supported is
259
    /// [`MatchKind::All`]. This corresponds to classical DFA construction
260
    /// where all possible matches are added to the DFA.
261
    ///
262
    /// Typically, `All` is used when one wants to execute an overlapping
263
    /// search and `LeftmostFirst` otherwise. In particular, it rarely makes
264
    /// sense to use `All` with the various "leftmost" find routines, since the
265
    /// leftmost routines depend on the `LeftmostFirst` automata construction
266
    /// strategy. Specifically, `LeftmostFirst` adds dead states to the DFA
267
    /// as a way to terminate the search and report a match. `LeftmostFirst`
268
    /// also supports non-greedy matches using this strategy where as `All`
269
    /// does not.
270
    ///
271
    /// # Example: overlapping search
272
    ///
273
    /// This example shows the typical use of `MatchKind::All`, which is to
274
    /// report overlapping matches.
275
    ///
276
    /// ```
277
    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
278
    /// use regex_automata::{
279
    ///     dfa::{Automaton, OverlappingState, dense},
280
    ///     HalfMatch, Input, MatchKind,
281
    /// };
282
    ///
283
    /// let dfa = dense::Builder::new()
284
    ///     .configure(dense::Config::new().match_kind(MatchKind::All))
285
    ///     .build_many(&[r"\w+$", r"\S+$"])?;
286
    /// let input = Input::new("@foo");
287
    /// let mut state = OverlappingState::start();
288
    ///
289
    /// let expected = Some(HalfMatch::must(1, 4));
290
    /// dfa.try_search_overlapping_fwd(&input, &mut state)?;
291
    /// assert_eq!(expected, state.get_match());
292
    ///
293
    /// // The first pattern also matches at the same position, so re-running
294
    /// // the search will yield another match. Notice also that the first
295
    /// // pattern is returned after the second. This is because the second
296
    /// // pattern begins its match before the first, is therefore an earlier
297
    /// // match and is thus reported first.
298
    /// let expected = Some(HalfMatch::must(0, 4));
299
    /// dfa.try_search_overlapping_fwd(&input, &mut state)?;
300
    /// assert_eq!(expected, state.get_match());
301
    ///
302
    /// # Ok::<(), Box<dyn std::error::Error>>(())
303
    /// ```
304
    ///
305
    /// # Example: reverse automaton to find start of match
306
    ///
307
    /// Another example for using `MatchKind::All` is for constructing a
308
    /// reverse automaton to find the start of a match. `All` semantics are
309
    /// used for this in order to find the longest possible match, which
310
    /// corresponds to the leftmost starting position.
311
    ///
312
    /// Note that if you need the starting position then
313
    /// [`dfa::regex::Regex`](crate::dfa::regex::Regex) will handle this for
314
    /// you, so it's usually not necessary to do this yourself.
315
    ///
316
    /// ```
317
    /// use regex_automata::{
318
    ///     dfa::{dense, Automaton, StartKind},
319
    ///     nfa::thompson::NFA,
320
    ///     Anchored, HalfMatch, Input, MatchKind,
321
    /// };
322
    ///
323
    /// let haystack = "123foobar456".as_bytes();
324
    /// let pattern = r"[a-z]+r";
325
    ///
326
    /// let dfa_fwd = dense::DFA::new(pattern)?;
327
    /// let dfa_rev = dense::Builder::new()
328
    ///     .thompson(NFA::config().reverse(true))
329
    ///     .configure(dense::Config::new()
330
    ///         // This isn't strictly necessary since both anchored and
331
    ///         // unanchored searches are supported by default. But since
332
    ///         // finding the start-of-match only requires anchored searches,
333
    ///         // we can get rid of the unanchored configuration and possibly
334
    ///         // slim down our DFA considerably.
335
    ///         .start_kind(StartKind::Anchored)
336
    ///         .match_kind(MatchKind::All)
337
    ///     )
338
    ///     .build(pattern)?;
339
    /// let expected_fwd = HalfMatch::must(0, 9);
340
    /// let expected_rev = HalfMatch::must(0, 3);
341
    /// let got_fwd = dfa_fwd.try_search_fwd(&Input::new(haystack))?.unwrap();
342
    /// // Here we don't specify the pattern to search for since there's only
343
    /// // one pattern and we're doing a leftmost search. But if this were an
344
    /// // overlapping search, you'd need to specify the pattern that matched
345
    /// // in the forward direction. (Otherwise, you might wind up finding the
346
    /// // starting position of a match of some other pattern.) That in turn
347
    /// // requires building the reverse automaton with starts_for_each_pattern
348
    /// // enabled. Indeed, this is what Regex does internally.
349
    /// let input = Input::new(haystack)
350
    ///     .range(..got_fwd.offset())
351
    ///     .anchored(Anchored::Yes);
352
    /// let got_rev = dfa_rev.try_search_rev(&input)?.unwrap();
353
    /// assert_eq!(expected_fwd, got_fwd);
354
    /// assert_eq!(expected_rev, got_rev);
355
    ///
356
    /// # Ok::<(), Box<dyn std::error::Error>>(())
357
    /// ```
358
82.1k
    pub fn match_kind(mut self, kind: MatchKind) -> Config {
359
82.1k
        self.match_kind = Some(kind);
360
82.1k
        self
361
82.1k
    }
362
363
    /// The type of starting state configuration to use for a DFA.
364
    ///
365
    /// By default, the starting state configuration is [`StartKind::Both`].
366
    ///
367
    /// # Example
368
    ///
369
    /// ```
370
    /// use regex_automata::{
371
    ///     dfa::{dense::DFA, Automaton, StartKind},
372
    ///     Anchored, HalfMatch, Input,
373
    /// };
374
    ///
375
    /// let haystack = "quux foo123";
376
    /// let expected = HalfMatch::must(0, 11);
377
    ///
378
    /// // By default, DFAs support both anchored and unanchored searches.
379
    /// let dfa = DFA::new(r"[0-9]+")?;
380
    /// let input = Input::new(haystack);
381
    /// assert_eq!(Some(expected), dfa.try_search_fwd(&input)?);
382
    ///
383
    /// // But if we only need anchored searches, then we can build a DFA
384
    /// // that only supports anchored searches. This leads to a smaller DFA
385
    /// // (potentially significantly smaller in some cases), but a DFA that
386
    /// // will panic if you try to use it with an unanchored search.
387
    /// let dfa = DFA::builder()
388
    ///     .configure(DFA::config().start_kind(StartKind::Anchored))
389
    ///     .build(r"[0-9]+")?;
390
    /// let input = Input::new(haystack)
391
    ///     .range(8..)
392
    ///     .anchored(Anchored::Yes);
393
    /// assert_eq!(Some(expected), dfa.try_search_fwd(&input)?);
394
    ///
395
    /// # Ok::<(), Box<dyn std::error::Error>>(())
396
    /// ```
397
41.7k
    pub fn start_kind(mut self, kind: StartKind) -> Config {
398
41.7k
        self.start_kind = Some(kind);
399
41.7k
        self
400
41.7k
    }
401
402
    /// Whether to compile a separate start state for each pattern in the
403
    /// automaton.
404
    ///
405
    /// When enabled, a separate **anchored** start state is added for each
406
    /// pattern in the DFA. When this start state is used, then the DFA will
407
    /// only search for matches for the pattern specified, even if there are
408
    /// other patterns in the DFA.
409
    ///
410
    /// The main downside of this option is that it can potentially increase
411
    /// the size of the DFA and/or increase the time it takes to build the DFA.
412
    ///
413
    /// There are a few reasons one might want to enable this (it's disabled
414
    /// by default):
415
    ///
416
    /// 1. When looking for the start of an overlapping match (using a
417
    /// reverse DFA), doing it correctly requires starting the reverse search
418
    /// using the starting state of the pattern that matched in the forward
419
    /// direction. Indeed, when building a [`Regex`](crate::dfa::regex::Regex),
420
    /// it will automatically enable this option when building the reverse DFA
421
    /// internally.
422
    /// 2. When you want to use a DFA with multiple patterns to both search
423
    /// for matches of any pattern or to search for anchored matches of one
424
    /// particular pattern while using the same DFA. (Otherwise, you would need
425
    /// to compile a new DFA for each pattern.)
426
    /// 3. Since the start states added for each pattern are anchored, if you
427
    /// compile an unanchored DFA with one pattern while also enabling this
428
    /// option, then you can use the same DFA to perform anchored or unanchored
429
    /// searches. The latter you get with the standard search APIs. The former
430
    /// you get from the various `_at` search methods that allow you specify a
431
    /// pattern ID to search for.
432
    ///
433
    /// By default this is disabled.
434
    ///
435
    /// # Example
436
    ///
437
    /// This example shows how to use this option to permit the same DFA to
438
    /// run both anchored and unanchored searches for a single pattern.
439
    ///
440
    /// ```
441
    /// use regex_automata::{
442
    ///     dfa::{dense, Automaton},
443
    ///     Anchored, HalfMatch, PatternID, Input,
444
    /// };
445
    ///
446
    /// let dfa = dense::Builder::new()
447
    ///     .configure(dense::Config::new().starts_for_each_pattern(true))
448
    ///     .build(r"foo[0-9]+")?;
449
    /// let haystack = "quux foo123";
450
    ///
451
    /// // Here's a normal unanchored search. Notice that we use 'None' for the
452
    /// // pattern ID. Since the DFA was built as an unanchored machine, it
453
    /// // use its default unanchored starting state.
454
    /// let expected = HalfMatch::must(0, 11);
455
    /// let input = Input::new(haystack);
456
    /// assert_eq!(Some(expected), dfa.try_search_fwd(&input)?);
457
    /// // But now if we explicitly specify the pattern to search ('0' being
458
    /// // the only pattern in the DFA), then it will use the starting state
459
    /// // for that specific pattern which is always anchored. Since the
460
    /// // pattern doesn't have a match at the beginning of the haystack, we
461
    /// // find nothing.
462
    /// let input = Input::new(haystack)
463
    ///     .anchored(Anchored::Pattern(PatternID::must(0)));
464
    /// assert_eq!(None, dfa.try_search_fwd(&input)?);
465
    /// // And finally, an anchored search is not the same as putting a '^' at
466
    /// // beginning of the pattern. An anchored search can only match at the
467
    /// // beginning of the *search*, which we can change:
468
    /// let input = Input::new(haystack)
469
    ///     .anchored(Anchored::Pattern(PatternID::must(0)))
470
    ///     .range(5..);
471
    /// assert_eq!(Some(expected), dfa.try_search_fwd(&input)?);
472
    ///
473
    /// # Ok::<(), Box<dyn std::error::Error>>(())
474
    /// ```
475
43.4k
    pub fn starts_for_each_pattern(mut self, yes: bool) -> Config {
476
43.4k
        self.starts_for_each_pattern = Some(yes);
477
43.4k
        self
478
43.4k
    }
479
480
    /// Whether to attempt to shrink the size of the DFA's alphabet or not.
481
    ///
482
    /// This option is enabled by default and should never be disabled unless
483
    /// one is debugging a generated DFA.
484
    ///
485
    /// When enabled, the DFA will use a map from all possible bytes to their
486
    /// corresponding equivalence class. Each equivalence class represents a
487
    /// set of bytes that does not discriminate between a match and a non-match
488
    /// in the DFA. For example, the pattern `[ab]+` has at least two
489
    /// equivalence classes: a set containing `a` and `b` and a set containing
490
    /// every byte except for `a` and `b`. `a` and `b` are in the same
491
    /// equivalence class because they never discriminate between a match and a
492
    /// non-match.
493
    ///
494
    /// The advantage of this map is that the size of the transition table
495
    /// can be reduced drastically from `#states * 256 * sizeof(StateID)` to
496
    /// `#states * k * sizeof(StateID)` where `k` is the number of equivalence
497
    /// classes (rounded up to the nearest power of 2). As a result, total
498
    /// space usage can decrease substantially. Moreover, since a smaller
499
    /// alphabet is used, DFA compilation becomes faster as well.
500
    ///
501
    /// **WARNING:** This is only useful for debugging DFAs. Disabling this
502
    /// does not yield any speed advantages. Namely, even when this is
503
    /// disabled, a byte class map is still used while searching. The only
504
    /// difference is that every byte will be forced into its own distinct
505
    /// equivalence class. This is useful for debugging the actual generated
506
    /// transitions because it lets one see the transitions defined on actual
507
    /// bytes instead of the equivalence classes.
508
43.4k
    pub fn byte_classes(mut self, yes: bool) -> Config {
509
43.4k
        self.byte_classes = Some(yes);
510
43.4k
        self
511
43.4k
    }
512
513
    /// Heuristically enable Unicode word boundaries.
514
    ///
515
    /// When set, this will attempt to implement Unicode word boundaries as if
516
    /// they were ASCII word boundaries. This only works when the search input
517
    /// is ASCII only. If a non-ASCII byte is observed while searching, then a
518
    /// [`MatchError::quit`](crate::MatchError::quit) error is returned.
519
    ///
520
    /// A possible alternative to enabling this option is to simply use an
521
    /// ASCII word boundary, e.g., via `(?-u:\b)`. The main reason to use this
522
    /// option is if you absolutely need Unicode support. This option lets one
523
    /// use a fast search implementation (a DFA) for some potentially very
524
    /// common cases, while providing the option to fall back to some other
525
    /// regex engine to handle the general case when an error is returned.
526
    ///
527
    /// If the pattern provided has no Unicode word boundary in it, then this
528
    /// option has no effect. (That is, quitting on a non-ASCII byte only
529
    /// occurs when this option is enabled _and_ a Unicode word boundary is
530
    /// present in the pattern.)
531
    ///
532
    /// This is almost equivalent to setting all non-ASCII bytes to be quit
533
    /// bytes. The only difference is that this will cause non-ASCII bytes to
534
    /// be quit bytes _only_ when a Unicode word boundary is present in the
535
    /// pattern.
536
    ///
537
    /// When enabling this option, callers _must_ be prepared to handle
538
    /// a [`MatchError`](crate::MatchError) error during search.
539
    /// When using a [`Regex`](crate::dfa::regex::Regex), this corresponds
540
    /// to using the `try_` suite of methods. Alternatively, if
541
    /// callers can guarantee that their input is ASCII only, then a
542
    /// [`MatchError::quit`](crate::MatchError::quit) error will never be
543
    /// returned while searching.
544
    ///
545
    /// This is disabled by default.
546
    ///
547
    /// # Example
548
    ///
549
    /// This example shows how to heuristically enable Unicode word boundaries
550
    /// in a pattern. It also shows what happens when a search comes across a
551
    /// non-ASCII byte.
552
    ///
553
    /// ```
554
    /// use regex_automata::{
555
    ///     dfa::{Automaton, dense},
556
    ///     HalfMatch, Input, MatchError,
557
    /// };
558
    ///
559
    /// let dfa = dense::Builder::new()
560
    ///     .configure(dense::Config::new().unicode_word_boundary(true))
561
    ///     .build(r"\b[0-9]+\b")?;
562
    ///
563
    /// // The match occurs before the search ever observes the snowman
564
    /// // character, so no error occurs.
565
    /// let haystack = "foo 123  ☃".as_bytes();
566
    /// let expected = Some(HalfMatch::must(0, 7));
567
    /// let got = dfa.try_search_fwd(&Input::new(haystack))?;
568
    /// assert_eq!(expected, got);
569
    ///
570
    /// // Notice that this search fails, even though the snowman character
571
    /// // occurs after the ending match offset. This is because search
572
    /// // routines read one byte past the end of the search to account for
573
    /// // look-around, and indeed, this is required here to determine whether
574
    /// // the trailing \b matches.
575
    /// let haystack = "foo 123 ☃".as_bytes();
576
    /// let expected = MatchError::quit(0xE2, 8);
577
    /// let got = dfa.try_search_fwd(&Input::new(haystack));
578
    /// assert_eq!(Err(expected), got);
579
    ///
580
    /// // Another example is executing a search where the span of the haystack
581
    /// // we specify is all ASCII, but there is non-ASCII just before it. This
582
    /// // correctly also reports an error.
583
    /// let input = Input::new("β123").range(2..);
584
    /// let expected = MatchError::quit(0xB2, 1);
585
    /// let got = dfa.try_search_fwd(&input);
586
    /// assert_eq!(Err(expected), got);
587
    ///
588
    /// // And similarly for the trailing word boundary.
589
    /// let input = Input::new("123β").range(..3);
590
    /// let expected = MatchError::quit(0xCE, 3);
591
    /// let got = dfa.try_search_fwd(&input);
592
    /// assert_eq!(Err(expected), got);
593
    ///
594
    /// # Ok::<(), Box<dyn std::error::Error>>(())
595
    /// ```
596
43.4k
    pub fn unicode_word_boundary(mut self, yes: bool) -> Config {
597
        // We have a separate option for this instead of just setting the
598
        // appropriate quit bytes here because we don't want to set quit bytes
599
        // for every regex. We only want to set them when the regex contains a
600
        // Unicode word boundary.
601
43.4k
        self.unicode_word_boundary = Some(yes);
602
43.4k
        self
603
43.4k
    }
604
605
    /// Add a "quit" byte to the DFA.
606
    ///
607
    /// When a quit byte is seen during search time, then search will return
608
    /// a [`MatchError::quit`](crate::MatchError::quit) error indicating the
609
    /// offset at which the search stopped.
610
    ///
611
    /// A quit byte will always overrule any other aspects of a regex. For
612
    /// example, if the `x` byte is added as a quit byte and the regex `\w` is
613
    /// used, then observing `x` will cause the search to quit immediately
614
    /// despite the fact that `x` is in the `\w` class.
615
    ///
616
    /// This mechanism is primarily useful for heuristically enabling certain
617
    /// features like Unicode word boundaries in a DFA. Namely, if the input
618
    /// to search is ASCII, then a Unicode word boundary can be implemented
619
    /// via an ASCII word boundary with no change in semantics. Thus, a DFA
620
    /// can attempt to match a Unicode word boundary but give up as soon as it
621
    /// observes a non-ASCII byte. Indeed, if callers set all non-ASCII bytes
622
    /// to be quit bytes, then Unicode word boundaries will be permitted when
623
    /// building DFAs. Of course, callers should enable
624
    /// [`Config::unicode_word_boundary`] if they want this behavior instead.
625
    /// (The advantage being that non-ASCII quit bytes will only be added if a
626
    /// Unicode word boundary is in the pattern.)
627
    ///
628
    /// When enabling this option, callers _must_ be prepared to handle a
629
    /// [`MatchError`](crate::MatchError) error during search. When using a
630
    /// [`Regex`](crate::dfa::regex::Regex), this corresponds to using the
631
    /// `try_` suite of methods.
632
    ///
633
    /// By default, there are no quit bytes set.
634
    ///
635
    /// # Panics
636
    ///
637
    /// This panics if heuristic Unicode word boundaries are enabled and any
638
    /// non-ASCII byte is removed from the set of quit bytes. Namely, enabling
639
    /// Unicode word boundaries requires setting every non-ASCII byte to a quit
640
    /// byte. So if the caller attempts to undo any of that, then this will
641
    /// panic.
642
    ///
643
    /// # Example
644
    ///
645
    /// This example shows how to cause a search to terminate if it sees a
646
    /// `\n` byte. This could be useful if, for example, you wanted to prevent
647
    /// a user supplied pattern from matching across a line boundary.
648
    ///
649
    /// ```
650
    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
651
    /// use regex_automata::{dfa::{Automaton, dense}, Input, MatchError};
652
    ///
653
    /// let dfa = dense::Builder::new()
654
    ///     .configure(dense::Config::new().quit(b'\n', true))
655
    ///     .build(r"foo\p{any}+bar")?;
656
    ///
657
    /// let haystack = "foo\nbar".as_bytes();
658
    /// // Normally this would produce a match, since \p{any} contains '\n'.
659
    /// // But since we instructed the automaton to enter a quit state if a
660
    /// // '\n' is observed, this produces a match error instead.
661
    /// let expected = MatchError::quit(b'\n', 3);
662
    /// let got = dfa.try_search_fwd(&Input::new(haystack)).unwrap_err();
663
    /// assert_eq!(expected, got);
664
    ///
665
    /// # Ok::<(), Box<dyn std::error::Error>>(())
666
    /// ```
667
0
    pub fn quit(mut self, byte: u8, yes: bool) -> Config {
668
0
        if self.get_unicode_word_boundary() && !byte.is_ascii() && !yes {
669
0
            panic!(
670
0
                "cannot set non-ASCII byte to be non-quit when \
671
0
                 Unicode word boundaries are enabled"
672
            );
673
0
        }
674
0
        if self.quitset.is_none() {
675
0
            self.quitset = Some(ByteSet::empty());
676
0
        }
677
0
        if yes {
678
0
            self.quitset.as_mut().unwrap().add(byte);
679
0
        } else {
680
0
            self.quitset.as_mut().unwrap().remove(byte);
681
0
        }
682
0
        self
683
0
    }
684
685
    /// Enable specializing start states in the DFA.
686
    ///
687
    /// When start states are specialized, an implementor of a search routine
688
    /// using a lazy DFA can tell when the search has entered a starting state.
689
    /// When start states aren't specialized, then it is impossible to know
690
    /// whether the search has entered a start state.
691
    ///
692
    /// Ideally, this option wouldn't need to exist and we could always
693
    /// specialize start states. The problem is that start states can be quite
694
    /// active. This in turn means that an efficient search routine is likely
695
    /// to ping-pong between a heavily optimized hot loop that handles most
696
    /// states and to a less optimized specialized handling of start states.
697
    /// This causes branches to get heavily mispredicted and overall can
698
    /// materially decrease throughput. Therefore, specializing start states
699
    /// should only be enabled when it is needed.
700
    ///
701
    /// Knowing whether a search is in a start state is typically useful when a
702
    /// prefilter is active for the search. A prefilter is typically only run
703
    /// when in a start state and a prefilter can greatly accelerate a search.
704
    /// Therefore, the possible cost of specializing start states is worth it
705
    /// in this case. Otherwise, if you have no prefilter, there is likely no
706
    /// reason to specialize start states.
707
    ///
708
    /// This is disabled by default, but note that it is automatically
709
    /// enabled (or disabled) if [`Config::prefilter`] is set. Namely, unless
710
    /// `specialize_start_states` has already been set, [`Config::prefilter`]
711
    /// will automatically enable or disable it based on whether a prefilter
712
    /// is present or not, respectively. This is done because a prefilter's
713
    /// effectiveness is rooted in being executed whenever the DFA is in a
714
    /// start state, and that's only possible to do when they are specialized.
715
    ///
716
    /// Note that it is plausibly reasonable to _disable_ this option
717
    /// explicitly while _enabling_ a prefilter. In that case, a prefilter
718
    /// will still be run at the beginning of a search, but never again. This
719
    /// in theory could strike a good balance if you're in a situation where a
720
    /// prefilter is likely to produce many false positive candidates.
721
    ///
722
    /// # Example
723
    ///
724
    /// This example shows how to enable start state specialization and then
725
    /// shows how to check whether a state is a start state or not.
726
    ///
727
    /// ```
728
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, Input};
729
    ///
730
    /// let dfa = DFA::builder()
731
    ///     .configure(DFA::config().specialize_start_states(true))
732
    ///     .build(r"[a-z]+")?;
733
    ///
734
    /// let haystack = "123 foobar 4567".as_bytes();
735
    /// let sid = dfa.start_state_forward(&Input::new(haystack))?;
736
    /// // The ID returned by 'start_state_forward' will always be tagged as
737
    /// // a start state when start state specialization is enabled.
738
    /// assert!(dfa.is_special_state(sid));
739
    /// assert!(dfa.is_start_state(sid));
740
    ///
741
    /// # Ok::<(), Box<dyn std::error::Error>>(())
742
    /// ```
743
    ///
744
    /// Compare the above with the default DFA configuration where start states
745
    /// are _not_ specialized. In this case, the start state is not tagged at
746
    /// all:
747
    ///
748
    /// ```
749
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, Input};
750
    ///
751
    /// let dfa = DFA::new(r"[a-z]+")?;
752
    ///
753
    /// let haystack = "123 foobar 4567";
754
    /// let sid = dfa.start_state_forward(&Input::new(haystack))?;
755
    /// // Start states are not special in the default configuration!
756
    /// assert!(!dfa.is_special_state(sid));
757
    /// assert!(!dfa.is_start_state(sid));
758
    ///
759
    /// # Ok::<(), Box<dyn std::error::Error>>(())
760
    /// ```
761
82.1k
    pub fn specialize_start_states(mut self, yes: bool) -> Config {
762
82.1k
        self.specialize_start_states = Some(yes);
763
82.1k
        self
764
82.1k
    }
765
766
    /// Set a size limit on the total heap used by a DFA.
767
    ///
768
    /// This size limit is expressed in bytes and is applied during
769
    /// determinization of an NFA into a DFA. If the DFA's heap usage, and only
770
    /// the DFA, exceeds this configured limit, then determinization is stopped
771
    /// and an error is returned.
772
    ///
773
    /// This limit does not apply to auxiliary storage used during
774
    /// determinization that isn't part of the generated DFA.
775
    ///
776
    /// This limit is only applied during determinization. Currently, there is
777
    /// no way to post-pone this check to after minimization if minimization
778
    /// was enabled.
779
    ///
780
    /// The total limit on heap used during determinization is the sum of the
781
    /// DFA and determinization size limits.
782
    ///
783
    /// The default is no limit.
784
    ///
785
    /// # Example
786
    ///
787
    /// This example shows a DFA that fails to build because of a configured
788
    /// size limit. This particular example also serves as a cautionary tale
789
    /// demonstrating just how big DFAs with large Unicode character classes
790
    /// can get.
791
    ///
792
    /// ```
793
    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
794
    /// use regex_automata::{dfa::{dense, Automaton}, Input};
795
    ///
796
    /// // 6MB isn't enough!
797
    /// dense::Builder::new()
798
    ///     .configure(dense::Config::new().dfa_size_limit(Some(6_000_000)))
799
    ///     .build(r"\w{20}")
800
    ///     .unwrap_err();
801
    ///
802
    /// // ... but 7MB probably is!
803
    /// // (Note that DFA sizes aren't necessarily stable between releases.)
804
    /// let dfa = dense::Builder::new()
805
    ///     .configure(dense::Config::new().dfa_size_limit(Some(7_000_000)))
806
    ///     .build(r"\w{20}")?;
807
    /// let haystack = "A".repeat(20).into_bytes();
808
    /// assert!(dfa.try_search_fwd(&Input::new(&haystack))?.is_some());
809
    ///
810
    /// # Ok::<(), Box<dyn std::error::Error>>(())
811
    /// ```
812
    ///
813
    /// While one needs a little more than 6MB to represent `\w{20}`, it
814
    /// turns out that you only need a little more than 6KB to represent
815
    /// `(?-u:\w{20})`. So only use Unicode if you need it!
816
    ///
817
    /// As with [`Config::determinize_size_limit`], the size of a DFA is
818
    /// influenced by other factors, such as what start state configurations
819
    /// to support. For example, if you only need unanchored searches and not
820
    /// anchored searches, then configuring the DFA to only support unanchored
821
    /// searches can reduce its size. By default, DFAs support both unanchored
822
    /// and anchored searches.
823
    ///
824
    /// ```
825
    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
826
    /// use regex_automata::{dfa::{dense, Automaton, StartKind}, Input};
827
    ///
828
    /// // 3MB isn't enough!
829
    /// dense::Builder::new()
830
    ///     .configure(dense::Config::new()
831
    ///         .dfa_size_limit(Some(3_000_000))
832
    ///         .start_kind(StartKind::Unanchored)
833
    ///     )
834
    ///     .build(r"\w{20}")
835
    ///     .unwrap_err();
836
    ///
837
    /// // ... but 4MB probably is!
838
    /// // (Note that DFA sizes aren't necessarily stable between releases.)
839
    /// let dfa = dense::Builder::new()
840
    ///     .configure(dense::Config::new()
841
    ///         .dfa_size_limit(Some(4_000_000))
842
    ///         .start_kind(StartKind::Unanchored)
843
    ///     )
844
    ///     .build(r"\w{20}")?;
845
    /// let haystack = "A".repeat(20).into_bytes();
846
    /// assert!(dfa.try_search_fwd(&Input::new(&haystack))?.is_some());
847
    ///
848
    /// # Ok::<(), Box<dyn std::error::Error>>(())
849
    /// ```
850
43.4k
    pub fn dfa_size_limit(mut self, bytes: Option<usize>) -> Config {
851
43.4k
        self.dfa_size_limit = Some(bytes);
852
43.4k
        self
853
43.4k
    }
854
855
    /// Set a size limit on the total heap used by determinization.
856
    ///
857
    /// This size limit is expressed in bytes and is applied during
858
    /// determinization of an NFA into a DFA. If the heap used for auxiliary
859
    /// storage during determinization (memory that is not in the DFA but
860
    /// necessary for building the DFA) exceeds this configured limit, then
861
    /// determinization is stopped and an error is returned.
862
    ///
863
    /// This limit does not apply to heap used by the DFA itself.
864
    ///
865
    /// The total limit on heap used during determinization is the sum of the
866
    /// DFA and determinization size limits.
867
    ///
868
    /// The default is no limit.
869
    ///
870
    /// # Example
871
    ///
872
    /// This example shows a DFA that fails to build because of a
873
    /// configured size limit on the amount of heap space used by
874
    /// determinization. This particular example complements the example for
875
    /// [`Config::dfa_size_limit`] by demonstrating that not only does Unicode
876
    /// potentially make DFAs themselves big, but it also results in more
877
    /// auxiliary storage during determinization. (Although, auxiliary storage
878
    /// is still not as much as the DFA itself.)
879
    ///
880
    /// ```
881
    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
882
    /// # if !cfg!(target_pointer_width = "64") { return Ok(()); } // see #1039
883
    /// use regex_automata::{dfa::{dense, Automaton}, Input};
884
    ///
885
    /// // 700KB isn't enough!
886
    /// dense::Builder::new()
887
    ///     .configure(dense::Config::new()
888
    ///         .determinize_size_limit(Some(700_000))
889
    ///     )
890
    ///     .build(r"\w{20}")
891
    ///     .unwrap_err();
892
    ///
893
    /// // ... but 800KB probably is!
894
    /// // (Note that auxiliary storage sizes aren't necessarily stable between
895
    /// // releases.)
896
    /// let dfa = dense::Builder::new()
897
    ///     .configure(dense::Config::new()
898
    ///         .determinize_size_limit(Some(800_000))
899
    ///     )
900
    ///     .build(r"\w{20}")?;
901
    /// let haystack = "A".repeat(20).into_bytes();
902
    /// assert!(dfa.try_search_fwd(&Input::new(&haystack))?.is_some());
903
    ///
904
    /// # Ok::<(), Box<dyn std::error::Error>>(())
905
    /// ```
906
    ///
907
    /// Note that some parts of the configuration on a DFA can have a
908
    /// big impact on how big the DFA is, and thus, how much memory is
909
    /// used. For example, the default setting for [`Config::start_kind`] is
910
    /// [`StartKind::Both`]. But if you only need an anchored search, for
911
    /// example, then it can be much cheaper to build a DFA that only supports
912
    /// anchored searches. (Running an unanchored search with it would panic.)
913
    ///
914
    /// ```
915
    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
916
    /// # if !cfg!(target_pointer_width = "64") { return Ok(()); } // see #1039
917
    /// use regex_automata::{
918
    ///     dfa::{dense, Automaton, StartKind},
919
    ///     Anchored, Input,
920
    /// };
921
    ///
922
    /// // 200KB isn't enough!
923
    /// dense::Builder::new()
924
    ///     .configure(dense::Config::new()
925
    ///         .determinize_size_limit(Some(200_000))
926
    ///         .start_kind(StartKind::Anchored)
927
    ///     )
928
    ///     .build(r"\w{20}")
929
    ///     .unwrap_err();
930
    ///
931
    /// // ... but 300KB probably is!
932
    /// // (Note that auxiliary storage sizes aren't necessarily stable between
933
    /// // releases.)
934
    /// let dfa = dense::Builder::new()
935
    ///     .configure(dense::Config::new()
936
    ///         .determinize_size_limit(Some(300_000))
937
    ///         .start_kind(StartKind::Anchored)
938
    ///     )
939
    ///     .build(r"\w{20}")?;
940
    /// let haystack = "A".repeat(20).into_bytes();
941
    /// let input = Input::new(&haystack).anchored(Anchored::Yes);
942
    /// assert!(dfa.try_search_fwd(&input)?.is_some());
943
    ///
944
    /// # Ok::<(), Box<dyn std::error::Error>>(())
945
    /// ```
946
43.4k
    pub fn determinize_size_limit(mut self, bytes: Option<usize>) -> Config {
947
43.4k
        self.determinize_size_limit = Some(bytes);
948
43.4k
        self
949
43.4k
    }
950
951
    /// Returns whether this configuration has enabled simple state
952
    /// acceleration.
953
80.2k
    pub fn get_accelerate(&self) -> bool {
954
80.2k
        self.accelerate.unwrap_or(true)
955
80.2k
    }
956
957
    /// Returns the prefilter attached to this configuration, if any.
958
125k
    pub fn get_prefilter(&self) -> Option<&Prefilter> {
959
125k
        self.pre.as_ref().unwrap_or(&None).as_ref()
960
125k
    }
961
962
    /// Returns whether this configuration has enabled the expensive process
963
    /// of minimizing a DFA.
964
80.2k
    pub fn get_minimize(&self) -> bool {
965
80.2k
        self.minimize.unwrap_or(false)
966
80.2k
    }
967
968
    /// Returns the match semantics set in this configuration.
969
82.1k
    pub fn get_match_kind(&self) -> MatchKind {
970
82.1k
        self.match_kind.unwrap_or(MatchKind::LeftmostFirst)
971
82.1k
    }
972
973
    /// Returns the starting state configuration for a DFA.
974
82.1k
    pub fn get_starts(&self) -> StartKind {
975
82.1k
        self.start_kind.unwrap_or(StartKind::Both)
976
82.1k
    }
977
978
    /// Returns whether this configuration has enabled anchored starting states
979
    /// for every pattern in the DFA.
980
82.1k
    pub fn get_starts_for_each_pattern(&self) -> bool {
981
82.1k
        self.starts_for_each_pattern.unwrap_or(false)
982
82.1k
    }
983
984
    /// Returns whether this configuration has enabled byte classes or not.
985
    /// This is typically a debugging oriented option, as disabling it confers
986
    /// no speed benefit.
987
82.1k
    pub fn get_byte_classes(&self) -> bool {
988
82.1k
        self.byte_classes.unwrap_or(true)
989
82.1k
    }
990
991
    /// Returns whether this configuration has enabled heuristic Unicode word
992
    /// boundary support. When enabled, it is possible for a search to return
993
    /// an error.
994
82.1k
    pub fn get_unicode_word_boundary(&self) -> bool {
995
82.1k
        self.unicode_word_boundary.unwrap_or(false)
996
82.1k
    }
997
998
    /// Returns whether this configuration will instruct the DFA to enter a
999
    /// quit state whenever the given byte is seen during a search. When at
1000
    /// least one byte has this enabled, it is possible for a search to return
1001
    /// an error.
1002
0
    pub fn get_quit(&self, byte: u8) -> bool {
1003
0
        self.quitset.map_or(false, |q| q.contains(byte))
1004
0
    }
1005
1006
    /// Returns whether this configuration will instruct the DFA to
1007
    /// "specialize" start states. When enabled, the DFA will mark start states
1008
    /// as "special" so that search routines using the DFA can detect when
1009
    /// it's in a start state and do some kind of optimization (like run a
1010
    /// prefilter).
1011
80.2k
    pub fn get_specialize_start_states(&self) -> bool {
1012
80.2k
        self.specialize_start_states.unwrap_or(false)
1013
80.2k
    }
1014
1015
    /// Returns the DFA size limit of this configuration if one was set.
1016
    /// The size limit is total number of bytes on the heap that a DFA is
1017
    /// permitted to use. If the DFA exceeds this limit during construction,
1018
    /// then construction is stopped and an error is returned.
1019
82.1k
    pub fn get_dfa_size_limit(&self) -> Option<usize> {
1020
82.1k
        self.dfa_size_limit.unwrap_or(None)
1021
82.1k
    }
1022
1023
    /// Returns the determinization size limit of this configuration if one
1024
    /// was set. The size limit is total number of bytes on the heap that
1025
    /// determinization is permitted to use. If determinization exceeds this
1026
    /// limit during construction, then construction is stopped and an error is
1027
    /// returned.
1028
    ///
1029
    /// This is different from the DFA size limit in that this only applies to
1030
    /// the auxiliary storage used during determinization. Once determinization
1031
    /// is complete, this memory is freed.
1032
    ///
1033
    /// The limit on the total heap memory used is the sum of the DFA and
1034
    /// determinization size limits.
1035
82.1k
    pub fn get_determinize_size_limit(&self) -> Option<usize> {
1036
82.1k
        self.determinize_size_limit.unwrap_or(None)
1037
82.1k
    }
1038
1039
    /// Overwrite the default configuration such that the options in `o` are
1040
    /// always used. If an option in `o` is not set, then the corresponding
1041
    /// option in `self` is used. If it's not set in `self` either, then it
1042
    /// remains not set.
1043
82.1k
    pub(crate) fn overwrite(&self, o: Config) -> Config {
1044
        Config {
1045
82.1k
            accelerate: o.accelerate.or(self.accelerate),
1046
82.1k
            pre: o.pre.or_else(|| self.pre.clone()),
1047
82.1k
            minimize: o.minimize.or(self.minimize),
1048
82.1k
            match_kind: o.match_kind.or(self.match_kind),
1049
82.1k
            start_kind: o.start_kind.or(self.start_kind),
1050
82.1k
            starts_for_each_pattern: o
1051
82.1k
                .starts_for_each_pattern
1052
82.1k
                .or(self.starts_for_each_pattern),
1053
82.1k
            byte_classes: o.byte_classes.or(self.byte_classes),
1054
82.1k
            unicode_word_boundary: o
1055
82.1k
                .unicode_word_boundary
1056
82.1k
                .or(self.unicode_word_boundary),
1057
82.1k
            quitset: o.quitset.or(self.quitset),
1058
82.1k
            specialize_start_states: o
1059
82.1k
                .specialize_start_states
1060
82.1k
                .or(self.specialize_start_states),
1061
82.1k
            dfa_size_limit: o.dfa_size_limit.or(self.dfa_size_limit),
1062
82.1k
            determinize_size_limit: o
1063
82.1k
                .determinize_size_limit
1064
82.1k
                .or(self.determinize_size_limit),
1065
        }
1066
82.1k
    }
1067
}
1068
1069
/// A builder for constructing a deterministic finite automaton from regular
1070
/// expressions.
1071
///
1072
/// This builder provides two main things:
1073
///
1074
/// 1. It provides a few different `build` routines for actually constructing
1075
/// a DFA from different kinds of inputs. The most convenient is
1076
/// [`Builder::build`], which builds a DFA directly from a pattern string. The
1077
/// most flexible is [`Builder::build_from_nfa`], which builds a DFA straight
1078
/// from an NFA.
1079
/// 2. The builder permits configuring a number of things.
1080
/// [`Builder::configure`] is used with [`Config`] to configure aspects of
1081
/// the DFA and the construction process itself. [`Builder::syntax`] and
1082
/// [`Builder::thompson`] permit configuring the regex parser and Thompson NFA
1083
/// construction, respectively. The syntax and thompson configurations only
1084
/// apply when building from a pattern string.
1085
///
1086
/// This builder always constructs a *single* DFA. As such, this builder
1087
/// can only be used to construct regexes that either detect the presence
1088
/// of a match or find the end location of a match. A single DFA cannot
1089
/// produce both the start and end of a match. For that information, use a
1090
/// [`Regex`](crate::dfa::regex::Regex), which can be similarly configured
1091
/// using [`regex::Builder`](crate::dfa::regex::Builder). The main reason to
1092
/// use a DFA directly is if the end location of a match is enough for your use
1093
/// case. Namely, a `Regex` will construct two DFAs instead of one, since a
1094
/// second reverse DFA is needed to find the start of a match.
1095
///
1096
/// Note that if one wants to build a sparse DFA, you must first build a dense
1097
/// DFA and convert that to a sparse DFA. There is no way to build a sparse
1098
/// DFA without first building a dense DFA.
1099
///
1100
/// # Example
1101
///
1102
/// This example shows how to build a minimized DFA that completely disables
1103
/// Unicode. That is:
1104
///
1105
/// * Things such as `\w`, `.` and `\b` are no longer Unicode-aware. `\w`
1106
///   and `\b` are ASCII-only while `.` matches any byte except for `\n`
1107
///   (instead of any UTF-8 encoding of a Unicode scalar value except for
1108
///   `\n`). Things that are Unicode only, such as `\pL`, are not allowed.
1109
/// * The pattern itself is permitted to match invalid UTF-8. For example,
1110
///   things like `[^a]` that match any byte except for `a` are permitted.
1111
///
1112
/// ```
1113
/// use regex_automata::{
1114
///     dfa::{Automaton, dense},
1115
///     util::syntax,
1116
///     HalfMatch, Input,
1117
/// };
1118
///
1119
/// let dfa = dense::Builder::new()
1120
///     .configure(dense::Config::new().minimize(false))
1121
///     .syntax(syntax::Config::new().unicode(false).utf8(false))
1122
///     .build(r"foo[^b]ar.*")?;
1123
///
1124
/// let haystack = b"\xFEfoo\xFFar\xE2\x98\xFF\n";
1125
/// let expected = Some(HalfMatch::must(0, 10));
1126
/// let got = dfa.try_search_fwd(&Input::new(haystack))?;
1127
/// assert_eq!(expected, got);
1128
///
1129
/// # Ok::<(), Box<dyn std::error::Error>>(())
1130
/// ```
1131
#[cfg(feature = "dfa-build")]
1132
#[derive(Clone, Debug)]
1133
pub struct Builder {
1134
    config: Config,
1135
    #[cfg(feature = "syntax")]
1136
    thompson: thompson::Compiler,
1137
}
1138
1139
#[cfg(feature = "dfa-build")]
1140
impl Builder {
1141
    /// Create a new dense DFA builder with the default configuration.
1142
120k
    pub fn new() -> Builder {
1143
120k
        Builder {
1144
120k
            config: Config::default(),
1145
120k
            #[cfg(feature = "syntax")]
1146
120k
            thompson: thompson::Compiler::new(),
1147
120k
        }
1148
120k
    }
1149
1150
    /// Build a DFA from the given pattern.
1151
    ///
1152
    /// If there was a problem parsing or compiling the pattern, then an error
1153
    /// is returned.
1154
    #[cfg(feature = "syntax")]
1155
0
    pub fn build(&self, pattern: &str) -> Result<OwnedDFA, BuildError> {
1156
0
        self.build_many(&[pattern])
1157
0
    }
1158
1159
    /// Build a DFA from the given patterns.
1160
    ///
1161
    /// When matches are returned, the pattern ID corresponds to the index of
1162
    /// the pattern in the slice given.
1163
    #[cfg(feature = "syntax")]
1164
0
    pub fn build_many<P: AsRef<str>>(
1165
0
        &self,
1166
0
        patterns: &[P],
1167
0
    ) -> Result<OwnedDFA, BuildError> {
1168
0
        let nfa = self
1169
0
            .thompson
1170
0
            .clone()
1171
0
            // We can always forcefully disable captures because DFAs do not
1172
0
            // support them.
1173
0
            .configure(
1174
0
                thompson::Config::new()
1175
0
                    .which_captures(thompson::WhichCaptures::None),
1176
0
            )
1177
0
            .build_many(patterns)
1178
0
            .map_err(BuildError::nfa)?;
1179
0
        self.build_from_nfa(&nfa)
1180
0
    }
1181
1182
    /// Build a DFA from the given NFA.
1183
    ///
1184
    /// # Example
1185
    ///
1186
    /// This example shows how to build a DFA if you already have an NFA in
1187
    /// hand.
1188
    ///
1189
    /// ```
1190
    /// use regex_automata::{
1191
    ///     dfa::{Automaton, dense},
1192
    ///     nfa::thompson::NFA,
1193
    ///     HalfMatch, Input,
1194
    /// };
1195
    ///
1196
    /// let haystack = "foo123bar".as_bytes();
1197
    ///
1198
    /// // This shows how to set non-default options for building an NFA.
1199
    /// let nfa = NFA::compiler()
1200
    ///     .configure(NFA::config().shrink(true))
1201
    ///     .build(r"[0-9]+")?;
1202
    /// let dfa = dense::Builder::new().build_from_nfa(&nfa)?;
1203
    /// let expected = Some(HalfMatch::must(0, 6));
1204
    /// let got = dfa.try_search_fwd(&Input::new(haystack))?;
1205
    /// assert_eq!(expected, got);
1206
    ///
1207
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1208
    /// ```
1209
82.1k
    pub fn build_from_nfa(
1210
82.1k
        &self,
1211
82.1k
        nfa: &thompson::NFA,
1212
82.1k
    ) -> Result<OwnedDFA, BuildError> {
1213
82.1k
        let mut quitset = self.config.quitset.unwrap_or(ByteSet::empty());
1214
82.1k
        if self.config.get_unicode_word_boundary()
1215
82.1k
            && nfa.look_set_any().contains_word_unicode()
1216
        {
1217
3.67M
            for b in 0x80..=0xFF {
1218
3.64M
                quitset.add(b);
1219
3.64M
            }
1220
53.6k
        }
1221
82.1k
        let classes = if !self.config.get_byte_classes() {
1222
            // DFAs will always use the equivalence class map, but enabling
1223
            // this option is useful for debugging. Namely, this will cause all
1224
            // transitions to be defined over their actual bytes instead of an
1225
            // opaque equivalence class identifier. The former is much easier
1226
            // to grok as a human.
1227
0
            ByteClasses::singletons()
1228
        } else {
1229
82.1k
            let mut set = nfa.byte_class_set().clone();
1230
            // It is important to distinguish any "quit" bytes from all other
1231
            // bytes. Otherwise, a non-quit byte may end up in the same
1232
            // class as a quit byte, and thus cause the DFA to stop when it
1233
            // shouldn't.
1234
            //
1235
            // Test case:
1236
            //
1237
            //   regex-cli find match dense --unicode-word-boundary \
1238
            //     -p '^#' -p '\b10\.55\.182\.100\b' -y @conn.json.1000x.log
1239
82.1k
            if !quitset.is_empty() {
1240
28.4k
                set.add_set(&quitset);
1241
53.6k
            }
1242
82.1k
            set.byte_classes()
1243
        };
1244
1245
82.1k
        let mut dfa = DFA::initial(
1246
82.1k
            classes,
1247
82.1k
            nfa.pattern_len(),
1248
82.1k
            self.config.get_starts(),
1249
82.1k
            nfa.look_matcher(),
1250
82.1k
            self.config.get_starts_for_each_pattern(),
1251
82.1k
            self.config.get_prefilter().map(|p| p.clone()),
1252
82.1k
            quitset,
1253
82.1k
            Flags::from_nfa(&nfa),
1254
0
        )?;
1255
82.1k
        determinize::Config::new()
1256
82.1k
            .match_kind(self.config.get_match_kind())
1257
82.1k
            .quit(quitset)
1258
82.1k
            .dfa_size_limit(self.config.get_dfa_size_limit())
1259
82.1k
            .determinize_size_limit(self.config.get_determinize_size_limit())
1260
82.1k
            .run(nfa, &mut dfa)?;
1261
80.2k
        if self.config.get_minimize() {
1262
0
            dfa.minimize();
1263
80.2k
        }
1264
80.2k
        if self.config.get_accelerate() {
1265
77.3k
            dfa.accelerate();
1266
77.3k
        }
1267
        // The state shuffling done before this point always assumes that start
1268
        // states should be marked as "special," even though it isn't the
1269
        // default configuration. State shuffling is complex enough as it is,
1270
        // so it's simpler to just "fix" our special state ID ranges to not
1271
        // include starting states after-the-fact.
1272
80.2k
        if !self.config.get_specialize_start_states() {
1273
65.0k
            dfa.special.set_no_special_start_states();
1274
65.0k
        }
1275
        // Look for and set the universal starting states.
1276
80.2k
        dfa.set_universal_starts();
1277
80.2k
        dfa.tt.table.shrink_to_fit();
1278
80.2k
        dfa.st.table.shrink_to_fit();
1279
80.2k
        dfa.ms.slices.shrink_to_fit();
1280
80.2k
        dfa.ms.pattern_ids.shrink_to_fit();
1281
80.2k
        Ok(dfa)
1282
82.1k
    }
1283
1284
    /// Apply the given dense DFA configuration options to this builder.
1285
82.1k
    pub fn configure(&mut self, config: Config) -> &mut Builder {
1286
82.1k
        self.config = self.config.overwrite(config);
1287
82.1k
        self
1288
82.1k
    }
1289
1290
    /// Set the syntax configuration for this builder using
1291
    /// [`syntax::Config`](crate::util::syntax::Config).
1292
    ///
1293
    /// This permits setting things like case insensitivity, Unicode and multi
1294
    /// line mode.
1295
    ///
1296
    /// These settings only apply when constructing a DFA directly from a
1297
    /// pattern.
1298
    #[cfg(feature = "syntax")]
1299
0
    pub fn syntax(
1300
0
        &mut self,
1301
0
        config: crate::util::syntax::Config,
1302
0
    ) -> &mut Builder {
1303
0
        self.thompson.syntax(config);
1304
0
        self
1305
0
    }
1306
1307
    /// Set the Thompson NFA configuration for this builder using
1308
    /// [`nfa::thompson::Config`](crate::nfa::thompson::Config).
1309
    ///
1310
    /// This permits setting things like whether the DFA should match the regex
1311
    /// in reverse or if additional time should be spent shrinking the size of
1312
    /// the NFA.
1313
    ///
1314
    /// These settings only apply when constructing a DFA directly from a
1315
    /// pattern.
1316
    #[cfg(feature = "syntax")]
1317
0
    pub fn thompson(&mut self, config: thompson::Config) -> &mut Builder {
1318
0
        self.thompson.configure(config);
1319
0
        self
1320
0
    }
1321
}
1322
1323
#[cfg(feature = "dfa-build")]
1324
impl Default for Builder {
1325
0
    fn default() -> Builder {
1326
0
        Builder::new()
1327
0
    }
1328
}
1329
1330
/// A convenience alias for an owned DFA. We use this particular instantiation
1331
/// a lot in this crate, so it's worth giving it a name. This instantiation
1332
/// is commonly used for mutable APIs on the DFA while building it. The main
1333
/// reason for making DFAs generic is no_std support, and more generally,
1334
/// making it possible to load a DFA from an arbitrary slice of bytes.
1335
#[cfg(feature = "alloc")]
1336
pub(crate) type OwnedDFA = DFA<alloc::vec::Vec<u32>>;
1337
1338
/// A dense table-based deterministic finite automaton (DFA).
1339
///
1340
/// All dense DFAs have one or more start states, zero or more match states
1341
/// and a transition table that maps the current state and the current byte
1342
/// of input to the next state. A DFA can use this information to implement
1343
/// fast searching. In particular, the use of a dense DFA generally makes the
1344
/// trade off that match speed is the most valuable characteristic, even if
1345
/// building the DFA may take significant time *and* space. (More concretely,
1346
/// building a DFA takes time and space that is exponential in the size of the
1347
/// pattern in the worst case.) As such, the processing of every byte of input
1348
/// is done with a small constant number of operations that does not vary with
1349
/// the pattern, its size or the size of the alphabet. If your needs don't line
1350
/// up with this trade off, then a dense DFA may not be an adequate solution to
1351
/// your problem.
1352
///
1353
/// In contrast, a [`sparse::DFA`] makes the opposite
1354
/// trade off: it uses less space but will execute a variable number of
1355
/// instructions per byte at match time, which makes it slower for matching.
1356
/// (Note that space usage is still exponential in the size of the pattern in
1357
/// the worst case.)
1358
///
1359
/// A DFA can be built using the default configuration via the
1360
/// [`DFA::new`] constructor. Otherwise, one can
1361
/// configure various aspects via [`dense::Builder`](Builder).
1362
///
1363
/// A single DFA fundamentally supports the following operations:
1364
///
1365
/// 1. Detection of a match.
1366
/// 2. Location of the end of a match.
1367
/// 3. In the case of a DFA with multiple patterns, which pattern matched is
1368
///    reported as well.
1369
///
1370
/// A notable absence from the above list of capabilities is the location of
1371
/// the *start* of a match. In order to provide both the start and end of
1372
/// a match, *two* DFAs are required. This functionality is provided by a
1373
/// [`Regex`](crate::dfa::regex::Regex).
1374
///
1375
/// # Type parameters
1376
///
1377
/// A `DFA` has one type parameter, `T`, which is used to represent state IDs,
1378
/// pattern IDs and accelerators. `T` is typically a `Vec<u32>` or a `&[u32]`.
1379
///
1380
/// # The `Automaton` trait
1381
///
1382
/// This type implements the [`Automaton`] trait, which means it can be used
1383
/// for searching. For example:
1384
///
1385
/// ```
1386
/// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
1387
///
1388
/// let dfa = DFA::new("foo[0-9]+")?;
1389
/// let expected = HalfMatch::must(0, 8);
1390
/// assert_eq!(Some(expected), dfa.try_search_fwd(&Input::new("foo12345"))?);
1391
/// # Ok::<(), Box<dyn std::error::Error>>(())
1392
/// ```
1393
#[derive(Clone)]
1394
pub struct DFA<T> {
1395
    /// The transition table for this DFA. This includes the transitions
1396
    /// themselves, along with the stride, number of states and the equivalence
1397
    /// class mapping.
1398
    tt: TransitionTable<T>,
1399
    /// The set of starting state identifiers for this DFA. The starting state
1400
    /// IDs act as pointers into the transition table. The specific starting
1401
    /// state chosen for each search is dependent on the context at which the
1402
    /// search begins.
1403
    st: StartTable<T>,
1404
    /// The set of match states and the patterns that match for each
1405
    /// corresponding match state.
1406
    ///
1407
    /// This structure is technically only needed because of support for
1408
    /// multi-regexes. Namely, multi-regexes require answering not just whether
1409
    /// a match exists, but _which_ patterns match. So we need to store the
1410
    /// matching pattern IDs for each match state. We do this even when there
1411
    /// is only one pattern for the sake of simplicity. In practice, this uses
1412
    /// up very little space for the case of one pattern.
1413
    ms: MatchStates<T>,
1414
    /// Information about which states are "special." Special states are states
1415
    /// that are dead, quit, matching, starting or accelerated. For more info,
1416
    /// see the docs for `Special`.
1417
    special: Special,
1418
    /// The accelerators for this DFA.
1419
    ///
1420
    /// If a state is accelerated, then there exist only a small number of
1421
    /// bytes that can cause the DFA to leave the state. This permits searching
1422
    /// to use optimized routines to find those specific bytes instead of using
1423
    /// the transition table.
1424
    ///
1425
    /// All accelerated states exist in a contiguous range in the DFA's
1426
    /// transition table. See dfa/special.rs for more details on how states are
1427
    /// arranged.
1428
    accels: Accels<T>,
1429
    /// Any prefilter attached to this DFA.
1430
    ///
1431
    /// Note that currently prefilters are not serialized. When deserializing
1432
    /// a DFA from bytes, this is always set to `None`.
1433
    pre: Option<Prefilter>,
1434
    /// The set of "quit" bytes for this DFA.
1435
    ///
1436
    /// This is only used when computing the start state for a particular
1437
    /// position in a haystack. Namely, in the case where there is a quit
1438
    /// byte immediately before the start of the search, this set needs to be
1439
    /// explicitly consulted. In all other cases, quit bytes are detected by
1440
    /// the DFA itself, by transitioning all quit bytes to a special "quit
1441
    /// state."
1442
    quitset: ByteSet,
1443
    /// Various flags describing the behavior of this DFA.
1444
    flags: Flags,
1445
}
1446
1447
#[cfg(feature = "dfa-build")]
1448
impl OwnedDFA {
1449
    /// Parse the given regular expression using a default configuration and
1450
    /// return the corresponding DFA.
1451
    ///
1452
    /// If you want a non-default configuration, then use the
1453
    /// [`dense::Builder`](Builder) to set your own configuration.
1454
    ///
1455
    /// # Example
1456
    ///
1457
    /// ```
1458
    /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
1459
    ///
1460
    /// let dfa = dense::DFA::new("foo[0-9]+bar")?;
1461
    /// let expected = Some(HalfMatch::must(0, 11));
1462
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345bar"))?);
1463
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1464
    /// ```
1465
    #[cfg(feature = "syntax")]
1466
0
    pub fn new(pattern: &str) -> Result<OwnedDFA, BuildError> {
1467
0
        Builder::new().build(pattern)
1468
0
    }
1469
1470
    /// Parse the given regular expressions using a default configuration and
1471
    /// return the corresponding multi-DFA.
1472
    ///
1473
    /// If you want a non-default configuration, then use the
1474
    /// [`dense::Builder`](Builder) to set your own configuration.
1475
    ///
1476
    /// # Example
1477
    ///
1478
    /// ```
1479
    /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
1480
    ///
1481
    /// let dfa = dense::DFA::new_many(&["[0-9]+", "[a-z]+"])?;
1482
    /// let expected = Some(HalfMatch::must(1, 3));
1483
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345bar"))?);
1484
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1485
    /// ```
1486
    #[cfg(feature = "syntax")]
1487
    pub fn new_many<P: AsRef<str>>(
1488
        patterns: &[P],
1489
    ) -> Result<OwnedDFA, BuildError> {
1490
        Builder::new().build_many(patterns)
1491
    }
1492
}
1493
1494
#[cfg(feature = "dfa-build")]
1495
impl OwnedDFA {
1496
    /// Create a new DFA that matches every input.
1497
    ///
1498
    /// # Example
1499
    ///
1500
    /// ```
1501
    /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
1502
    ///
1503
    /// let dfa = dense::DFA::always_match()?;
1504
    ///
1505
    /// let expected = Some(HalfMatch::must(0, 0));
1506
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new(""))?);
1507
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo"))?);
1508
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1509
    /// ```
1510
0
    pub fn always_match() -> Result<OwnedDFA, BuildError> {
1511
0
        let nfa = thompson::NFA::always_match();
1512
0
        Builder::new().build_from_nfa(&nfa)
1513
0
    }
1514
1515
    /// Create a new DFA that never matches any input.
1516
    ///
1517
    /// # Example
1518
    ///
1519
    /// ```
1520
    /// use regex_automata::{dfa::{Automaton, dense}, Input};
1521
    ///
1522
    /// let dfa = dense::DFA::never_match()?;
1523
    /// assert_eq!(None, dfa.try_search_fwd(&Input::new(""))?);
1524
    /// assert_eq!(None, dfa.try_search_fwd(&Input::new("foo"))?);
1525
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1526
    /// ```
1527
0
    pub fn never_match() -> Result<OwnedDFA, BuildError> {
1528
0
        let nfa = thompson::NFA::never_match();
1529
0
        Builder::new().build_from_nfa(&nfa)
1530
0
    }
1531
1532
    /// Create an initial DFA with the given equivalence classes, pattern
1533
    /// length and whether anchored starting states are enabled for each
1534
    /// pattern. An initial DFA can be further mutated via determinization.
1535
82.1k
    fn initial(
1536
82.1k
        classes: ByteClasses,
1537
82.1k
        pattern_len: usize,
1538
82.1k
        starts: StartKind,
1539
82.1k
        lookm: &LookMatcher,
1540
82.1k
        starts_for_each_pattern: bool,
1541
82.1k
        pre: Option<Prefilter>,
1542
82.1k
        quitset: ByteSet,
1543
82.1k
        flags: Flags,
1544
82.1k
    ) -> Result<OwnedDFA, BuildError> {
1545
82.1k
        let start_pattern_len =
1546
82.1k
            if starts_for_each_pattern { Some(pattern_len) } else { None };
1547
        Ok(DFA {
1548
82.1k
            tt: TransitionTable::minimal(classes),
1549
82.1k
            st: StartTable::dead(starts, lookm, start_pattern_len)?,
1550
82.1k
            ms: MatchStates::empty(pattern_len),
1551
82.1k
            special: Special::new(),
1552
82.1k
            accels: Accels::empty(),
1553
82.1k
            pre,
1554
82.1k
            quitset,
1555
82.1k
            flags,
1556
        })
1557
82.1k
    }
1558
}
1559
1560
#[cfg(feature = "dfa-build")]
1561
impl DFA<&[u32]> {
1562
    /// Return a new default dense DFA compiler configuration.
1563
    ///
1564
    /// This is a convenience routine to avoid needing to import the [`Config`]
1565
    /// type when customizing the construction of a dense DFA.
1566
0
    pub fn config() -> Config {
1567
0
        Config::new()
1568
0
    }
1569
1570
    /// Create a new dense DFA builder with the default configuration.
1571
    ///
1572
    /// This is a convenience routine to avoid needing to import the
1573
    /// [`Builder`] type in common cases.
1574
0
    pub fn builder() -> Builder {
1575
0
        Builder::new()
1576
0
    }
1577
}
1578
1579
impl<T: AsRef<[u32]>> DFA<T> {
1580
    /// Cheaply return a borrowed version of this dense DFA. Specifically,
1581
    /// the DFA returned always uses `&[u32]` for its transition table.
1582
    pub fn as_ref(&self) -> DFA<&'_ [u32]> {
1583
        DFA {
1584
            tt: self.tt.as_ref(),
1585
            st: self.st.as_ref(),
1586
            ms: self.ms.as_ref(),
1587
            special: self.special,
1588
            accels: self.accels(),
1589
            pre: self.pre.clone(),
1590
            quitset: self.quitset,
1591
            flags: self.flags,
1592
        }
1593
    }
1594
1595
    /// Return an owned version of this sparse DFA. Specifically, the DFA
1596
    /// returned always uses `Vec<u32>` for its transition table.
1597
    ///
1598
    /// Effectively, this returns a dense DFA whose transition table lives on
1599
    /// the heap.
1600
    #[cfg(feature = "alloc")]
1601
    pub fn to_owned(&self) -> OwnedDFA {
1602
        DFA {
1603
            tt: self.tt.to_owned(),
1604
            st: self.st.to_owned(),
1605
            ms: self.ms.to_owned(),
1606
            special: self.special,
1607
            accels: self.accels().to_owned(),
1608
            pre: self.pre.clone(),
1609
            quitset: self.quitset,
1610
            flags: self.flags,
1611
        }
1612
    }
1613
1614
    /// Returns the starting state configuration for this DFA.
1615
    ///
1616
    /// The default is [`StartKind::Both`], which means the DFA supports both
1617
    /// unanchored and anchored searches. However, this can generally lead to
1618
    /// bigger DFAs. Therefore, a DFA might be compiled with support for just
1619
    /// unanchored or anchored searches. In that case, running a search with
1620
    /// an unsupported configuration will panic.
1621
324k
    pub fn start_kind(&self) -> StartKind {
1622
324k
        self.st.kind
1623
324k
    }
1624
1625
    /// Returns the start byte map used for computing the `Start` configuration
1626
    /// at the beginning of a search.
1627
0
    pub(crate) fn start_map(&self) -> &StartByteMap {
1628
0
        &self.st.start_map
1629
0
    }
1630
1631
    /// Returns true only if this DFA has starting states for each pattern.
1632
    ///
1633
    /// When a DFA has starting states for each pattern, then a search with the
1634
    /// DFA can be configured to only look for anchored matches of a specific
1635
    /// pattern. Specifically, APIs like [`Automaton::try_search_fwd`] can
1636
    /// accept a non-None `pattern_id` if and only if this method returns true.
1637
    /// Otherwise, calling `try_search_fwd` will panic.
1638
    ///
1639
    /// Note that if the DFA has no patterns, this always returns false.
1640
82.1k
    pub fn starts_for_each_pattern(&self) -> bool {
1641
82.1k
        self.st.pattern_len.is_some()
1642
82.1k
    }
1643
1644
    /// Returns the equivalence classes that make up the alphabet for this DFA.
1645
    ///
1646
    /// Unless [`Config::byte_classes`] was disabled, it is possible that
1647
    /// multiple distinct bytes are grouped into the same equivalence class
1648
    /// if it is impossible for them to discriminate between a match and a
1649
    /// non-match. This has the effect of reducing the overall alphabet size
1650
    /// and in turn potentially substantially reducing the size of the DFA's
1651
    /// transition table.
1652
    ///
1653
    /// The downside of using equivalence classes like this is that every state
1654
    /// transition will automatically use this map to convert an arbitrary
1655
    /// byte to its corresponding equivalence class. In practice this has a
1656
    /// negligible impact on performance.
1657
5.05M
    pub fn byte_classes(&self) -> &ByteClasses {
1658
5.05M
        &self.tt.classes
1659
5.05M
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>>>::byte_classes
Line
Count
Source
1657
4.80M
    pub fn byte_classes(&self) -> &ByteClasses {
1658
4.80M
        &self.tt.classes
1659
4.80M
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::byte_classes
Line
Count
Source
1657
251k
    pub fn byte_classes(&self) -> &ByteClasses {
1658
251k
        &self.tt.classes
1659
251k
    }
1660
1661
    /// Returns the total number of elements in the alphabet for this DFA.
1662
    ///
1663
    /// That is, this returns the total number of transitions that each state
1664
    /// in this DFA must have. Typically, a normal byte oriented DFA would
1665
    /// always have an alphabet size of 256, corresponding to the number of
1666
    /// unique values in a single byte. However, this implementation has two
1667
    /// peculiarities that impact the alphabet length:
1668
    ///
1669
    /// * Every state has a special "EOI" transition that is only followed
1670
    /// after the end of some haystack is reached. This EOI transition is
1671
    /// necessary to account for one byte of look-ahead when implementing
1672
    /// things like `\b` and `$`.
1673
    /// * Bytes are grouped into equivalence classes such that no two bytes in
1674
    /// the same class can distinguish a match from a non-match. For example,
1675
    /// in the regex `^[a-z]+$`, the ASCII bytes `a-z` could all be in the
1676
    /// same equivalence class. This leads to a massive space savings.
1677
    ///
1678
    /// Note though that the alphabet length does _not_ necessarily equal the
1679
    /// total stride space taken up by a single DFA state in the transition
1680
    /// table. Namely, for performance reasons, the stride is always the
1681
    /// smallest power of two that is greater than or equal to the alphabet
1682
    /// length. For this reason, [`DFA::stride`] or [`DFA::stride2`] are
1683
    /// often more useful. The alphabet length is typically useful only for
1684
    /// informational purposes.
1685
0
    pub fn alphabet_len(&self) -> usize {
1686
0
        self.tt.alphabet_len()
1687
0
    }
1688
1689
    /// Returns the total stride for every state in this DFA, expressed as the
1690
    /// exponent of a power of 2. The stride is the amount of space each state
1691
    /// takes up in the transition table, expressed as a number of transitions.
1692
    /// (Unused transitions map to dead states.)
1693
    ///
1694
    /// The stride of a DFA is always equivalent to the smallest power of 2
1695
    /// that is greater than or equal to the DFA's alphabet length. This
1696
    /// definition uses extra space, but permits faster translation between
1697
    /// premultiplied state identifiers and contiguous indices (by using shifts
1698
    /// instead of relying on integer division).
1699
    ///
1700
    /// For example, if the DFA's stride is 16 transitions, then its `stride2`
1701
    /// is `4` since `2^4 = 16`.
1702
    ///
1703
    /// The minimum `stride2` value is `1` (corresponding to a stride of `2`)
1704
    /// while the maximum `stride2` value is `9` (corresponding to a stride of
1705
    /// `512`). The maximum is not `8` since the maximum alphabet size is `257`
1706
    /// when accounting for the special EOI transition. However, an alphabet
1707
    /// length of that size is exceptionally rare since the alphabet is shrunk
1708
    /// into equivalence classes.
1709
196k
    pub fn stride2(&self) -> usize {
1710
196k
        self.tt.stride2
1711
196k
    }
1712
1713
    /// Returns the total stride for every state in this DFA. This corresponds
1714
    /// to the total number of transitions used by each state in this DFA's
1715
    /// transition table.
1716
    ///
1717
    /// Please see [`DFA::stride2`] for more information. In particular, this
1718
    /// returns the stride as the number of transitions, where as `stride2`
1719
    /// returns it as the exponent of a power of 2.
1720
9.52k
    pub fn stride(&self) -> usize {
1721
9.52k
        self.tt.stride()
1722
9.52k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>>>::stride
Line
Count
Source
1720
7.25k
    pub fn stride(&self) -> usize {
1721
7.25k
        self.tt.stride()
1722
7.25k
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::stride
Line
Count
Source
1720
2.27k
    pub fn stride(&self) -> usize {
1721
2.27k
        self.tt.stride()
1722
2.27k
    }
1723
1724
    /// Returns the memory usage, in bytes, of this DFA.
1725
    ///
1726
    /// The memory usage is computed based on the number of bytes used to
1727
    /// represent this DFA.
1728
    ///
1729
    /// This does **not** include the stack size used up by this DFA. To
1730
    /// compute that, use `std::mem::size_of::<dense::DFA>()`.
1731
852k
    pub fn memory_usage(&self) -> usize {
1732
852k
        self.tt.memory_usage()
1733
852k
            + self.st.memory_usage()
1734
852k
            + self.ms.memory_usage()
1735
852k
            + self.accels.memory_usage()
1736
852k
    }
1737
}
1738
1739
/// Routines for converting a dense DFA to other representations, such as
1740
/// sparse DFAs or raw bytes suitable for persistent storage.
1741
impl<T: AsRef<[u32]>> DFA<T> {
1742
    /// Convert this dense DFA to a sparse DFA.
1743
    ///
1744
    /// If a `StateID` is too small to represent all states in the sparse
1745
    /// DFA, then this returns an error. In most cases, if a dense DFA is
1746
    /// constructable with `StateID` then a sparse DFA will be as well.
1747
    /// However, it is not guaranteed.
1748
    ///
1749
    /// # Example
1750
    ///
1751
    /// ```
1752
    /// use regex_automata::{dfa::{Automaton, dense}, HalfMatch, Input};
1753
    ///
1754
    /// let dense = dense::DFA::new("foo[0-9]+")?;
1755
    /// let sparse = dense.to_sparse()?;
1756
    ///
1757
    /// let expected = Some(HalfMatch::must(0, 8));
1758
    /// assert_eq!(expected, sparse.try_search_fwd(&Input::new("foo12345"))?);
1759
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1760
    /// ```
1761
    #[cfg(feature = "dfa-build")]
1762
0
    pub fn to_sparse(&self) -> Result<sparse::DFA<Vec<u8>>, BuildError> {
1763
0
        sparse::DFA::from_dense(self)
1764
0
    }
1765
1766
    /// Serialize this DFA as raw bytes to a `Vec<u8>` in little endian
1767
    /// format. Upon success, the `Vec<u8>` and the initial padding length are
1768
    /// returned.
1769
    ///
1770
    /// The written bytes are guaranteed to be deserialized correctly and
1771
    /// without errors in a semver compatible release of this crate by a
1772
    /// `DFA`'s deserialization APIs (assuming all other criteria for the
1773
    /// deserialization APIs has been satisfied):
1774
    ///
1775
    /// * [`DFA::from_bytes`]
1776
    /// * [`DFA::from_bytes_unchecked`]
1777
    ///
1778
    /// The padding returned is non-zero if the returned `Vec<u8>` starts at
1779
    /// an address that does not have the same alignment as `u32`. The padding
1780
    /// corresponds to the number of leading bytes written to the returned
1781
    /// `Vec<u8>`.
1782
    ///
1783
    /// # Example
1784
    ///
1785
    /// This example shows how to serialize and deserialize a DFA:
1786
    ///
1787
    /// ```
1788
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
1789
    ///
1790
    /// // Compile our original DFA.
1791
    /// let original_dfa = DFA::new("foo[0-9]+")?;
1792
    ///
1793
    /// // N.B. We use native endianness here to make the example work, but
1794
    /// // using to_bytes_little_endian would work on a little endian target.
1795
    /// let (buf, _) = original_dfa.to_bytes_native_endian();
1796
    /// // Even if buf has initial padding, DFA::from_bytes will automatically
1797
    /// // ignore it.
1798
    /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf)?.0;
1799
    ///
1800
    /// let expected = Some(HalfMatch::must(0, 8));
1801
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
1802
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1803
    /// ```
1804
    #[cfg(feature = "dfa-build")]
1805
    pub fn to_bytes_little_endian(&self) -> (Vec<u8>, usize) {
1806
        self.to_bytes::<wire::LE>()
1807
    }
1808
1809
    /// Serialize this DFA as raw bytes to a `Vec<u8>` in big endian
1810
    /// format. Upon success, the `Vec<u8>` and the initial padding length are
1811
    /// returned.
1812
    ///
1813
    /// The written bytes are guaranteed to be deserialized correctly and
1814
    /// without errors in a semver compatible release of this crate by a
1815
    /// `DFA`'s deserialization APIs (assuming all other criteria for the
1816
    /// deserialization APIs has been satisfied):
1817
    ///
1818
    /// * [`DFA::from_bytes`]
1819
    /// * [`DFA::from_bytes_unchecked`]
1820
    ///
1821
    /// The padding returned is non-zero if the returned `Vec<u8>` starts at
1822
    /// an address that does not have the same alignment as `u32`. The padding
1823
    /// corresponds to the number of leading bytes written to the returned
1824
    /// `Vec<u8>`.
1825
    ///
1826
    /// # Example
1827
    ///
1828
    /// This example shows how to serialize and deserialize a DFA:
1829
    ///
1830
    /// ```
1831
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
1832
    ///
1833
    /// // Compile our original DFA.
1834
    /// let original_dfa = DFA::new("foo[0-9]+")?;
1835
    ///
1836
    /// // N.B. We use native endianness here to make the example work, but
1837
    /// // using to_bytes_big_endian would work on a big endian target.
1838
    /// let (buf, _) = original_dfa.to_bytes_native_endian();
1839
    /// // Even if buf has initial padding, DFA::from_bytes will automatically
1840
    /// // ignore it.
1841
    /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf)?.0;
1842
    ///
1843
    /// let expected = Some(HalfMatch::must(0, 8));
1844
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
1845
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1846
    /// ```
1847
    #[cfg(feature = "dfa-build")]
1848
    pub fn to_bytes_big_endian(&self) -> (Vec<u8>, usize) {
1849
        self.to_bytes::<wire::BE>()
1850
    }
1851
1852
    /// Serialize this DFA as raw bytes to a `Vec<u8>` in native endian
1853
    /// format. Upon success, the `Vec<u8>` and the initial padding length are
1854
    /// returned.
1855
    ///
1856
    /// The written bytes are guaranteed to be deserialized correctly and
1857
    /// without errors in a semver compatible release of this crate by a
1858
    /// `DFA`'s deserialization APIs (assuming all other criteria for the
1859
    /// deserialization APIs has been satisfied):
1860
    ///
1861
    /// * [`DFA::from_bytes`]
1862
    /// * [`DFA::from_bytes_unchecked`]
1863
    ///
1864
    /// The padding returned is non-zero if the returned `Vec<u8>` starts at
1865
    /// an address that does not have the same alignment as `u32`. The padding
1866
    /// corresponds to the number of leading bytes written to the returned
1867
    /// `Vec<u8>`.
1868
    ///
1869
    /// Generally speaking, native endian format should only be used when
1870
    /// you know that the target you're compiling the DFA for matches the
1871
    /// endianness of the target on which you're compiling DFA. For example,
1872
    /// if serialization and deserialization happen in the same process or on
1873
    /// the same machine. Otherwise, when serializing a DFA for use in a
1874
    /// portable environment, you'll almost certainly want to serialize _both_
1875
    /// a little endian and a big endian version and then load the correct one
1876
    /// based on the target's configuration.
1877
    ///
1878
    /// # Example
1879
    ///
1880
    /// This example shows how to serialize and deserialize a DFA:
1881
    ///
1882
    /// ```
1883
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
1884
    ///
1885
    /// // Compile our original DFA.
1886
    /// let original_dfa = DFA::new("foo[0-9]+")?;
1887
    ///
1888
    /// let (buf, _) = original_dfa.to_bytes_native_endian();
1889
    /// // Even if buf has initial padding, DFA::from_bytes will automatically
1890
    /// // ignore it.
1891
    /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf)?.0;
1892
    ///
1893
    /// let expected = Some(HalfMatch::must(0, 8));
1894
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
1895
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1896
    /// ```
1897
    #[cfg(feature = "dfa-build")]
1898
    pub fn to_bytes_native_endian(&self) -> (Vec<u8>, usize) {
1899
        self.to_bytes::<wire::NE>()
1900
    }
1901
1902
    /// The implementation of the public `to_bytes` serialization methods,
1903
    /// which is generic over endianness.
1904
    #[cfg(feature = "dfa-build")]
1905
    fn to_bytes<E: Endian>(&self) -> (Vec<u8>, usize) {
1906
        let len = self.write_to_len();
1907
        let (mut buf, padding) = wire::alloc_aligned_buffer::<u32>(len);
1908
        // This should always succeed since the only possible serialization
1909
        // error is providing a buffer that's too small, but we've ensured that
1910
        // `buf` is big enough here.
1911
        self.as_ref().write_to::<E>(&mut buf[padding..]).unwrap();
1912
        (buf, padding)
1913
    }
1914
1915
    /// Serialize this DFA as raw bytes to the given slice, in little endian
1916
    /// format. Upon success, the total number of bytes written to `dst` is
1917
    /// returned.
1918
    ///
1919
    /// The written bytes are guaranteed to be deserialized correctly and
1920
    /// without errors in a semver compatible release of this crate by a
1921
    /// `DFA`'s deserialization APIs (assuming all other criteria for the
1922
    /// deserialization APIs has been satisfied):
1923
    ///
1924
    /// * [`DFA::from_bytes`]
1925
    /// * [`DFA::from_bytes_unchecked`]
1926
    ///
1927
    /// Note that unlike the various `to_byte_*` routines, this does not write
1928
    /// any padding. Callers are responsible for handling alignment correctly.
1929
    ///
1930
    /// # Errors
1931
    ///
1932
    /// This returns an error if the given destination slice is not big enough
1933
    /// to contain the full serialized DFA. If an error occurs, then nothing
1934
    /// is written to `dst`.
1935
    ///
1936
    /// # Example
1937
    ///
1938
    /// This example shows how to serialize and deserialize a DFA without
1939
    /// dynamic memory allocation.
1940
    ///
1941
    /// ```
1942
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
1943
    ///
1944
    /// // Compile our original DFA.
1945
    /// let original_dfa = DFA::new("foo[0-9]+")?;
1946
    ///
1947
    /// // Create a 4KB buffer on the stack to store our serialized DFA. We
1948
    /// // need to use a special type to force the alignment of our [u8; N]
1949
    /// // array to be aligned to a 4 byte boundary. Otherwise, deserializing
1950
    /// // the DFA may fail because of an alignment mismatch.
1951
    /// #[repr(C)]
1952
    /// struct Aligned<B: ?Sized> {
1953
    ///     _align: [u32; 0],
1954
    ///     bytes: B,
1955
    /// }
1956
    /// let mut buf = Aligned { _align: [], bytes: [0u8; 4 * (1<<10)] };
1957
    /// // N.B. We use native endianness here to make the example work, but
1958
    /// // using write_to_little_endian would work on a little endian target.
1959
    /// let written = original_dfa.write_to_native_endian(&mut buf.bytes)?;
1960
    /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf.bytes[..written])?.0;
1961
    ///
1962
    /// let expected = Some(HalfMatch::must(0, 8));
1963
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
1964
    /// # Ok::<(), Box<dyn std::error::Error>>(())
1965
    /// ```
1966
    pub fn write_to_little_endian(
1967
        &self,
1968
        dst: &mut [u8],
1969
    ) -> Result<usize, SerializeError> {
1970
        self.as_ref().write_to::<wire::LE>(dst)
1971
    }
1972
1973
    /// Serialize this DFA as raw bytes to the given slice, in big endian
1974
    /// format. Upon success, the total number of bytes written to `dst` is
1975
    /// returned.
1976
    ///
1977
    /// The written bytes are guaranteed to be deserialized correctly and
1978
    /// without errors in a semver compatible release of this crate by a
1979
    /// `DFA`'s deserialization APIs (assuming all other criteria for the
1980
    /// deserialization APIs has been satisfied):
1981
    ///
1982
    /// * [`DFA::from_bytes`]
1983
    /// * [`DFA::from_bytes_unchecked`]
1984
    ///
1985
    /// Note that unlike the various `to_byte_*` routines, this does not write
1986
    /// any padding. Callers are responsible for handling alignment correctly.
1987
    ///
1988
    /// # Errors
1989
    ///
1990
    /// This returns an error if the given destination slice is not big enough
1991
    /// to contain the full serialized DFA. If an error occurs, then nothing
1992
    /// is written to `dst`.
1993
    ///
1994
    /// # Example
1995
    ///
1996
    /// This example shows how to serialize and deserialize a DFA without
1997
    /// dynamic memory allocation.
1998
    ///
1999
    /// ```
2000
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
2001
    ///
2002
    /// // Compile our original DFA.
2003
    /// let original_dfa = DFA::new("foo[0-9]+")?;
2004
    ///
2005
    /// // Create a 4KB buffer on the stack to store our serialized DFA. We
2006
    /// // need to use a special type to force the alignment of our [u8; N]
2007
    /// // array to be aligned to a 4 byte boundary. Otherwise, deserializing
2008
    /// // the DFA may fail because of an alignment mismatch.
2009
    /// #[repr(C)]
2010
    /// struct Aligned<B: ?Sized> {
2011
    ///     _align: [u32; 0],
2012
    ///     bytes: B,
2013
    /// }
2014
    /// let mut buf = Aligned { _align: [], bytes: [0u8; 4 * (1<<10)] };
2015
    /// // N.B. We use native endianness here to make the example work, but
2016
    /// // using write_to_big_endian would work on a big endian target.
2017
    /// let written = original_dfa.write_to_native_endian(&mut buf.bytes)?;
2018
    /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf.bytes[..written])?.0;
2019
    ///
2020
    /// let expected = Some(HalfMatch::must(0, 8));
2021
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
2022
    /// # Ok::<(), Box<dyn std::error::Error>>(())
2023
    /// ```
2024
    pub fn write_to_big_endian(
2025
        &self,
2026
        dst: &mut [u8],
2027
    ) -> Result<usize, SerializeError> {
2028
        self.as_ref().write_to::<wire::BE>(dst)
2029
    }
2030
2031
    /// Serialize this DFA as raw bytes to the given slice, in native endian
2032
    /// format. Upon success, the total number of bytes written to `dst` is
2033
    /// returned.
2034
    ///
2035
    /// The written bytes are guaranteed to be deserialized correctly and
2036
    /// without errors in a semver compatible release of this crate by a
2037
    /// `DFA`'s deserialization APIs (assuming all other criteria for the
2038
    /// deserialization APIs has been satisfied):
2039
    ///
2040
    /// * [`DFA::from_bytes`]
2041
    /// * [`DFA::from_bytes_unchecked`]
2042
    ///
2043
    /// Generally speaking, native endian format should only be used when
2044
    /// you know that the target you're compiling the DFA for matches the
2045
    /// endianness of the target on which you're compiling DFA. For example,
2046
    /// if serialization and deserialization happen in the same process or on
2047
    /// the same machine. Otherwise, when serializing a DFA for use in a
2048
    /// portable environment, you'll almost certainly want to serialize _both_
2049
    /// a little endian and a big endian version and then load the correct one
2050
    /// based on the target's configuration.
2051
    ///
2052
    /// Note that unlike the various `to_byte_*` routines, this does not write
2053
    /// any padding. Callers are responsible for handling alignment correctly.
2054
    ///
2055
    /// # Errors
2056
    ///
2057
    /// This returns an error if the given destination slice is not big enough
2058
    /// to contain the full serialized DFA. If an error occurs, then nothing
2059
    /// is written to `dst`.
2060
    ///
2061
    /// # Example
2062
    ///
2063
    /// This example shows how to serialize and deserialize a DFA without
2064
    /// dynamic memory allocation.
2065
    ///
2066
    /// ```
2067
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
2068
    ///
2069
    /// // Compile our original DFA.
2070
    /// let original_dfa = DFA::new("foo[0-9]+")?;
2071
    ///
2072
    /// // Create a 4KB buffer on the stack to store our serialized DFA. We
2073
    /// // need to use a special type to force the alignment of our [u8; N]
2074
    /// // array to be aligned to a 4 byte boundary. Otherwise, deserializing
2075
    /// // the DFA may fail because of an alignment mismatch.
2076
    /// #[repr(C)]
2077
    /// struct Aligned<B: ?Sized> {
2078
    ///     _align: [u32; 0],
2079
    ///     bytes: B,
2080
    /// }
2081
    /// let mut buf = Aligned { _align: [], bytes: [0u8; 4 * (1<<10)] };
2082
    /// let written = original_dfa.write_to_native_endian(&mut buf.bytes)?;
2083
    /// let dfa: DFA<&[u32]> = DFA::from_bytes(&buf.bytes[..written])?.0;
2084
    ///
2085
    /// let expected = Some(HalfMatch::must(0, 8));
2086
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
2087
    /// # Ok::<(), Box<dyn std::error::Error>>(())
2088
    /// ```
2089
    pub fn write_to_native_endian(
2090
        &self,
2091
        dst: &mut [u8],
2092
    ) -> Result<usize, SerializeError> {
2093
        self.as_ref().write_to::<wire::NE>(dst)
2094
    }
2095
2096
    /// Return the total number of bytes required to serialize this DFA.
2097
    ///
2098
    /// This is useful for determining the size of the buffer required to pass
2099
    /// to one of the serialization routines:
2100
    ///
2101
    /// * [`DFA::write_to_little_endian`]
2102
    /// * [`DFA::write_to_big_endian`]
2103
    /// * [`DFA::write_to_native_endian`]
2104
    ///
2105
    /// Passing a buffer smaller than the size returned by this method will
2106
    /// result in a serialization error. Serialization routines are guaranteed
2107
    /// to succeed when the buffer is big enough.
2108
    ///
2109
    /// # Example
2110
    ///
2111
    /// This example shows how to dynamically allocate enough room to serialize
2112
    /// a DFA.
2113
    ///
2114
    /// ```
2115
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
2116
    ///
2117
    /// let original_dfa = DFA::new("foo[0-9]+")?;
2118
    ///
2119
    /// let mut buf = vec![0; original_dfa.write_to_len()];
2120
    /// // This is guaranteed to succeed, because the only serialization error
2121
    /// // that can occur is when the provided buffer is too small. But
2122
    /// // write_to_len guarantees a correct size.
2123
    /// let written = original_dfa.write_to_native_endian(&mut buf).unwrap();
2124
    /// // But this is not guaranteed to succeed! In particular,
2125
    /// // deserialization requires proper alignment for &[u32], but our buffer
2126
    /// // was allocated as a &[u8] whose required alignment is smaller than
2127
    /// // &[u32]. However, it's likely to work in practice because of how most
2128
    /// // allocators work. So if you write code like this, make sure to either
2129
    /// // handle the error correctly and/or run it under Miri since Miri will
2130
    /// // likely provoke the error by returning Vec<u8> buffers with alignment
2131
    /// // less than &[u32].
2132
    /// let dfa: DFA<&[u32]> = match DFA::from_bytes(&buf[..written]) {
2133
    ///     // As mentioned above, it is legal for an error to be returned
2134
    ///     // here. It is quite difficult to get a Vec<u8> with a guaranteed
2135
    ///     // alignment equivalent to Vec<u32>.
2136
    ///     Err(_) => return Ok(()),
2137
    ///     Ok((dfa, _)) => dfa,
2138
    /// };
2139
    ///
2140
    /// let expected = Some(HalfMatch::must(0, 8));
2141
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
2142
    /// # Ok::<(), Box<dyn std::error::Error>>(())
2143
    /// ```
2144
    ///
2145
    /// Note that this example isn't actually guaranteed to work! In
2146
    /// particular, if `buf` is not aligned to a 4-byte boundary, then the
2147
    /// `DFA::from_bytes` call will fail. If you need this to work, then you
2148
    /// either need to deal with adding some initial padding yourself, or use
2149
    /// one of the `to_bytes` methods, which will do it for you.
2150
    pub fn write_to_len(&self) -> usize {
2151
        wire::write_label_len(LABEL)
2152
        + wire::write_endianness_check_len()
2153
        + wire::write_version_len()
2154
        + size_of::<u32>() // unused, intended for future flexibility
2155
        + self.flags.write_to_len()
2156
        + self.tt.write_to_len()
2157
        + self.st.write_to_len()
2158
        + self.ms.write_to_len()
2159
        + self.special.write_to_len()
2160
        + self.accels.write_to_len()
2161
        + self.quitset.write_to_len()
2162
    }
2163
}
2164
2165
impl<'a> DFA<&'a [u32]> {
2166
    /// Safely deserialize a DFA with a specific state identifier
2167
    /// representation. Upon success, this returns both the deserialized DFA
2168
    /// and the number of bytes read from the given slice. Namely, the contents
2169
    /// of the slice beyond the DFA are not read.
2170
    ///
2171
    /// Deserializing a DFA using this routine will never allocate heap memory.
2172
    /// For safety purposes, the DFA's transition table will be verified such
2173
    /// that every transition points to a valid state. If this verification is
2174
    /// too costly, then a [`DFA::from_bytes_unchecked`] API is provided, which
2175
    /// will always execute in constant time.
2176
    ///
2177
    /// The bytes given must be generated by one of the serialization APIs
2178
    /// of a `DFA` using a semver compatible release of this crate. Those
2179
    /// include:
2180
    ///
2181
    /// * [`DFA::to_bytes_little_endian`]
2182
    /// * [`DFA::to_bytes_big_endian`]
2183
    /// * [`DFA::to_bytes_native_endian`]
2184
    /// * [`DFA::write_to_little_endian`]
2185
    /// * [`DFA::write_to_big_endian`]
2186
    /// * [`DFA::write_to_native_endian`]
2187
    ///
2188
    /// The `to_bytes` methods allocate and return a `Vec<u8>` for you, along
2189
    /// with handling alignment correctly. The `write_to` methods do not
2190
    /// allocate and write to an existing slice (which may be on the stack).
2191
    /// Since deserialization always uses the native endianness of the target
2192
    /// platform, the serialization API you use should match the endianness of
2193
    /// the target platform. (It's often a good idea to generate serialized
2194
    /// DFAs for both forms of endianness and then load the correct one based
2195
    /// on endianness.)
2196
    ///
2197
    /// # Errors
2198
    ///
2199
    /// Generally speaking, it's easier to state the conditions in which an
2200
    /// error is _not_ returned. All of the following must be true:
2201
    ///
2202
    /// * The bytes given must be produced by one of the serialization APIs
2203
    ///   on this DFA, as mentioned above.
2204
    /// * The endianness of the target platform matches the endianness used to
2205
    ///   serialized the provided DFA.
2206
    /// * The slice given must have the same alignment as `u32`.
2207
    ///
2208
    /// If any of the above are not true, then an error will be returned.
2209
    ///
2210
    /// # Panics
2211
    ///
2212
    /// This routine will never panic for any input.
2213
    ///
2214
    /// # Example
2215
    ///
2216
    /// This example shows how to serialize a DFA to raw bytes, deserialize it
2217
    /// and then use it for searching.
2218
    ///
2219
    /// ```
2220
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
2221
    ///
2222
    /// let initial = DFA::new("foo[0-9]+")?;
2223
    /// let (bytes, _) = initial.to_bytes_native_endian();
2224
    /// let dfa: DFA<&[u32]> = DFA::from_bytes(&bytes)?.0;
2225
    ///
2226
    /// let expected = Some(HalfMatch::must(0, 8));
2227
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
2228
    /// # Ok::<(), Box<dyn std::error::Error>>(())
2229
    /// ```
2230
    ///
2231
    /// # Example: dealing with alignment and padding
2232
    ///
2233
    /// In the above example, we used the `to_bytes_native_endian` method to
2234
    /// serialize a DFA, but we ignored part of its return value corresponding
2235
    /// to padding added to the beginning of the serialized DFA. This is OK
2236
    /// because deserialization will skip this initial padding. What matters
2237
    /// is that the address immediately following the padding has an alignment
2238
    /// that matches `u32`. That is, the following is an equivalent but
2239
    /// alternative way to write the above example:
2240
    ///
2241
    /// ```
2242
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
2243
    ///
2244
    /// let initial = DFA::new("foo[0-9]+")?;
2245
    /// // Serialization returns the number of leading padding bytes added to
2246
    /// // the returned Vec<u8>.
2247
    /// let (bytes, pad) = initial.to_bytes_native_endian();
2248
    /// let dfa: DFA<&[u32]> = DFA::from_bytes(&bytes[pad..])?.0;
2249
    ///
2250
    /// let expected = Some(HalfMatch::must(0, 8));
2251
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
2252
    /// # Ok::<(), Box<dyn std::error::Error>>(())
2253
    /// ```
2254
    ///
2255
    /// This padding is necessary because Rust's standard library does
2256
    /// not expose any safe and robust way of creating a `Vec<u8>` with a
2257
    /// guaranteed alignment other than 1. Now, in practice, the underlying
2258
    /// allocator is likely to provide a `Vec<u8>` that meets our alignment
2259
    /// requirements, which means `pad` is zero in practice most of the time.
2260
    ///
2261
    /// The purpose of exposing the padding like this is flexibility for the
2262
    /// caller. For example, if one wants to embed a serialized DFA into a
2263
    /// compiled program, then it's important to guarantee that it starts at a
2264
    /// `u32`-aligned address. The simplest way to do this is to discard the
2265
    /// padding bytes and set it up so that the serialized DFA itself begins at
2266
    /// a properly aligned address. We can show this in two parts. The first
2267
    /// part is serializing the DFA to a file:
2268
    ///
2269
    /// ```no_run
2270
    /// use regex_automata::dfa::dense::DFA;
2271
    ///
2272
    /// let dfa = DFA::new("foo[0-9]+")?;
2273
    ///
2274
    /// let (bytes, pad) = dfa.to_bytes_big_endian();
2275
    /// // Write the contents of the DFA *without* the initial padding.
2276
    /// std::fs::write("foo.bigendian.dfa", &bytes[pad..])?;
2277
    ///
2278
    /// // Do it again, but this time for little endian.
2279
    /// let (bytes, pad) = dfa.to_bytes_little_endian();
2280
    /// std::fs::write("foo.littleendian.dfa", &bytes[pad..])?;
2281
    /// # Ok::<(), Box<dyn std::error::Error>>(())
2282
    /// ```
2283
    ///
2284
    /// And now the second part is embedding the DFA into the compiled program
2285
    /// and deserializing it at runtime on first use. We use conditional
2286
    /// compilation to choose the correct endianness.
2287
    ///
2288
    /// ```no_run
2289
    /// use regex_automata::{
2290
    ///     dfa::{Automaton, dense::DFA},
2291
    ///     util::{lazy::Lazy, wire::AlignAs},
2292
    ///     HalfMatch, Input,
2293
    /// };
2294
    ///
2295
    /// // This crate provides its own "lazy" type, kind of like
2296
    /// // lazy_static! or once_cell::sync::Lazy. But it works in no-alloc
2297
    /// // no-std environments and let's us write this using completely
2298
    /// // safe code.
2299
    /// static RE: Lazy<DFA<&'static [u32]>> = Lazy::new(|| {
2300
    ///     # const _: &str = stringify! {
2301
    ///     // This assignment is made possible (implicitly) via the
2302
    ///     // CoerceUnsized trait. This is what guarantees that our
2303
    ///     // bytes are stored in memory on a 4 byte boundary. You
2304
    ///     // *must* do this or something equivalent for correct
2305
    ///     // deserialization.
2306
    ///     static ALIGNED: &AlignAs<[u8], u32> = &AlignAs {
2307
    ///         _align: [],
2308
    ///         #[cfg(target_endian = "big")]
2309
    ///         bytes: *include_bytes!("foo.bigendian.dfa"),
2310
    ///         #[cfg(target_endian = "little")]
2311
    ///         bytes: *include_bytes!("foo.littleendian.dfa"),
2312
    ///     };
2313
    ///     # };
2314
    ///     # static ALIGNED: &AlignAs<[u8], u32> = &AlignAs {
2315
    ///     #     _align: [],
2316
    ///     #     bytes: [],
2317
    ///     # };
2318
    ///
2319
    ///     let (dfa, _) = DFA::from_bytes(&ALIGNED.bytes)
2320
    ///         .expect("serialized DFA should be valid");
2321
    ///     dfa
2322
    /// });
2323
    ///
2324
    /// let expected = Ok(Some(HalfMatch::must(0, 8)));
2325
    /// assert_eq!(expected, RE.try_search_fwd(&Input::new("foo12345")));
2326
    /// ```
2327
    ///
2328
    /// An alternative to [`util::lazy::Lazy`](crate::util::lazy::Lazy)
2329
    /// is [`lazy_static`](https://crates.io/crates/lazy_static) or
2330
    /// [`once_cell`](https://crates.io/crates/once_cell), which provide
2331
    /// stronger guarantees (like the initialization function only being
2332
    /// executed once). And `once_cell` in particular provides a more
2333
    /// expressive API. But a `Lazy` value from this crate is likely just fine
2334
    /// in most circumstances.
2335
    ///
2336
    /// Note that regardless of which initialization method you use, you
2337
    /// will still need to use the [`AlignAs`](crate::util::wire::AlignAs)
2338
    /// trick above to force correct alignment, but this is safe to do and
2339
    /// `from_bytes` will return an error if you get it wrong.
2340
3.63k
    pub fn from_bytes(
2341
3.63k
        slice: &'a [u8],
2342
3.63k
    ) -> Result<(DFA<&'a [u32]>, usize), DeserializeError> {
2343
        // SAFETY: This is safe because we validate the transition table, start
2344
        // table, match states and accelerators below. If any validation fails,
2345
        // then we return an error.
2346
3.63k
        let (dfa, nread) = unsafe { DFA::from_bytes_unchecked(slice)? };
2347
        // Note that validation order is important here:
2348
        //
2349
        // * `MatchState::validate` can be called with an untrusted DFA.
2350
        // * `TransistionTable::validate` uses `dfa.ms` through `match_len`.
2351
        // * `StartTable::validate` needs a valid transition table.
2352
        //
2353
        // So... validate the match states first.
2354
2.29k
        dfa.accels.validate()?;
2355
2.27k
        dfa.ms.validate(&dfa)?;
2356
2.21k
        dfa.tt.validate(&dfa)?;
2357
2.18k
        dfa.st.validate(&dfa)?;
2358
        // N.B. dfa.special doesn't have a way to do unchecked deserialization,
2359
        // so it has already been validated.
2360
745k
        for state in dfa.states() {
2361
            // If the state is an accel state, then it must have a non-empty
2362
            // accelerator.
2363
745k
            if dfa.is_accel_state(state.id()) {
2364
1.97k
                let index = dfa.accelerator_index(state.id());
2365
1.97k
                if index >= dfa.accels.len() {
2366
8
                    return Err(DeserializeError::generic(
2367
8
                        "found DFA state with invalid accelerator index",
2368
8
                    ));
2369
1.96k
                }
2370
1.96k
                let needles = dfa.accels.needles(index);
2371
1.96k
                if !(1 <= needles.len() && needles.len() <= 3) {
2372
2
                    return Err(DeserializeError::generic(
2373
2
                        "accelerator needles has invalid length",
2374
2
                    ));
2375
1.96k
                }
2376
743k
            }
2377
        }
2378
2.10k
        Ok((dfa, nread))
2379
3.63k
    }
2380
2381
    /// Deserialize a DFA with a specific state identifier representation in
2382
    /// constant time by omitting the verification of the validity of the
2383
    /// transition table and other data inside the DFA.
2384
    ///
2385
    /// This is just like [`DFA::from_bytes`], except it can potentially return
2386
    /// a DFA that exhibits undefined behavior if its transition table contains
2387
    /// invalid state identifiers.
2388
    ///
2389
    /// This routine is useful if you need to deserialize a DFA cheaply
2390
    /// and cannot afford the transition table validation performed by
2391
    /// `from_bytes`.
2392
    ///
2393
    /// # Example
2394
    ///
2395
    /// ```
2396
    /// use regex_automata::{dfa::{Automaton, dense::DFA}, HalfMatch, Input};
2397
    ///
2398
    /// let initial = DFA::new("foo[0-9]+")?;
2399
    /// let (bytes, _) = initial.to_bytes_native_endian();
2400
    /// // SAFETY: This is guaranteed to be safe since the bytes given come
2401
    /// // directly from a compatible serialization routine.
2402
    /// let dfa: DFA<&[u32]> = unsafe { DFA::from_bytes_unchecked(&bytes)?.0 };
2403
    ///
2404
    /// let expected = Some(HalfMatch::must(0, 8));
2405
    /// assert_eq!(expected, dfa.try_search_fwd(&Input::new("foo12345"))?);
2406
    /// # Ok::<(), Box<dyn std::error::Error>>(())
2407
    /// ```
2408
3.63k
    pub unsafe fn from_bytes_unchecked(
2409
3.63k
        slice: &'a [u8],
2410
3.63k
    ) -> Result<(DFA<&'a [u32]>, usize), DeserializeError> {
2411
3.63k
        let mut nr = 0;
2412
2413
3.63k
        nr += wire::skip_initial_padding(slice);
2414
3.63k
        wire::check_alignment::<StateID>(&slice[nr..])?;
2415
3.63k
        nr += wire::read_label(&slice[nr..], LABEL)?;
2416
3.63k
        nr += wire::read_endianness_check(&slice[nr..])?;
2417
3.63k
        nr += wire::read_version(&slice[nr..], VERSION)?;
2418
2419
3.63k
        let _unused = wire::try_read_u32(&slice[nr..], "unused space")?;
2420
3.61k
        nr += size_of::<u32>();
2421
2422
3.61k
        let (flags, nread) = Flags::from_bytes(&slice[nr..])?;
2423
3.60k
        nr += nread;
2424
2425
3.60k
        let (tt, nread) = TransitionTable::from_bytes_unchecked(&slice[nr..])?;
2426
3.37k
        nr += nread;
2427
2428
3.37k
        let (st, nread) = StartTable::from_bytes_unchecked(&slice[nr..])?;
2429
2.99k
        nr += nread;
2430
2431
2.99k
        let (ms, nread) = MatchStates::from_bytes_unchecked(&slice[nr..])?;
2432
2.89k
        nr += nread;
2433
2434
2.89k
        let (special, nread) = Special::from_bytes(&slice[nr..])?;
2435
2.48k
        nr += nread;
2436
2.48k
        special.validate_state_len(tt.len(), tt.stride2)?;
2437
2438
2.35k
        let (accels, nread) = Accels::from_bytes_unchecked(&slice[nr..])?;
2439
2.33k
        nr += nread;
2440
2441
2.33k
        let (quitset, nread) = ByteSet::from_bytes(&slice[nr..])?;
2442
2.29k
        nr += nread;
2443
2444
        // Prefilters don't support serialization, so they're always absent.
2445
2.29k
        let pre = None;
2446
2.29k
        Ok((DFA { tt, st, ms, special, accels, pre, quitset, flags }, nr))
2447
3.63k
    }
2448
2449
    /// The implementation of the public `write_to` serialization methods,
2450
    /// which is generic over endianness.
2451
    ///
2452
    /// This is defined only for &[u32] to reduce binary size/compilation time.
2453
    fn write_to<E: Endian>(
2454
        &self,
2455
        mut dst: &mut [u8],
2456
    ) -> Result<usize, SerializeError> {
2457
        let nwrite = self.write_to_len();
2458
        if dst.len() < nwrite {
2459
            return Err(SerializeError::buffer_too_small("dense DFA"));
2460
        }
2461
        dst = &mut dst[..nwrite];
2462
2463
        let mut nw = 0;
2464
        nw += wire::write_label(LABEL, &mut dst[nw..])?;
2465
        nw += wire::write_endianness_check::<E>(&mut dst[nw..])?;
2466
        nw += wire::write_version::<E>(VERSION, &mut dst[nw..])?;
2467
        nw += {
2468
            // Currently unused, intended for future flexibility
2469
            E::write_u32(0, &mut dst[nw..]);
2470
            size_of::<u32>()
2471
        };
2472
        nw += self.flags.write_to::<E>(&mut dst[nw..])?;
2473
        nw += self.tt.write_to::<E>(&mut dst[nw..])?;
2474
        nw += self.st.write_to::<E>(&mut dst[nw..])?;
2475
        nw += self.ms.write_to::<E>(&mut dst[nw..])?;
2476
        nw += self.special.write_to::<E>(&mut dst[nw..])?;
2477
        nw += self.accels.write_to::<E>(&mut dst[nw..])?;
2478
        nw += self.quitset.write_to::<E>(&mut dst[nw..])?;
2479
        Ok(nw)
2480
    }
2481
}
2482
2483
/// Other routines that work for all `T`.
2484
impl<T> DFA<T> {
2485
    /// Set or unset the prefilter attached to this DFA.
2486
    ///
2487
    /// This is useful when one has deserialized a DFA from `&[u8]`.
2488
    /// Deserialization does not currently include prefilters, so if you
2489
    /// want prefilter acceleration, you'll need to rebuild it and attach
2490
    /// it here.
2491
    pub fn set_prefilter(&mut self, prefilter: Option<Prefilter>) {
2492
        self.pre = prefilter
2493
    }
2494
}
2495
2496
// The following methods implement mutable routines on the internal
2497
// representation of a DFA. As such, we must fix the first type parameter to a
2498
// `Vec<u32>` since a generic `T: AsRef<[u32]>` does not permit mutation. We
2499
// can get away with this because these methods are internal to the crate and
2500
// are exclusively used during construction of the DFA.
2501
#[cfg(feature = "dfa-build")]
2502
impl OwnedDFA {
2503
    /// Add a start state of this DFA.
2504
1.20M
    pub(crate) fn set_start_state(
2505
1.20M
        &mut self,
2506
1.20M
        anchored: Anchored,
2507
1.20M
        start: Start,
2508
1.20M
        id: StateID,
2509
1.20M
    ) {
2510
1.20M
        assert!(self.tt.is_valid(id), "invalid start state");
2511
1.20M
        self.st.set_start(anchored, start, id);
2512
1.20M
    }
2513
2514
    /// Set the given transition to this DFA. Both the `from` and `to` states
2515
    /// must already exist.
2516
38.6M
    pub(crate) fn set_transition(
2517
38.6M
        &mut self,
2518
38.6M
        from: StateID,
2519
38.6M
        byte: alphabet::Unit,
2520
38.6M
        to: StateID,
2521
38.6M
    ) {
2522
38.6M
        self.tt.set(from, byte, to);
2523
38.6M
    }
2524
2525
    /// An empty state (a state where all transitions lead to a dead state)
2526
    /// and return its identifier. The identifier returned is guaranteed to
2527
    /// not point to any other existing state.
2528
    ///
2529
    /// If adding a state would exceed `StateID::LIMIT`, then this returns an
2530
    /// error.
2531
852k
    pub(crate) fn add_empty_state(&mut self) -> Result<StateID, BuildError> {
2532
852k
        self.tt.add_empty_state()
2533
852k
    }
2534
2535
    /// Swap the two states given in the transition table.
2536
    ///
2537
    /// This routine does not do anything to check the correctness of this
2538
    /// swap. Callers must ensure that other states pointing to id1 and id2 are
2539
    /// updated appropriately.
2540
169k
    pub(crate) fn swap_states(&mut self, id1: StateID, id2: StateID) {
2541
169k
        self.tt.swap(id1, id2);
2542
169k
    }
2543
2544
    /// Remap all of the state identifiers in this DFA according to the map
2545
    /// function given. This includes all transitions and all starting state
2546
    /// identifiers.
2547
87.5k
    pub(crate) fn remap(&mut self, map: impl Fn(StateID) -> StateID) {
2548
        // We could loop over each state ID and call 'remap_state' here, but
2549
        // this is more direct: just map every transition directly. This
2550
        // technically might do a little extra work since the alphabet length
2551
        // is likely less than the stride, but if that is indeed an issue we
2552
        // should benchmark it and fix it.
2553
27.3M
        for sid in self.tt.table_mut().iter_mut() {
2554
27.3M
            *sid = map(*sid);
2555
27.3M
        }
2556
1.55M
        for sid in self.st.table_mut().iter_mut() {
2557
1.55M
            *sid = map(*sid);
2558
1.55M
        }
2559
87.5k
    }
2560
2561
    /// Remap the transitions for the state given according to the function
2562
    /// given. This applies the given map function to every transition in the
2563
    /// given state and changes the transition in place to the result of the
2564
    /// map function for that transition.
2565
0
    pub(crate) fn remap_state(
2566
0
        &mut self,
2567
0
        id: StateID,
2568
0
        map: impl Fn(StateID) -> StateID,
2569
0
    ) {
2570
0
        self.tt.remap(id, map);
2571
0
    }
2572
2573
    /// Truncate the states in this DFA to the given length.
2574
    ///
2575
    /// This routine does not do anything to check the correctness of this
2576
    /// truncation. Callers must ensure that other states pointing to truncated
2577
    /// states are updated appropriately.
2578
0
    pub(crate) fn truncate_states(&mut self, len: usize) {
2579
0
        self.tt.truncate(len);
2580
0
    }
2581
2582
    /// Minimize this DFA in place using Hopcroft's algorithm.
2583
0
    pub(crate) fn minimize(&mut self) {
2584
0
        Minimizer::new(self).run();
2585
0
    }
2586
2587
    /// Updates the match state pattern ID map to use the one provided.
2588
    ///
2589
    /// This is useful when it's convenient to manipulate matching states
2590
    /// (and their corresponding pattern IDs) as a map. In particular, the
2591
    /// representation used by a DFA for this map is not amenable to mutation,
2592
    /// so if things need to be changed (like when shuffling states), it's
2593
    /// often easier to work with the map form.
2594
87.5k
    pub(crate) fn set_pattern_map(
2595
87.5k
        &mut self,
2596
87.5k
        map: &BTreeMap<StateID, Vec<PatternID>>,
2597
87.5k
    ) -> Result<(), BuildError> {
2598
87.5k
        self.ms = self.ms.new_with_map(map)?;
2599
87.5k
        Ok(())
2600
87.5k
    }
2601
2602
    /// Find states that have a small number of non-loop transitions and mark
2603
    /// them as candidates for acceleration during search.
2604
77.3k
    pub(crate) fn accelerate(&mut self) {
2605
        // dead and quit states can never be accelerated.
2606
77.3k
        if self.state_len() <= 2 {
2607
0
            return;
2608
77.3k
        }
2609
2610
        // Go through every state and record their accelerator, if possible.
2611
77.3k
        let mut accels = BTreeMap::new();
2612
        // Count the number of accelerated match, start and non-match/start
2613
        // states.
2614
77.3k
        let (mut cmatch, mut cstart, mut cnormal) = (0, 0, 0);
2615
910k
        for state in self.states() {
2616
910k
            if let Some(accel) = state.accelerate(self.byte_classes()) {
2617
12.9k
                debug!(
2618
0
                    "accelerating full DFA state {}: {:?}",
2619
0
                    state.id().as_usize(),
2620
                    accel,
2621
                );
2622
12.9k
                accels.insert(state.id(), accel);
2623
12.9k
                if self.is_match_state(state.id()) {
2624
2.37k
                    cmatch += 1;
2625
10.5k
                } else if self.is_start_state(state.id()) {
2626
6.08k
                    cstart += 1;
2627
6.08k
                } else {
2628
4.44k
                    assert!(!self.is_dead_state(state.id()));
2629
4.44k
                    assert!(!self.is_quit_state(state.id()));
2630
4.44k
                    cnormal += 1;
2631
                }
2632
897k
            }
2633
        }
2634
        // If no states were able to be accelerated, then we're done.
2635
77.3k
        if accels.is_empty() {
2636
70.0k
            return;
2637
7.25k
        }
2638
7.25k
        let original_accels_len = accels.len();
2639
2640
        // A remapper keeps track of state ID changes. Once we're done
2641
        // shuffling, the remapper is used to rewrite all transitions in the
2642
        // DFA based on the new positions of states.
2643
7.25k
        let mut remapper = Remapper::new(self);
2644
2645
        // As we swap states, if they are match states, we need to swap their
2646
        // pattern ID lists too (for multi-regexes). We do this by converting
2647
        // the lists to an easily swappable map, and then convert back to
2648
        // MatchStates once we're done.
2649
7.25k
        let mut new_matches = self.ms.to_map(self);
2650
2651
        // There is at least one state that gets accelerated, so these are
2652
        // guaranteed to get set to sensible values below.
2653
7.25k
        self.special.min_accel = StateID::MAX;
2654
7.25k
        self.special.max_accel = StateID::ZERO;
2655
7.25k
        let update_special_accel =
2656
12.9k
            |special: &mut Special, accel_id: StateID| {
2657
12.9k
                special.min_accel = cmp::min(special.min_accel, accel_id);
2658
12.9k
                special.max_accel = cmp::max(special.max_accel, accel_id);
2659
12.9k
            };
2660
2661
        // Start by shuffling match states. Any match states that are
2662
        // accelerated get moved to the end of the match state range.
2663
7.25k
        if cmatch > 0 && self.special.matches() {
2664
            // N.B. special.{min,max}_match do not need updating, since the
2665
            // range/number of match states does not change. Only the ordering
2666
            // of match states may change.
2667
755
            let mut next_id = self.special.max_match;
2668
755
            let mut cur_id = next_id;
2669
11.3k
            while cur_id >= self.special.min_match {
2670
10.5k
                if let Some(accel) = accels.remove(&cur_id) {
2671
2.37k
                    accels.insert(next_id, accel);
2672
2.37k
                    update_special_accel(&mut self.special, next_id);
2673
2674
                    // No need to do any actual swapping for equivalent IDs.
2675
2.37k
                    if cur_id != next_id {
2676
2.26k
                        remapper.swap(self, cur_id, next_id);
2677
2.26k
2678
2.26k
                        // Swap pattern IDs for match states.
2679
2.26k
                        let cur_pids = new_matches.remove(&cur_id).unwrap();
2680
2.26k
                        let next_pids = new_matches.remove(&next_id).unwrap();
2681
2.26k
                        new_matches.insert(cur_id, next_pids);
2682
2.26k
                        new_matches.insert(next_id, cur_pids);
2683
2.26k
                    }
2684
2.37k
                    next_id = self.tt.prev_state_id(next_id);
2685
8.18k
                }
2686
10.5k
                cur_id = self.tt.prev_state_id(cur_id);
2687
            }
2688
6.49k
        }
2689
2690
        // This is where it gets tricky. Without acceleration, start states
2691
        // normally come right after match states. But we want accelerated
2692
        // states to be a single contiguous range (to make it very fast
2693
        // to determine whether a state *is* accelerated), while also keeping
2694
        // match and starting states as contiguous ranges for the same reason.
2695
        // So what we do here is shuffle states such that it looks like this:
2696
        //
2697
        //     DQMMMMAAAAASSSSSSNNNNNNN
2698
        //         |         |
2699
        //         |---------|
2700
        //      accelerated states
2701
        //
2702
        // Where:
2703
        //   D - dead state
2704
        //   Q - quit state
2705
        //   M - match state (may be accelerated)
2706
        //   A - normal state that is accelerated
2707
        //   S - start state (may be accelerated)
2708
        //   N - normal state that is NOT accelerated
2709
        //
2710
        // We implement this by shuffling states, which is done by a sequence
2711
        // of pairwise swaps. We start by looking at all normal states to be
2712
        // accelerated. When we find one, we swap it with the earliest starting
2713
        // state, and then swap that with the earliest normal state. This
2714
        // preserves the contiguous property.
2715
        //
2716
        // Once we're done looking for accelerated normal states, now we look
2717
        // for accelerated starting states by moving them to the beginning
2718
        // of the starting state range (just like we moved accelerated match
2719
        // states to the end of the matching state range).
2720
        //
2721
        // For a more detailed/different perspective on this, see the docs
2722
        // in dfa/special.rs.
2723
7.25k
        if cnormal > 0 {
2724
            // our next available starting and normal states for swapping.
2725
1.17k
            let mut next_start_id = self.special.min_start;
2726
1.17k
            let mut cur_id = self.to_state_id(self.state_len() - 1);
2727
            // This is guaranteed to exist since cnormal > 0.
2728
1.17k
            let mut next_norm_id =
2729
1.17k
                self.tt.next_state_id(self.special.max_start);
2730
27.4k
            while cur_id >= next_norm_id {
2731
26.2k
                if let Some(accel) = accels.remove(&cur_id) {
2732
4.44k
                    remapper.swap(self, next_start_id, cur_id);
2733
4.44k
                    remapper.swap(self, next_norm_id, cur_id);
2734
                    // Keep our accelerator map updated with new IDs if the
2735
                    // states we swapped were also accelerated.
2736
4.44k
                    if let Some(accel2) = accels.remove(&next_norm_id) {
2737
1.25k
                        accels.insert(cur_id, accel2);
2738
3.19k
                    }
2739
4.44k
                    if let Some(accel2) = accels.remove(&next_start_id) {
2740
929
                        accels.insert(next_norm_id, accel2);
2741
3.51k
                    }
2742
4.44k
                    accels.insert(next_start_id, accel);
2743
4.44k
                    update_special_accel(&mut self.special, next_start_id);
2744
                    // Our start range shifts one to the right now.
2745
4.44k
                    self.special.min_start =
2746
4.44k
                        self.tt.next_state_id(self.special.min_start);
2747
4.44k
                    self.special.max_start =
2748
4.44k
                        self.tt.next_state_id(self.special.max_start);
2749
4.44k
                    next_start_id = self.tt.next_state_id(next_start_id);
2750
4.44k
                    next_norm_id = self.tt.next_state_id(next_norm_id);
2751
21.8k
                }
2752
                // This is pretty tricky, but if our 'next_norm_id' state also
2753
                // happened to be accelerated, then the result is that it is
2754
                // now in the position of cur_id, so we need to consider it
2755
                // again. This loop is still guaranteed to terminate though,
2756
                // because when accels contains cur_id, we're guaranteed to
2757
                // increment next_norm_id even if cur_id remains unchanged.
2758
26.2k
                if !accels.contains_key(&cur_id) {
2759
25.0k
                    cur_id = self.tt.prev_state_id(cur_id);
2760
25.0k
                }
2761
            }
2762
6.08k
        }
2763
        // Just like we did for match states, but we want to move accelerated
2764
        // start states to the beginning of the range instead of the end.
2765
7.25k
        if cstart > 0 {
2766
            // N.B. special.{min,max}_start do not need updating, since the
2767
            // range/number of start states does not change at this point. Only
2768
            // the ordering of start states may change.
2769
6.08k
            let mut next_id = self.special.min_start;
2770
6.08k
            let mut cur_id = next_id;
2771
21.2k
            while cur_id <= self.special.max_start {
2772
15.1k
                if let Some(accel) = accels.remove(&cur_id) {
2773
6.08k
                    remapper.swap(self, cur_id, next_id);
2774
6.08k
                    accels.insert(next_id, accel);
2775
6.08k
                    update_special_accel(&mut self.special, next_id);
2776
6.08k
                    next_id = self.tt.next_state_id(next_id);
2777
9.05k
                }
2778
15.1k
                cur_id = self.tt.next_state_id(cur_id);
2779
            }
2780
1.16k
        }
2781
2782
        // Remap all transitions in our DFA and assert some things.
2783
7.25k
        remapper.remap(self);
2784
        // This unwrap is OK because acceleration never changes the number of
2785
        // match states or patterns in those match states. Since acceleration
2786
        // runs after the pattern map has been set at least once, we know that
2787
        // our match states cannot error.
2788
7.25k
        self.set_pattern_map(&new_matches).unwrap();
2789
7.25k
        self.special.set_max();
2790
7.25k
        self.special.validate().expect("special state ranges should validate");
2791
7.25k
        self.special
2792
7.25k
            .validate_state_len(self.state_len(), self.stride2())
2793
7.25k
            .expect(
2794
7.25k
                "special state ranges should be consistent with state length",
2795
            );
2796
7.25k
        assert_eq!(
2797
7.25k
            self.special.accel_len(self.stride()),
2798
            // We record the number of accelerated states initially detected
2799
            // since the accels map is itself mutated in the process above.
2800
            // If mutated incorrectly, its size may change, and thus can't be
2801
            // trusted as a source of truth of how many accelerated states we
2802
            // expected there to be.
2803
            original_accels_len,
2804
0
            "mismatch with expected number of accelerated states",
2805
        );
2806
2807
        // And finally record our accelerators. We kept our accels map updated
2808
        // as we shuffled states above, so the accelerators should now
2809
        // correspond to a contiguous range in the state ID space. (Which we
2810
        // assert.)
2811
7.25k
        let mut prev: Option<StateID> = None;
2812
20.1k
        for (id, accel) in accels {
2813
12.9k
            assert!(prev.map_or(true, |p| self.tt.next_state_id(p) == id));
2814
12.9k
            prev = Some(id);
2815
12.9k
            self.accels.add(accel);
2816
        }
2817
77.3k
    }
2818
2819
    /// Shuffle the states in this DFA so that starting states, match
2820
    /// states and accelerated states are all contiguous.
2821
    ///
2822
    /// See dfa/special.rs for more details.
2823
80.2k
    pub(crate) fn shuffle(
2824
80.2k
        &mut self,
2825
80.2k
        mut matches: BTreeMap<StateID, Vec<PatternID>>,
2826
80.2k
    ) -> Result<(), BuildError> {
2827
        // The determinizer always adds a quit state and it is always second.
2828
80.2k
        self.special.quit_id = self.to_state_id(1);
2829
        // If all we have are the dead and quit states, then we're done and
2830
        // the DFA will never produce a match.
2831
80.2k
        if self.state_len() <= 2 {
2832
0
            self.special.set_max();
2833
0
            return Ok(());
2834
80.2k
        }
2835
2836
        // Collect all our non-DEAD start states into a convenient set and
2837
        // confirm there is no overlap with match states. In the classical DFA
2838
        // construction, start states can be match states. But because of
2839
        // look-around, we delay all matches by a byte, which prevents start
2840
        // states from being match states.
2841
80.2k
        let mut is_start: BTreeSet<StateID> = BTreeSet::new();
2842
1.42M
        for (start_id, _, _) in self.starts() {
2843
            // If a starting configuration points to a DEAD state, then we
2844
            // don't want to shuffle it. The DEAD state is always the first
2845
            // state with ID=0. So we can just leave it be.
2846
1.42M
            if start_id == DEAD {
2847
249k
                continue;
2848
1.17M
            }
2849
1.17M
            assert!(
2850
1.17M
                !matches.contains_key(&start_id),
2851
0
                "{start_id:?} is both a start and a match state, \
2852
0
                 which is not allowed",
2853
            );
2854
1.17M
            is_start.insert(start_id);
2855
        }
2856
2857
        // We implement shuffling by a sequence of pairwise swaps of states.
2858
        // Since we have a number of things referencing states via their
2859
        // IDs and swapping them changes their IDs, we need to record every
2860
        // swap we make so that we can remap IDs. The remapper handles this
2861
        // book-keeping for us.
2862
80.2k
        let mut remapper = Remapper::new(self);
2863
2864
        // Shuffle matching states.
2865
80.2k
        if matches.is_empty() {
2866
20.6k
            self.special.min_match = DEAD;
2867
20.6k
            self.special.max_match = DEAD;
2868
20.6k
        } else {
2869
            // The determinizer guarantees that the first two states are the
2870
            // dead and quit states, respectively. We want our match states to
2871
            // come right after quit.
2872
59.6k
            let mut next_id = self.to_state_id(2);
2873
59.6k
            let mut new_matches = BTreeMap::new();
2874
59.6k
            self.special.min_match = next_id;
2875
169k
            for (id, pids) in matches {
2876
109k
                remapper.swap(self, next_id, id);
2877
109k
                new_matches.insert(next_id, pids);
2878
                // If we swapped a start state, then update our set.
2879
109k
                if is_start.contains(&next_id) {
2880
82.2k
                    is_start.remove(&next_id);
2881
82.2k
                    is_start.insert(id);
2882
82.2k
                }
2883
109k
                next_id = self.tt.next_state_id(next_id);
2884
            }
2885
59.6k
            matches = new_matches;
2886
59.6k
            self.special.max_match = cmp::max(
2887
59.6k
                self.special.min_match,
2888
59.6k
                self.tt.prev_state_id(next_id),
2889
59.6k
            );
2890
        }
2891
2892
        // Shuffle starting states.
2893
        {
2894
80.2k
            let mut next_id = self.to_state_id(2);
2895
80.2k
            if self.special.matches() {
2896
59.6k
                next_id = self.tt.next_state_id(self.special.max_match);
2897
59.6k
            }
2898
80.2k
            self.special.min_start = next_id;
2899
246k
            for id in is_start {
2900
166k
                remapper.swap(self, next_id, id);
2901
166k
                next_id = self.tt.next_state_id(next_id);
2902
166k
            }
2903
80.2k
            self.special.max_start = cmp::max(
2904
80.2k
                self.special.min_start,
2905
80.2k
                self.tt.prev_state_id(next_id),
2906
80.2k
            );
2907
        }
2908
2909
        // Finally remap all transitions in our DFA.
2910
80.2k
        remapper.remap(self);
2911
80.2k
        self.set_pattern_map(&matches)?;
2912
80.2k
        self.special.set_max();
2913
80.2k
        self.special.validate().expect("special state ranges should validate");
2914
80.2k
        self.special
2915
80.2k
            .validate_state_len(self.state_len(), self.stride2())
2916
80.2k
            .expect(
2917
80.2k
                "special state ranges should be consistent with state length",
2918
            );
2919
80.2k
        Ok(())
2920
80.2k
    }
2921
2922
    /// Checks whether there are universal start states (both anchored and
2923
    /// unanchored), and if so, sets the relevant fields to the start state
2924
    /// IDs.
2925
    ///
2926
    /// Universal start states occur precisely when the all patterns in the
2927
    /// DFA have no look-around assertions in their prefix.
2928
80.2k
    fn set_universal_starts(&mut self) {
2929
80.2k
        assert_eq!(6, Start::len(), "expected 6 start configurations");
2930
2931
80.2k
        let start_id = |dfa: &mut OwnedDFA,
2932
                        anchored: Anchored,
2933
584k
                        start: Start| {
2934
            // This OK because we only call 'start' under conditions
2935
            // in which we know it will succeed.
2936
584k
            dfa.st.start(anchored, start).expect("valid Input configuration")
2937
584k
        };
2938
80.2k
        if self.start_kind().has_unanchored() {
2939
38.7k
            let anchor = Anchored::No;
2940
38.7k
            let sid = start_id(self, anchor, Start::NonWordByte);
2941
38.7k
            if sid == start_id(self, anchor, Start::WordByte)
2942
30.9k
                && sid == start_id(self, anchor, Start::Text)
2943
28.4k
                && sid == start_id(self, anchor, Start::LineLF)
2944
28.4k
                && sid == start_id(self, anchor, Start::LineCR)
2945
28.4k
                && sid == start_id(self, anchor, Start::CustomLineTerminator)
2946
28.4k
            {
2947
28.4k
                self.st.universal_start_unanchored = Some(sid);
2948
28.4k
            }
2949
41.5k
        }
2950
80.2k
        if self.start_kind().has_anchored() {
2951
80.2k
            let anchor = Anchored::Yes;
2952
80.2k
            let sid = start_id(self, anchor, Start::NonWordByte);
2953
80.2k
            if sid == start_id(self, anchor, Start::WordByte)
2954
61.8k
                && sid == start_id(self, anchor, Start::Text)
2955
56.2k
                && sid == start_id(self, anchor, Start::LineLF)
2956
56.2k
                && sid == start_id(self, anchor, Start::LineCR)
2957
56.2k
                && sid == start_id(self, anchor, Start::CustomLineTerminator)
2958
56.2k
            {
2959
56.2k
                self.st.universal_start_anchored = Some(sid);
2960
56.2k
            }
2961
0
        }
2962
80.2k
    }
2963
}
2964
2965
// A variety of generic internal methods for accessing DFA internals.
2966
impl<T: AsRef<[u32]>> DFA<T> {
2967
    /// Return the info about special states.
2968
315k
    pub(crate) fn special(&self) -> &Special {
2969
315k
        &self.special
2970
315k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>>>::special
Line
Count
Source
2968
103k
    pub(crate) fn special(&self) -> &Special {
2969
103k
        &self.special
2970
103k
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::special
Line
Count
Source
2968
2.55k
    pub(crate) fn special(&self) -> &Special {
2969
2.55k
        &self.special
2970
2.55k
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::special
Line
Count
Source
2968
208k
    pub(crate) fn special(&self) -> &Special {
2969
208k
        &self.special
2970
208k
    }
2971
2972
    /// Return the info about special states as a mutable borrow.
2973
    #[cfg(feature = "dfa-build")]
2974
0
    pub(crate) fn special_mut(&mut self) -> &mut Special {
2975
0
        &mut self.special
2976
0
    }
2977
2978
    /// Returns the quit set (may be empty) used by this DFA.
2979
0
    pub(crate) fn quitset(&self) -> &ByteSet {
2980
0
        &self.quitset
2981
0
    }
2982
2983
    /// Returns the flags for this DFA.
2984
0
    pub(crate) fn flags(&self) -> &Flags {
2985
0
        &self.flags
2986
0
    }
2987
2988
    /// Returns an iterator over all states in this DFA.
2989
    ///
2990
    /// This iterator yields a tuple for each state. The first element of the
2991
    /// tuple corresponds to a state's identifier, and the second element
2992
    /// corresponds to the state itself (comprised of its transitions).
2993
79.4k
    pub(crate) fn states(&self) -> StateIter<'_, T> {
2994
79.4k
        self.tt.states()
2995
79.4k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>>>::states
Line
Count
Source
2993
77.3k
    pub(crate) fn states(&self) -> StateIter<'_, T> {
2994
77.3k
        self.tt.states()
2995
77.3k
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::states
Line
Count
Source
2993
2.11k
    pub(crate) fn states(&self) -> StateIter<'_, T> {
2994
2.11k
        self.tt.states()
2995
2.11k
    }
2996
2997
    /// Return the total number of states in this DFA. Every DFA has at least
2998
    /// 1 state, even the empty DFA.
2999
421k
    pub(crate) fn state_len(&self) -> usize {
3000
421k
        self.tt.len()
3001
421k
    }
3002
3003
    /// Return an iterator over all pattern IDs for the given match state.
3004
    ///
3005
    /// If the given state is not a match state, then this panics.
3006
    #[cfg(feature = "dfa-build")]
3007
0
    pub(crate) fn pattern_id_slice(&self, id: StateID) -> &[PatternID] {
3008
0
        assert!(self.is_match_state(id));
3009
0
        self.ms.pattern_id_slice(self.match_state_index(id))
3010
0
    }
3011
3012
    /// Return the total number of pattern IDs for the given match state.
3013
    ///
3014
    /// If the given state is not a match state, then this panics.
3015
582
    pub(crate) fn match_pattern_len(&self, id: StateID) -> usize {
3016
582
        assert!(self.is_match_state(id));
3017
582
        self.ms.pattern_len(self.match_state_index(id))
3018
582
    }
Unexecuted instantiation: <regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>>>::match_pattern_len
<regex_automata::dfa::dense::DFA<&[u32]>>::match_pattern_len
Line
Count
Source
3015
582
    pub(crate) fn match_pattern_len(&self, id: StateID) -> usize {
3016
582
        assert!(self.is_match_state(id));
3017
582
        self.ms.pattern_len(self.match_state_index(id))
3018
582
    }
3019
3020
    /// Returns the total number of patterns matched by this DFA.
3021
0
    pub(crate) fn pattern_len(&self) -> usize {
3022
0
        self.ms.pattern_len
3023
0
    }
3024
3025
    /// Returns a map from match state ID to a list of pattern IDs that match
3026
    /// in that state.
3027
    #[cfg(feature = "dfa-build")]
3028
0
    pub(crate) fn pattern_map(&self) -> BTreeMap<StateID, Vec<PatternID>> {
3029
0
        self.ms.to_map(self)
3030
0
    }
3031
3032
    /// Returns the ID of the quit state for this DFA.
3033
    #[cfg(feature = "dfa-build")]
3034
23.3M
    pub(crate) fn quit_id(&self) -> StateID {
3035
23.3M
        self.to_state_id(1)
3036
23.3M
    }
3037
3038
    /// Convert the given state identifier to the state's index. The state's
3039
    /// index corresponds to the position in which it appears in the transition
3040
    /// table. When a DFA is NOT premultiplied, then a state's identifier is
3041
    /// also its index. When a DFA is premultiplied, then a state's identifier
3042
    /// is equal to `index * alphabet_len`. This routine reverses that.
3043
15.6M
    pub(crate) fn to_index(&self, id: StateID) -> usize {
3044
15.6M
        self.tt.to_index(id)
3045
15.6M
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>>>::to_index
Line
Count
Source
3043
15.4M
    pub(crate) fn to_index(&self, id: StateID) -> usize {
3044
15.4M
        self.tt.to_index(id)
3045
15.4M
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::to_index
Line
Count
Source
3043
2.55k
    pub(crate) fn to_index(&self, id: StateID) -> usize {
3044
2.55k
        self.tt.to_index(id)
3045
2.55k
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::to_index
Line
Count
Source
3043
208k
    pub(crate) fn to_index(&self, id: StateID) -> usize {
3044
208k
        self.tt.to_index(id)
3045
208k
    }
3046
3047
    /// Convert an index to a state (in the range 0..self.state_len()) to an
3048
    /// actual state identifier.
3049
    ///
3050
    /// This is useful when using a `Vec<T>` as an efficient map keyed by state
3051
    /// to some other information (such as a remapped state ID).
3052
    #[cfg(feature = "dfa-build")]
3053
23.6M
    pub(crate) fn to_state_id(&self, index: usize) -> StateID {
3054
23.6M
        self.tt.to_state_id(index)
3055
23.6M
    }
3056
3057
    /// Return the table of state IDs for this DFA's start states.
3058
80.2k
    pub(crate) fn starts(&self) -> StartStateIter<'_> {
3059
80.2k
        self.st.iter()
3060
80.2k
    }
3061
3062
    /// Returns the index of the match state for the given ID. If the
3063
    /// given ID does not correspond to a match state, then this may
3064
    /// panic or produce an incorrect result.
3065
    #[cfg_attr(feature = "perf-inline", inline(always))]
3066
124k
    fn match_state_index(&self, id: StateID) -> usize {
3067
124k
        debug_assert!(self.is_match_state(id));
3068
        // This is one of the places where we rely on the fact that match
3069
        // states are contiguous in the transition table. Namely, that the
3070
        // first match state ID always corresponds to dfa.special.min_match.
3071
        // From there, since we know the stride, we can compute the overall
3072
        // index of any match state given the match state's ID.
3073
124k
        let min = self.special().min_match.as_usize();
3074
        // CORRECTNESS: We're allowed to produce an incorrect result or panic,
3075
        // so both the subtraction and the unchecked StateID construction is
3076
        // OK.
3077
124k
        self.to_index(StateID::new_unchecked(id.as_usize() - min))
3078
124k
    }
Unexecuted instantiation: <regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>>>::match_state_index
<regex_automata::dfa::dense::DFA<&[u32]>>::match_state_index
Line
Count
Source
3066
582
    fn match_state_index(&self, id: StateID) -> usize {
3067
582
        debug_assert!(self.is_match_state(id));
3068
        // This is one of the places where we rely on the fact that match
3069
        // states are contiguous in the transition table. Namely, that the
3070
        // first match state ID always corresponds to dfa.special.min_match.
3071
        // From there, since we know the stride, we can compute the overall
3072
        // index of any match state given the match state's ID.
3073
582
        let min = self.special().min_match.as_usize();
3074
        // CORRECTNESS: We're allowed to produce an incorrect result or panic,
3075
        // so both the subtraction and the unchecked StateID construction is
3076
        // OK.
3077
582
        self.to_index(StateID::new_unchecked(id.as_usize() - min))
3078
582
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::match_state_index
Line
Count
Source
3066
124k
    fn match_state_index(&self, id: StateID) -> usize {
3067
124k
        debug_assert!(self.is_match_state(id));
3068
        // This is one of the places where we rely on the fact that match
3069
        // states are contiguous in the transition table. Namely, that the
3070
        // first match state ID always corresponds to dfa.special.min_match.
3071
        // From there, since we know the stride, we can compute the overall
3072
        // index of any match state given the match state's ID.
3073
124k
        let min = self.special().min_match.as_usize();
3074
        // CORRECTNESS: We're allowed to produce an incorrect result or panic,
3075
        // so both the subtraction and the unchecked StateID construction is
3076
        // OK.
3077
124k
        self.to_index(StateID::new_unchecked(id.as_usize() - min))
3078
124k
    }
3079
3080
    /// Returns the index of the accelerator state for the given ID. If the
3081
    /// given ID does not correspond to an accelerator state, then this may
3082
    /// panic or produce an incorrect result.
3083
190k
    fn accelerator_index(&self, id: StateID) -> usize {
3084
190k
        let min = self.special().min_accel.as_usize();
3085
        // CORRECTNESS: We're allowed to produce an incorrect result or panic,
3086
        // so both the subtraction and the unchecked StateID construction is
3087
        // OK.
3088
190k
        self.to_index(StateID::new_unchecked(id.as_usize() - min))
3089
190k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>>>::accelerator_index
Line
Count
Source
3083
103k
    fn accelerator_index(&self, id: StateID) -> usize {
3084
103k
        let min = self.special().min_accel.as_usize();
3085
        // CORRECTNESS: We're allowed to produce an incorrect result or panic,
3086
        // so both the subtraction and the unchecked StateID construction is
3087
        // OK.
3088
103k
        self.to_index(StateID::new_unchecked(id.as_usize() - min))
3089
103k
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::accelerator_index
Line
Count
Source
3083
1.97k
    fn accelerator_index(&self, id: StateID) -> usize {
3084
1.97k
        let min = self.special().min_accel.as_usize();
3085
        // CORRECTNESS: We're allowed to produce an incorrect result or panic,
3086
        // so both the subtraction and the unchecked StateID construction is
3087
        // OK.
3088
1.97k
        self.to_index(StateID::new_unchecked(id.as_usize() - min))
3089
1.97k
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::accelerator_index
Line
Count
Source
3083
84.8k
    fn accelerator_index(&self, id: StateID) -> usize {
3084
84.8k
        let min = self.special().min_accel.as_usize();
3085
        // CORRECTNESS: We're allowed to produce an incorrect result or panic,
3086
        // so both the subtraction and the unchecked StateID construction is
3087
        // OK.
3088
84.8k
        self.to_index(StateID::new_unchecked(id.as_usize() - min))
3089
84.8k
    }
3090
3091
    /// Return the accelerators for this DFA.
3092
    fn accels(&self) -> Accels<&[u32]> {
3093
        self.accels.as_ref()
3094
    }
3095
3096
    /// Return this DFA's transition table as a slice.
3097
4.06M
    fn trans(&self) -> &[StateID] {
3098
4.06M
        self.tt.table()
3099
4.06M
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>>>::trans
Line
Count
Source
3097
3.81M
    fn trans(&self) -> &[StateID] {
3098
3.81M
        self.tt.table()
3099
3.81M
    }
<regex_automata::dfa::dense::DFA<&[u32]>>::trans
Line
Count
Source
3097
251k
    fn trans(&self) -> &[StateID] {
3098
251k
        self.tt.table()
3099
251k
    }
3100
}
3101
3102
impl<T: AsRef<[u32]>> fmt::Debug for DFA<T> {
3103
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3104
0
        writeln!(f, "dense::DFA(")?;
3105
0
        for state in self.states() {
3106
0
            fmt_state_indicator(f, self, state.id())?;
3107
0
            let id = if f.alternate() {
3108
0
                state.id().as_usize()
3109
            } else {
3110
0
                self.to_index(state.id())
3111
            };
3112
0
            write!(f, "{id:06?}: ")?;
3113
0
            state.fmt(f)?;
3114
0
            write!(f, "\n")?;
3115
        }
3116
0
        writeln!(f, "")?;
3117
0
        for (i, (start_id, anchored, sty)) in self.starts().enumerate() {
3118
0
            let id = if f.alternate() {
3119
0
                start_id.as_usize()
3120
            } else {
3121
0
                self.to_index(start_id)
3122
            };
3123
0
            if i % self.st.stride == 0 {
3124
0
                match anchored {
3125
0
                    Anchored::No => writeln!(f, "START-GROUP(unanchored)")?,
3126
0
                    Anchored::Yes => writeln!(f, "START-GROUP(anchored)")?,
3127
0
                    Anchored::Pattern(pid) => {
3128
0
                        writeln!(f, "START_GROUP(pattern: {pid:?})")?
3129
                    }
3130
                }
3131
0
            }
3132
0
            writeln!(f, "  {sty:?} => {id:06?}")?;
3133
        }
3134
0
        if self.pattern_len() > 1 {
3135
0
            writeln!(f, "")?;
3136
0
            for i in 0..self.ms.len() {
3137
0
                let id = self.ms.match_state_id(self, i);
3138
0
                let id = if f.alternate() {
3139
0
                    id.as_usize()
3140
                } else {
3141
0
                    self.to_index(id)
3142
                };
3143
0
                write!(f, "MATCH({id:06?}): ")?;
3144
0
                for (i, &pid) in self.ms.pattern_id_slice(i).iter().enumerate()
3145
                {
3146
0
                    if i > 0 {
3147
0
                        write!(f, ", ")?;
3148
0
                    }
3149
0
                    write!(f, "{pid:?}")?;
3150
                }
3151
0
                writeln!(f, "")?;
3152
            }
3153
0
        }
3154
0
        writeln!(f, "state length: {:?}", self.state_len())?;
3155
0
        writeln!(f, "pattern length: {:?}", self.pattern_len())?;
3156
0
        writeln!(f, "flags: {:?}", self.flags)?;
3157
0
        writeln!(f, ")")?;
3158
0
        Ok(())
3159
0
    }
3160
}
3161
3162
// SAFETY: We assert that our implementation of each method is correct.
3163
unsafe impl<T: AsRef<[u32]>> Automaton for DFA<T> {
3164
    #[cfg_attr(feature = "perf-inline", inline(always))]
3165
5.09M
    fn is_special_state(&self, id: StateID) -> bool {
3166
5.09M
        self.special.is_special_state(id)
3167
5.09M
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::is_special_state
Line
Count
Source
3165
4.64M
    fn is_special_state(&self, id: StateID) -> bool {
3166
4.64M
        self.special.is_special_state(id)
3167
4.64M
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::is_special_state
Line
Count
Source
3165
448k
    fn is_special_state(&self, id: StateID) -> bool {
3166
448k
        self.special.is_special_state(id)
3167
448k
    }
3168
3169
    #[cfg_attr(feature = "perf-inline", inline(always))]
3170
267k
    fn is_dead_state(&self, id: StateID) -> bool {
3171
267k
        self.special.is_dead_state(id)
3172
267k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::is_dead_state
Line
Count
Source
3170
266k
    fn is_dead_state(&self, id: StateID) -> bool {
3171
266k
        self.special.is_dead_state(id)
3172
266k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::is_dead_state
Line
Count
Source
3170
1.02k
    fn is_dead_state(&self, id: StateID) -> bool {
3171
1.02k
        self.special.is_dead_state(id)
3172
1.02k
    }
3173
3174
    #[cfg_attr(feature = "perf-inline", inline(always))]
3175
4.86k
    fn is_quit_state(&self, id: StateID) -> bool {
3176
4.86k
        self.special.is_quit_state(id)
3177
4.86k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::is_quit_state
Line
Count
Source
3175
4.86k
    fn is_quit_state(&self, id: StateID) -> bool {
3176
4.86k
        self.special.is_quit_state(id)
3177
4.86k
    }
Unexecuted instantiation: <regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::is_quit_state
3178
3179
    #[cfg_attr(feature = "perf-inline", inline(always))]
3180
939k
    fn is_match_state(&self, id: StateID) -> bool {
3181
939k
        self.special.is_match_state(id)
3182
939k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::is_match_state
Line
Count
Source
3180
780k
    fn is_match_state(&self, id: StateID) -> bool {
3181
780k
        self.special.is_match_state(id)
3182
780k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::is_match_state
Line
Count
Source
3180
582
    fn is_match_state(&self, id: StateID) -> bool {
3181
582
        self.special.is_match_state(id)
3182
582
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::is_match_state
Line
Count
Source
3180
158k
    fn is_match_state(&self, id: StateID) -> bool {
3181
158k
        self.special.is_match_state(id)
3182
158k
    }
3183
3184
    #[cfg_attr(feature = "perf-inline", inline(always))]
3185
1.07M
    fn is_start_state(&self, id: StateID) -> bool {
3186
1.07M
        self.special.is_start_state(id)
3187
1.07M
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::is_start_state
Line
Count
Source
3185
860k
    fn is_start_state(&self, id: StateID) -> bool {
3186
860k
        self.special.is_start_state(id)
3187
860k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::is_start_state
Line
Count
Source
3185
211k
    fn is_start_state(&self, id: StateID) -> bool {
3186
211k
        self.special.is_start_state(id)
3187
211k
    }
3188
3189
    #[cfg_attr(feature = "perf-inline", inline(always))]
3190
1.62M
    fn is_accel_state(&self, id: StateID) -> bool {
3191
1.62M
        self.special.is_accel_state(id)
3192
1.62M
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::is_accel_state
Line
Count
Source
3190
581k
    fn is_accel_state(&self, id: StateID) -> bool {
3191
581k
        self.special.is_accel_state(id)
3192
581k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::is_accel_state
Line
Count
Source
3190
745k
    fn is_accel_state(&self, id: StateID) -> bool {
3191
745k
        self.special.is_accel_state(id)
3192
745k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::is_accel_state
Line
Count
Source
3190
296k
    fn is_accel_state(&self, id: StateID) -> bool {
3191
296k
        self.special.is_accel_state(id)
3192
296k
    }
3193
3194
    #[cfg_attr(feature = "perf-inline", inline(always))]
3195
276k
    fn next_state(&self, current: StateID, input: u8) -> StateID {
3196
276k
        let input = self.byte_classes().get(input);
3197
276k
        let o = current.as_usize() + usize::from(input);
3198
276k
        self.trans()[o]
3199
276k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::next_state
Line
Count
Source
3195
276k
    fn next_state(&self, current: StateID, input: u8) -> StateID {
3196
276k
        let input = self.byte_classes().get(input);
3197
276k
        let o = current.as_usize() + usize::from(input);
3198
276k
        self.trans()[o]
3199
276k
    }
Unexecuted instantiation: <regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::next_state
3200
3201
    #[cfg_attr(feature = "perf-inline", inline(always))]
3202
3.74M
    unsafe fn next_state_unchecked(
3203
3.74M
        &self,
3204
3.74M
        current: StateID,
3205
3.74M
        byte: u8,
3206
3.74M
    ) -> StateID {
3207
        // We don't (or shouldn't) need an unchecked variant for the byte
3208
        // class mapping, since bound checks should be omitted automatically
3209
        // by virtue of its representation. If this ends up not being true as
3210
        // confirmed by codegen, please file an issue. ---AG
3211
3.74M
        let class = self.byte_classes().get(byte);
3212
3.74M
        let o = current.as_usize() + usize::from(class);
3213
3.74M
        let next = *self.trans().get_unchecked(o);
3214
3.74M
        next
3215
3.74M
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::next_state_unchecked
Line
Count
Source
3202
3.50M
    unsafe fn next_state_unchecked(
3203
3.50M
        &self,
3204
3.50M
        current: StateID,
3205
3.50M
        byte: u8,
3206
3.50M
    ) -> StateID {
3207
        // We don't (or shouldn't) need an unchecked variant for the byte
3208
        // class mapping, since bound checks should be omitted automatically
3209
        // by virtue of its representation. If this ends up not being true as
3210
        // confirmed by codegen, please file an issue. ---AG
3211
3.50M
        let class = self.byte_classes().get(byte);
3212
3.50M
        let o = current.as_usize() + usize::from(class);
3213
3.50M
        let next = *self.trans().get_unchecked(o);
3214
3.50M
        next
3215
3.50M
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::next_state_unchecked
Line
Count
Source
3202
235k
    unsafe fn next_state_unchecked(
3203
235k
        &self,
3204
235k
        current: StateID,
3205
235k
        byte: u8,
3206
235k
    ) -> StateID {
3207
        // We don't (or shouldn't) need an unchecked variant for the byte
3208
        // class mapping, since bound checks should be omitted automatically
3209
        // by virtue of its representation. If this ends up not being true as
3210
        // confirmed by codegen, please file an issue. ---AG
3211
235k
        let class = self.byte_classes().get(byte);
3212
235k
        let o = current.as_usize() + usize::from(class);
3213
235k
        let next = *self.trans().get_unchecked(o);
3214
235k
        next
3215
235k
    }
3216
3217
    #[cfg_attr(feature = "perf-inline", inline(always))]
3218
47.2k
    fn next_eoi_state(&self, current: StateID) -> StateID {
3219
47.2k
        let eoi = self.byte_classes().eoi().as_usize();
3220
47.2k
        let o = current.as_usize() + eoi;
3221
47.2k
        self.trans()[o]
3222
47.2k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::next_eoi_state
Line
Count
Source
3218
30.9k
    fn next_eoi_state(&self, current: StateID) -> StateID {
3219
30.9k
        let eoi = self.byte_classes().eoi().as_usize();
3220
30.9k
        let o = current.as_usize() + eoi;
3221
30.9k
        self.trans()[o]
3222
30.9k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::next_eoi_state
Line
Count
Source
3218
16.3k
    fn next_eoi_state(&self, current: StateID) -> StateID {
3219
16.3k
        let eoi = self.byte_classes().eoi().as_usize();
3220
16.3k
        let o = current.as_usize() + eoi;
3221
16.3k
        self.trans()[o]
3222
16.3k
    }
3223
3224
    #[cfg_attr(feature = "perf-inline", inline(always))]
3225
    fn pattern_len(&self) -> usize {
3226
        self.ms.pattern_len
3227
    }
3228
3229
    #[cfg_attr(feature = "perf-inline", inline(always))]
3230
582
    fn match_len(&self, id: StateID) -> usize {
3231
582
        self.match_pattern_len(id)
3232
582
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::match_len
Line
Count
Source
3230
582
    fn match_len(&self, id: StateID) -> usize {
3231
582
        self.match_pattern_len(id)
3232
582
    }
Unexecuted instantiation: <regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::match_len
3233
3234
    #[cfg_attr(feature = "perf-inline", inline(always))]
3235
507k
    fn match_pattern(&self, id: StateID, match_index: usize) -> PatternID {
3236
        // This is an optimization for the very common case of a DFA with a
3237
        // single pattern. This conditional avoids a somewhat more costly path
3238
        // that finds the pattern ID from the state machine, which requires
3239
        // a bit of slicing/pointer-chasing. This optimization tends to only
3240
        // matter when matches are frequent.
3241
507k
        if self.ms.pattern_len == 1 {
3242
383k
            return PatternID::ZERO;
3243
124k
        }
3244
124k
        let state_index = self.match_state_index(id);
3245
124k
        self.ms.pattern_id(state_index, match_index)
3246
507k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::match_pattern
Line
Count
Source
3235
378k
    fn match_pattern(&self, id: StateID, match_index: usize) -> PatternID {
3236
        // This is an optimization for the very common case of a DFA with a
3237
        // single pattern. This conditional avoids a somewhat more costly path
3238
        // that finds the pattern ID from the state machine, which requires
3239
        // a bit of slicing/pointer-chasing. This optimization tends to only
3240
        // matter when matches are frequent.
3241
378k
        if self.ms.pattern_len == 1 {
3242
378k
            return PatternID::ZERO;
3243
0
        }
3244
0
        let state_index = self.match_state_index(id);
3245
0
        self.ms.pattern_id(state_index, match_index)
3246
378k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::match_pattern
Line
Count
Source
3235
129k
    fn match_pattern(&self, id: StateID, match_index: usize) -> PatternID {
3236
        // This is an optimization for the very common case of a DFA with a
3237
        // single pattern. This conditional avoids a somewhat more costly path
3238
        // that finds the pattern ID from the state machine, which requires
3239
        // a bit of slicing/pointer-chasing. This optimization tends to only
3240
        // matter when matches are frequent.
3241
129k
        if self.ms.pattern_len == 1 {
3242
5.00k
            return PatternID::ZERO;
3243
124k
        }
3244
124k
        let state_index = self.match_state_index(id);
3245
124k
        self.ms.pattern_id(state_index, match_index)
3246
129k
    }
3247
3248
    #[cfg_attr(feature = "perf-inline", inline(always))]
3249
68.5k
    fn has_empty(&self) -> bool {
3250
68.5k
        self.flags.has_empty
3251
68.5k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::has_empty
Line
Count
Source
3249
66.4k
    fn has_empty(&self) -> bool {
3250
66.4k
        self.flags.has_empty
3251
66.4k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::has_empty
Line
Count
Source
3249
2.10k
    fn has_empty(&self) -> bool {
3250
2.10k
        self.flags.has_empty
3251
2.10k
    }
3252
3253
    #[cfg_attr(feature = "perf-inline", inline(always))]
3254
23.7k
    fn is_utf8(&self) -> bool {
3255
23.7k
        self.flags.is_utf8
3256
23.7k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::is_utf8
Line
Count
Source
3254
22.6k
    fn is_utf8(&self) -> bool {
3255
22.6k
        self.flags.is_utf8
3256
22.6k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::is_utf8
Line
Count
Source
3254
1.17k
    fn is_utf8(&self) -> bool {
3255
1.17k
        self.flags.is_utf8
3256
1.17k
    }
3257
3258
    #[cfg_attr(feature = "perf-inline", inline(always))]
3259
3.14k
    fn is_always_start_anchored(&self) -> bool {
3260
3.14k
        self.flags.is_always_start_anchored
3261
3.14k
    }
3262
3263
    #[cfg_attr(feature = "perf-inline", inline(always))]
3264
365k
    fn start_state(
3265
365k
        &self,
3266
365k
        config: &start::Config,
3267
365k
    ) -> Result<StateID, StartError> {
3268
365k
        let anchored = config.get_anchored();
3269
365k
        let start = match config.get_look_behind() {
3270
68.8k
            None => Start::Text,
3271
296k
            Some(byte) => {
3272
296k
                if !self.quitset.is_empty() && self.quitset.contains(byte) {
3273
802
                    return Err(StartError::quit(byte));
3274
295k
                }
3275
295k
                self.st.start_map.get(byte)
3276
            }
3277
        };
3278
364k
        self.st.start(anchored, start)
3279
365k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::start_state
Line
Count
Source
3264
347k
    fn start_state(
3265
347k
        &self,
3266
347k
        config: &start::Config,
3267
347k
    ) -> Result<StateID, StartError> {
3268
347k
        let anchored = config.get_anchored();
3269
347k
        let start = match config.get_look_behind() {
3270
66.7k
            None => Start::Text,
3271
280k
            Some(byte) => {
3272
280k
                if !self.quitset.is_empty() && self.quitset.contains(byte) {
3273
623
                    return Err(StartError::quit(byte));
3274
280k
                }
3275
280k
                self.st.start_map.get(byte)
3276
            }
3277
        };
3278
347k
        self.st.start(anchored, start)
3279
347k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::start_state
Line
Count
Source
3264
17.6k
    fn start_state(
3265
17.6k
        &self,
3266
17.6k
        config: &start::Config,
3267
17.6k
    ) -> Result<StateID, StartError> {
3268
17.6k
        let anchored = config.get_anchored();
3269
17.6k
        let start = match config.get_look_behind() {
3270
2.10k
            None => Start::Text,
3271
15.5k
            Some(byte) => {
3272
15.5k
                if !self.quitset.is_empty() && self.quitset.contains(byte) {
3273
179
                    return Err(StartError::quit(byte));
3274
15.3k
                }
3275
15.3k
                self.st.start_map.get(byte)
3276
            }
3277
        };
3278
17.4k
        self.st.start(anchored, start)
3279
17.6k
    }
3280
3281
    #[cfg_attr(feature = "perf-inline", inline(always))]
3282
95.6k
    fn universal_start_state(&self, mode: Anchored) -> Option<StateID> {
3283
95.6k
        match mode {
3284
95.6k
            Anchored::No => self.st.universal_start_unanchored,
3285
0
            Anchored::Yes => self.st.universal_start_anchored,
3286
0
            Anchored::Pattern(_) => None,
3287
        }
3288
95.6k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::universal_start_state
Line
Count
Source
3282
77.9k
    fn universal_start_state(&self, mode: Anchored) -> Option<StateID> {
3283
77.9k
        match mode {
3284
77.9k
            Anchored::No => self.st.universal_start_unanchored,
3285
0
            Anchored::Yes => self.st.universal_start_anchored,
3286
0
            Anchored::Pattern(_) => None,
3287
        }
3288
77.9k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::universal_start_state
Line
Count
Source
3282
17.6k
    fn universal_start_state(&self, mode: Anchored) -> Option<StateID> {
3283
17.6k
        match mode {
3284
17.6k
            Anchored::No => self.st.universal_start_unanchored,
3285
0
            Anchored::Yes => self.st.universal_start_anchored,
3286
0
            Anchored::Pattern(_) => None,
3287
        }
3288
17.6k
    }
3289
3290
    #[cfg_attr(feature = "perf-inline", inline(always))]
3291
188k
    fn accelerator(&self, id: StateID) -> &[u8] {
3292
188k
        if !self.is_accel_state(id) {
3293
0
            return &[];
3294
188k
        }
3295
188k
        self.accels.needles(self.accelerator_index(id))
3296
188k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::accelerator
Line
Count
Source
3291
103k
    fn accelerator(&self, id: StateID) -> &[u8] {
3292
103k
        if !self.is_accel_state(id) {
3293
0
            return &[];
3294
103k
        }
3295
103k
        self.accels.needles(self.accelerator_index(id))
3296
103k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::accelerator
Line
Count
Source
3291
84.8k
    fn accelerator(&self, id: StateID) -> &[u8] {
3292
84.8k
        if !self.is_accel_state(id) {
3293
0
            return &[];
3294
84.8k
        }
3295
84.8k
        self.accels.needles(self.accelerator_index(id))
3296
84.8k
    }
3297
3298
    #[cfg_attr(feature = "perf-inline", inline(always))]
3299
95.5k
    fn get_prefilter(&self) -> Option<&Prefilter> {
3300
95.5k
        self.pre.as_ref()
3301
95.5k
    }
<regex_automata::dfa::dense::DFA<alloc::vec::Vec<u32>> as regex_automata::dfa::automaton::Automaton>::get_prefilter
Line
Count
Source
3299
77.9k
    fn get_prefilter(&self) -> Option<&Prefilter> {
3300
77.9k
        self.pre.as_ref()
3301
77.9k
    }
<regex_automata::dfa::dense::DFA<&[u32]> as regex_automata::dfa::automaton::Automaton>::get_prefilter
Line
Count
Source
3299
17.6k
    fn get_prefilter(&self) -> Option<&Prefilter> {
3300
17.6k
        self.pre.as_ref()
3301
17.6k
    }
3302
}
3303
3304
/// The transition table portion of a dense DFA.
3305
///
3306
/// The transition table is the core part of the DFA in that it describes how
3307
/// to move from one state to another based on the input sequence observed.
3308
#[derive(Clone)]
3309
pub(crate) struct TransitionTable<T> {
3310
    /// A contiguous region of memory representing the transition table in
3311
    /// row-major order. The representation is dense. That is, every state
3312
    /// has precisely the same number of transitions. The maximum number of
3313
    /// transitions per state is 257 (256 for each possible byte value, plus 1
3314
    /// for the special EOI transition). If a DFA has been instructed to use
3315
    /// byte classes (the default), then the number of transitions is usually
3316
    /// substantially fewer.
3317
    ///
3318
    /// In practice, T is either `Vec<u32>` or `&[u32]`.
3319
    table: T,
3320
    /// A set of equivalence classes, where a single equivalence class
3321
    /// represents a set of bytes that never discriminate between a match
3322
    /// and a non-match in the DFA. Each equivalence class corresponds to a
3323
    /// single character in this DFA's alphabet, where the maximum number of
3324
    /// characters is 257 (each possible value of a byte plus the special
3325
    /// EOI transition). Consequently, the number of equivalence classes
3326
    /// corresponds to the number of transitions for each DFA state. Note
3327
    /// though that the *space* used by each DFA state in the transition table
3328
    /// may be larger. The total space used by each DFA state is known as the
3329
    /// stride.
3330
    ///
3331
    /// The only time the number of equivalence classes is fewer than 257 is if
3332
    /// the DFA's kind uses byte classes (which is the default). Equivalence
3333
    /// classes should generally only be disabled when debugging, so that
3334
    /// the transitions themselves aren't obscured. Disabling them has no
3335
    /// other benefit, since the equivalence class map is always used while
3336
    /// searching. In the vast majority of cases, the number of equivalence
3337
    /// classes is substantially smaller than 257, particularly when large
3338
    /// Unicode classes aren't used.
3339
    classes: ByteClasses,
3340
    /// The stride of each DFA state, expressed as a power-of-two exponent.
3341
    ///
3342
    /// The stride of a DFA corresponds to the total amount of space used by
3343
    /// each DFA state in the transition table. This may be bigger than the
3344
    /// size of a DFA's alphabet, since the stride is always the smallest
3345
    /// power of two greater than or equal to the alphabet size.
3346
    ///
3347
    /// While this wastes space, this avoids the need for integer division
3348
    /// to convert between premultiplied state IDs and their corresponding
3349
    /// indices. Instead, we can use simple bit-shifts.
3350
    ///
3351
    /// See the docs for the `stride2` method for more details.
3352
    ///
3353
    /// The minimum `stride2` value is `1` (corresponding to a stride of `2`)
3354
    /// while the maximum `stride2` value is `9` (corresponding to a stride of
3355
    /// `512`). The maximum is not `8` since the maximum alphabet size is `257`
3356
    /// when accounting for the special EOI transition. However, an alphabet
3357
    /// length of that size is exceptionally rare since the alphabet is shrunk
3358
    /// into equivalence classes.
3359
    stride2: usize,
3360
}
3361
3362
impl<'a> TransitionTable<&'a [u32]> {
3363
    /// Deserialize a transition table starting at the beginning of `slice`.
3364
    /// Upon success, return the total number of bytes read along with the
3365
    /// transition table.
3366
    ///
3367
    /// If there was a problem deserializing any part of the transition table,
3368
    /// then this returns an error. Notably, if the given slice does not have
3369
    /// the same alignment as `StateID`, then this will return an error (among
3370
    /// other possible errors).
3371
    ///
3372
    /// This is guaranteed to execute in constant time.
3373
    ///
3374
    /// # Safety
3375
    ///
3376
    /// This routine is not safe because it does not check the validity of the
3377
    /// transition table itself. In particular, the transition table can be
3378
    /// quite large, so checking its validity can be somewhat expensive. An
3379
    /// invalid transition table is not safe because other code may rely on the
3380
    /// transition table being correct (such as explicit bounds check elision).
3381
    /// Therefore, an invalid transition table can lead to undefined behavior.
3382
    ///
3383
    /// Callers that use this function must either pass on the safety invariant
3384
    /// or guarantee that the bytes given contain a valid transition table.
3385
    /// This guarantee is upheld by the bytes written by `write_to`.
3386
3.60k
    unsafe fn from_bytes_unchecked(
3387
3.60k
        mut slice: &'a [u8],
3388
3.60k
    ) -> Result<(TransitionTable<&'a [u32]>, usize), DeserializeError> {
3389
3.60k
        let slice_start = slice.as_ptr().as_usize();
3390
3391
3.59k
        let (state_len, nr) =
3392
3.60k
            wire::try_read_u32_as_usize(slice, "state length")?;
3393
3.59k
        slice = &slice[nr..];
3394
3395
3.59k
        let (stride2, nr) = wire::try_read_u32_as_usize(slice, "stride2")?;
3396
3.59k
        slice = &slice[nr..];
3397
3398
3.59k
        let (classes, nr) = ByteClasses::from_bytes(slice)?;
3399
3.46k
        slice = &slice[nr..];
3400
3401
        // The alphabet length (determined by the byte class map) cannot be
3402
        // bigger than the stride (total space used by each DFA state).
3403
3.46k
        if stride2 > 9 {
3404
31
            return Err(DeserializeError::generic(
3405
31
                "dense DFA has invalid stride2 (too big)",
3406
31
            ));
3407
3.43k
        }
3408
        // It also cannot be zero, since even a DFA that never matches anything
3409
        // has a non-zero number of states with at least two equivalence
3410
        // classes: one for all 256 byte values and another for the EOI
3411
        // sentinel.
3412
3.43k
        if stride2 < 1 {
3413
8
            return Err(DeserializeError::generic(
3414
8
                "dense DFA has invalid stride2 (too small)",
3415
8
            ));
3416
3.42k
        }
3417
        // This is OK since 1 <= stride2 <= 9.
3418
3.42k
        let stride =
3419
3.42k
            1usize.checked_shl(u32::try_from(stride2).unwrap()).unwrap();
3420
3.42k
        if classes.alphabet_len() > stride {
3421
7
            return Err(DeserializeError::generic(
3422
7
                "alphabet size cannot be bigger than transition table stride",
3423
7
            ));
3424
3.41k
        }
3425
3426
3.41k
        let trans_len =
3427
3.41k
            wire::shl(state_len, stride2, "dense table transition length")?;
3428
3.41k
        let table_bytes_len = wire::mul(
3429
3.41k
            trans_len,
3430
            StateID::SIZE,
3431
            "dense table state byte length",
3432
0
        )?;
3433
3.41k
        wire::check_slice_len(slice, table_bytes_len, "transition table")?;
3434
3.37k
        wire::check_alignment::<StateID>(slice)?;
3435
3.37k
        let table_bytes = &slice[..table_bytes_len];
3436
3.37k
        slice = &slice[table_bytes_len..];
3437
        // SAFETY: Since StateID is always representable as a u32, all we need
3438
        // to do is ensure that we have the proper length and alignment. We've
3439
        // checked both above, so the cast below is safe.
3440
        //
3441
        // N.B. This is the only not-safe code in this function.
3442
3.37k
        let table = core::slice::from_raw_parts(
3443
3.37k
            table_bytes.as_ptr().cast::<u32>(),
3444
3.37k
            trans_len,
3445
        );
3446
3.37k
        let tt = TransitionTable { table, classes, stride2 };
3447
3.37k
        Ok((tt, slice.as_ptr().as_usize() - slice_start))
3448
3.60k
    }
3449
}
3450
3451
#[cfg(feature = "dfa-build")]
3452
impl TransitionTable<Vec<u32>> {
3453
    /// Create a minimal transition table with just two states: a dead state
3454
    /// and a quit state. The alphabet length and stride of the transition
3455
    /// table is determined by the given set of equivalence classes.
3456
82.1k
    fn minimal(classes: ByteClasses) -> TransitionTable<Vec<u32>> {
3457
82.1k
        let mut tt = TransitionTable {
3458
82.1k
            table: vec![],
3459
82.1k
            classes,
3460
82.1k
            stride2: classes.stride2(),
3461
82.1k
        };
3462
        // Two states, regardless of alphabet size, can always fit into u32.
3463
82.1k
        tt.add_empty_state().unwrap(); // dead state
3464
82.1k
        tt.add_empty_state().unwrap(); // quit state
3465
82.1k
        tt
3466
82.1k
    }
3467
3468
    /// Set a transition in this table. Both the `from` and `to` states must
3469
    /// already exist, otherwise this panics. `unit` should correspond to the
3470
    /// transition out of `from` to set to `to`.
3471
38.6M
    fn set(&mut self, from: StateID, unit: alphabet::Unit, to: StateID) {
3472
38.6M
        assert!(self.is_valid(from), "invalid 'from' state");
3473
38.6M
        assert!(self.is_valid(to), "invalid 'to' state");
3474
38.6M
        self.table[from.as_usize() + self.classes.get_by_unit(unit)] =
3475
38.6M
            to.as_u32();
3476
38.6M
    }
3477
3478
    /// Add an empty state (a state where all transitions lead to a dead state)
3479
    /// and return its identifier. The identifier returned is guaranteed to
3480
    /// not point to any other existing state.
3481
    ///
3482
    /// If adding a state would exhaust the state identifier space, then this
3483
    /// returns an error.
3484
1.01M
    fn add_empty_state(&mut self) -> Result<StateID, BuildError> {
3485
        // Normally, to get a fresh state identifier, we would just
3486
        // take the index of the next state added to the transition
3487
        // table. However, we actually perform an optimization here
3488
        // that pre-multiplies state IDs by the stride, such that they
3489
        // point immediately at the beginning of their transitions in
3490
        // the transition table. This avoids an extra multiplication
3491
        // instruction for state lookup at search time.
3492
        //
3493
        // Premultiplied identifiers means that instead of your matching
3494
        // loop looking something like this:
3495
        //
3496
        //   state = dfa.start
3497
        //   for byte in haystack:
3498
        //       next = dfa.transitions[state * stride + byte]
3499
        //       if dfa.is_match(next):
3500
        //           return true
3501
        //   return false
3502
        //
3503
        // it can instead look like this:
3504
        //
3505
        //   state = dfa.start
3506
        //   for byte in haystack:
3507
        //       next = dfa.transitions[state + byte]
3508
        //       if dfa.is_match(next):
3509
        //           return true
3510
        //   return false
3511
        //
3512
        // In other words, we save a multiplication instruction in the
3513
        // critical path. This turns out to be a decent performance win.
3514
        // The cost of using premultiplied state ids is that they can
3515
        // require a bigger state id representation. (And they also make
3516
        // the code a bit more complex, especially during minimization and
3517
        // when reshuffling states, as one needs to convert back and forth
3518
        // between state IDs and state indices.)
3519
        //
3520
        // To do this, we simply take the index of the state into the
3521
        // entire transition table, rather than the index of the state
3522
        // itself. e.g., If the stride is 64, then the ID of the 3rd state
3523
        // is 192, not 2.
3524
1.01M
        let next = self.table.len();
3525
1.01M
        let id =
3526
1.01M
            StateID::new(next).map_err(|_| BuildError::too_many_states())?;
3527
1.01M
        self.table.extend(iter::repeat(0).take(self.stride()));
3528
1.01M
        Ok(id)
3529
1.01M
    }
3530
3531
    /// Swap the two states given in this transition table.
3532
    ///
3533
    /// This routine does not do anything to check the correctness of this
3534
    /// swap. Callers must ensure that other states pointing to id1 and id2 are
3535
    /// updated appropriately.
3536
    ///
3537
    /// Both id1 and id2 must point to valid states, otherwise this panics.
3538
169k
    fn swap(&mut self, id1: StateID, id2: StateID) {
3539
169k
        assert!(self.is_valid(id1), "invalid 'id1' state: {id1:?}");
3540
169k
        assert!(self.is_valid(id2), "invalid 'id2' state: {id2:?}");
3541
        // We only need to swap the parts of the state that are used. So if the
3542
        // stride is 64, but the alphabet length is only 33, then we save a lot
3543
        // of work.
3544
2.85M
        for b in 0..self.classes.alphabet_len() {
3545
2.85M
            self.table.swap(id1.as_usize() + b, id2.as_usize() + b);
3546
2.85M
        }
3547
169k
    }
3548
3549
    /// Remap the transitions for the state given according to the function
3550
    /// given. This applies the given map function to every transition in the
3551
    /// given state and changes the transition in place to the result of the
3552
    /// map function for that transition.
3553
0
    fn remap(&mut self, id: StateID, map: impl Fn(StateID) -> StateID) {
3554
0
        for byte in 0..self.alphabet_len() {
3555
0
            let i = id.as_usize() + byte;
3556
0
            let next = self.table()[i];
3557
0
            self.table_mut()[id.as_usize() + byte] = map(next);
3558
0
        }
3559
0
    }
3560
3561
    /// Truncate the states in this transition table to the given length.
3562
    ///
3563
    /// This routine does not do anything to check the correctness of this
3564
    /// truncation. Callers must ensure that other states pointing to truncated
3565
    /// states are updated appropriately.
3566
0
    fn truncate(&mut self, len: usize) {
3567
0
        self.table.truncate(len << self.stride2);
3568
0
    }
3569
}
3570
3571
impl<T: AsRef<[u32]>> TransitionTable<T> {
3572
    /// Writes a serialized form of this transition table to the buffer given.
3573
    /// If the buffer is too small, then an error is returned. To determine
3574
    /// how big the buffer must be, use `write_to_len`.
3575
    fn write_to<E: Endian>(
3576
        &self,
3577
        mut dst: &mut [u8],
3578
    ) -> Result<usize, SerializeError> {
3579
        let nwrite = self.write_to_len();
3580
        if dst.len() < nwrite {
3581
            return Err(SerializeError::buffer_too_small("transition table"));
3582
        }
3583
        dst = &mut dst[..nwrite];
3584
3585
        // write state length
3586
        // Unwrap is OK since number of states is guaranteed to fit in a u32.
3587
        E::write_u32(u32::try_from(self.len()).unwrap(), dst);
3588
        dst = &mut dst[size_of::<u32>()..];
3589
3590
        // write state stride (as power of 2)
3591
        // Unwrap is OK since stride2 is guaranteed to be <= 9.
3592
        E::write_u32(u32::try_from(self.stride2).unwrap(), dst);
3593
        dst = &mut dst[size_of::<u32>()..];
3594
3595
        // write byte class map
3596
        let n = self.classes.write_to(dst)?;
3597
        dst = &mut dst[n..];
3598
3599
        // write actual transitions
3600
        for &sid in self.table() {
3601
            let n = wire::write_state_id::<E>(sid, &mut dst);
3602
            dst = &mut dst[n..];
3603
        }
3604
        Ok(nwrite)
3605
    }
3606
3607
    /// Returns the number of bytes the serialized form of this transition
3608
    /// table will use.
3609
    fn write_to_len(&self) -> usize {
3610
        size_of::<u32>()   // state length
3611
        + size_of::<u32>() // stride2
3612
        + self.classes.write_to_len()
3613
        + (self.table().len() * StateID::SIZE)
3614
    }
3615
3616
    /// Validates that every state ID in this transition table is valid.
3617
    ///
3618
    /// That is, every state ID can be used to correctly index a state in this
3619
    /// table.
3620
2.21k
    fn validate(&self, dfa: &DFA<T>) -> Result<(), DeserializeError> {
3621
2.21k
        let sp = &dfa.special;
3622
747k
        for state in self.states() {
3623
            // We check that the ID itself is well formed. That is, if it's
3624
            // a special state then it must actually be a quit, dead, accel,
3625
            // match or start state.
3626
747k
            if sp.is_special_state(state.id()) {
3627
10.1k
                let is_actually_special = sp.is_dead_state(state.id())
3628
7.98k
                    || sp.is_quit_state(state.id())
3629
6.90k
                    || sp.is_match_state(state.id())
3630
6.31k
                    || sp.is_start_state(state.id())
3631
1.72k
                    || sp.is_accel_state(state.id());
3632
10.1k
                if !is_actually_special {
3633
                    // This is kind of a cryptic error message...
3634
16
                    return Err(DeserializeError::generic(
3635
16
                        "found dense state tagged as special but \
3636
16
                         wasn't actually special",
3637
16
                    ));
3638
10.1k
                }
3639
10.1k
                if sp.is_match_state(state.id())
3640
582
                    && dfa.match_len(state.id()) == 0
3641
                {
3642
2
                    return Err(DeserializeError::generic(
3643
2
                        "found match state with zero pattern IDs",
3644
2
                    ));
3645
10.1k
                }
3646
737k
            }
3647
1.50M
            for (_, to) in state.transitions() {
3648
1.50M
                if !self.is_valid(to) {
3649
15
                    return Err(DeserializeError::generic(
3650
15
                        "found invalid state ID in transition table",
3651
15
                    ));
3652
1.50M
                }
3653
            }
3654
        }
3655
2.18k
        Ok(())
3656
2.21k
    }
3657
3658
    /// Converts this transition table to a borrowed value.
3659
    fn as_ref(&self) -> TransitionTable<&'_ [u32]> {
3660
        TransitionTable {
3661
            table: self.table.as_ref(),
3662
            classes: self.classes.clone(),
3663
            stride2: self.stride2,
3664
        }
3665
    }
3666
3667
    /// Converts this transition table to an owned value.
3668
    #[cfg(feature = "alloc")]
3669
    fn to_owned(&self) -> TransitionTable<alloc::vec::Vec<u32>> {
3670
        TransitionTable {
3671
            table: self.table.as_ref().to_vec(),
3672
            classes: self.classes.clone(),
3673
            stride2: self.stride2,
3674
        }
3675
    }
3676
3677
    /// Return the state for the given ID. If the given ID is not valid, then
3678
    /// this panics.
3679
2.40M
    fn state(&self, id: StateID) -> State<'_> {
3680
2.40M
        assert!(self.is_valid(id));
3681
3682
2.40M
        let i = id.as_usize();
3683
2.40M
        State {
3684
2.40M
            id,
3685
2.40M
            stride2: self.stride2,
3686
2.40M
            transitions: &self.table()[i..i + self.alphabet_len()],
3687
2.40M
        }
3688
2.40M
    }
<regex_automata::dfa::dense::TransitionTable<alloc::vec::Vec<u32>>>::state
Line
Count
Source
3679
910k
    fn state(&self, id: StateID) -> State<'_> {
3680
910k
        assert!(self.is_valid(id));
3681
3682
910k
        let i = id.as_usize();
3683
910k
        State {
3684
910k
            id,
3685
910k
            stride2: self.stride2,
3686
910k
            transitions: &self.table()[i..i + self.alphabet_len()],
3687
910k
        }
3688
910k
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::state
Line
Count
Source
3679
1.49M
    fn state(&self, id: StateID) -> State<'_> {
3680
1.49M
        assert!(self.is_valid(id));
3681
3682
1.49M
        let i = id.as_usize();
3683
1.49M
        State {
3684
1.49M
            id,
3685
1.49M
            stride2: self.stride2,
3686
1.49M
            transitions: &self.table()[i..i + self.alphabet_len()],
3687
1.49M
        }
3688
1.49M
    }
3689
3690
    /// Returns an iterator over all states in this transition table.
3691
    ///
3692
    /// This iterator yields a tuple for each state. The first element of the
3693
    /// tuple corresponds to a state's identifier, and the second element
3694
    /// corresponds to the state itself (comprised of its transitions).
3695
81.6k
    fn states(&self) -> StateIter<'_, T> {
3696
81.6k
        StateIter {
3697
81.6k
            tt: self,
3698
81.6k
            it: self.table().chunks(self.stride()).enumerate(),
3699
81.6k
        }
3700
81.6k
    }
<regex_automata::dfa::dense::TransitionTable<alloc::vec::Vec<u32>>>::states
Line
Count
Source
3695
77.3k
    fn states(&self) -> StateIter<'_, T> {
3696
77.3k
        StateIter {
3697
77.3k
            tt: self,
3698
77.3k
            it: self.table().chunks(self.stride()).enumerate(),
3699
77.3k
        }
3700
77.3k
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::states
Line
Count
Source
3695
4.32k
    fn states(&self) -> StateIter<'_, T> {
3696
4.32k
        StateIter {
3697
4.32k
            tt: self,
3698
4.32k
            it: self.table().chunks(self.stride()).enumerate(),
3699
4.32k
        }
3700
4.32k
    }
3701
3702
    /// Convert a state identifier to an index to a state (in the range
3703
    /// 0..self.len()).
3704
    ///
3705
    /// This is useful when using a `Vec<T>` as an efficient map keyed by state
3706
    /// to some other information (such as a remapped state ID).
3707
    ///
3708
    /// If the given ID is not valid, then this may panic or produce an
3709
    /// incorrect index.
3710
16.1M
    fn to_index(&self, id: StateID) -> usize {
3711
16.1M
        id.as_usize() >> self.stride2
3712
16.1M
    }
<regex_automata::dfa::dense::TransitionTable<alloc::vec::Vec<u32>>>::to_index
Line
Count
Source
3710
15.9M
    fn to_index(&self, id: StateID) -> usize {
3711
15.9M
        id.as_usize() >> self.stride2
3712
15.9M
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::to_index
Line
Count
Source
3710
2.55k
    fn to_index(&self, id: StateID) -> usize {
3711
2.55k
        id.as_usize() >> self.stride2
3712
2.55k
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::to_index
Line
Count
Source
3710
208k
    fn to_index(&self, id: StateID) -> usize {
3711
208k
        id.as_usize() >> self.stride2
3712
208k
    }
3713
3714
    /// Convert an index to a state (in the range 0..self.len()) to an actual
3715
    /// state identifier.
3716
    ///
3717
    /// This is useful when using a `Vec<T>` as an efficient map keyed by state
3718
    /// to some other information (such as a remapped state ID).
3719
    ///
3720
    /// If the given index is not in the specified range, then this may panic
3721
    /// or produce an incorrect state ID.
3722
26.6M
    fn to_state_id(&self, index: usize) -> StateID {
3723
        // CORRECTNESS: If the given index is not valid, then it is not
3724
        // required for this to panic or return a valid state ID.
3725
26.6M
        StateID::new_unchecked(index << self.stride2)
3726
26.6M
    }
<regex_automata::dfa::dense::TransitionTable<alloc::vec::Vec<u32>>>::to_state_id
Line
Count
Source
3722
25.1M
    fn to_state_id(&self, index: usize) -> StateID {
3723
        // CORRECTNESS: If the given index is not valid, then it is not
3724
        // required for this to panic or return a valid state ID.
3725
25.1M
        StateID::new_unchecked(index << self.stride2)
3726
25.1M
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::to_state_id
Line
Count
Source
3722
1.49M
    fn to_state_id(&self, index: usize) -> StateID {
3723
        // CORRECTNESS: If the given index is not valid, then it is not
3724
        // required for this to panic or return a valid state ID.
3725
1.49M
        StateID::new_unchecked(index << self.stride2)
3726
1.49M
    }
3727
3728
    /// Returns the state ID for the state immediately following the one given.
3729
    ///
3730
    /// This does not check whether the state ID returned is invalid. In fact,
3731
    /// if the state ID given is the last state in this DFA, then the state ID
3732
    /// returned is guaranteed to be invalid.
3733
    #[cfg(feature = "dfa-build")]
3734
381k
    fn next_state_id(&self, id: StateID) -> StateID {
3735
381k
        self.to_state_id(self.to_index(id).checked_add(1).unwrap())
3736
381k
    }
3737
3738
    /// Returns the state ID for the state immediately preceding the one given.
3739
    ///
3740
    /// If the dead ID given (which is zero), then this panics.
3741
    #[cfg(feature = "dfa-build")]
3742
177k
    fn prev_state_id(&self, id: StateID) -> StateID {
3743
177k
        self.to_state_id(self.to_index(id).checked_sub(1).unwrap())
3744
177k
    }
3745
3746
    /// Returns the table as a slice of state IDs.
3747
90.6M
    fn table(&self) -> &[StateID] {
3748
90.6M
        wire::u32s_to_state_ids(self.table.as_ref())
3749
90.6M
    }
<regex_automata::dfa::dense::TransitionTable<alloc::vec::Vec<u32>>>::table
Line
Count
Source
3747
85.8M
    fn table(&self) -> &[StateID] {
3748
85.8M
        wire::u32s_to_state_ids(self.table.as_ref())
3749
85.8M
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::table
Line
Count
Source
3747
4.53M
    fn table(&self) -> &[StateID] {
3748
4.53M
        wire::u32s_to_state_ids(self.table.as_ref())
3749
4.53M
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::table
Line
Count
Source
3747
251k
    fn table(&self) -> &[StateID] {
3748
251k
        wire::u32s_to_state_ids(self.table.as_ref())
3749
251k
    }
3750
3751
    /// Returns the total number of states in this transition table.
3752
    ///
3753
    /// Note that a DFA always has at least two states: the dead and quit
3754
    /// states. In particular, the dead state always has ID 0 and is
3755
    /// correspondingly always the first state. The dead state is never a match
3756
    /// state.
3757
423k
    fn len(&self) -> usize {
3758
423k
        self.table().len() >> self.stride2
3759
423k
    }
<regex_automata::dfa::dense::TransitionTable<alloc::vec::Vec<u32>>>::len
Line
Count
Source
3757
421k
    fn len(&self) -> usize {
3758
421k
        self.table().len() >> self.stride2
3759
421k
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::len
Line
Count
Source
3757
2.48k
    fn len(&self) -> usize {
3758
2.48k
        self.table().len() >> self.stride2
3759
2.48k
    }
3760
3761
    /// Returns the total stride for every state in this DFA. This corresponds
3762
    /// to the total number of transitions used by each state in this DFA's
3763
    /// transition table.
3764
83.8M
    fn stride(&self) -> usize {
3765
83.8M
        1 << self.stride2
3766
83.8M
    }
<regex_automata::dfa::dense::TransitionTable<alloc::vec::Vec<u32>>>::stride
Line
Count
Source
3764
80.8M
    fn stride(&self) -> usize {
3765
80.8M
        1 << self.stride2
3766
80.8M
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::stride
Line
Count
Source
3764
3.04M
    fn stride(&self) -> usize {
3765
3.04M
        1 << self.stride2
3766
3.04M
    }
3767
3768
    /// Returns the total number of elements in the alphabet for this
3769
    /// transition table. This is always less than or equal to `self.stride()`.
3770
    /// It is only equal when the alphabet length is a power of 2. Otherwise,
3771
    /// it is always strictly less.
3772
2.40M
    fn alphabet_len(&self) -> usize {
3773
2.40M
        self.classes.alphabet_len()
3774
2.40M
    }
<regex_automata::dfa::dense::TransitionTable<alloc::vec::Vec<u32>>>::alphabet_len
Line
Count
Source
3772
910k
    fn alphabet_len(&self) -> usize {
3773
910k
        self.classes.alphabet_len()
3774
910k
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::alphabet_len
Line
Count
Source
3772
1.49M
    fn alphabet_len(&self) -> usize {
3773
1.49M
        self.classes.alphabet_len()
3774
1.49M
    }
3775
3776
    /// Returns true if and only if the given state ID is valid for this
3777
    /// transition table. Validity in this context means that the given ID can
3778
    /// be used as a valid offset with `self.stride()` to index this transition
3779
    /// table.
3780
82.7M
    fn is_valid(&self, id: StateID) -> bool {
3781
82.7M
        let id = id.as_usize();
3782
82.7M
        id < self.table().len() && id % self.stride() == 0
3783
82.7M
    }
<regex_automata::dfa::dense::TransitionTable<alloc::vec::Vec<u32>>>::is_valid
Line
Count
Source
3780
79.7M
    fn is_valid(&self, id: StateID) -> bool {
3781
79.7M
        let id = id.as_usize();
3782
79.7M
        id < self.table().len() && id % self.stride() == 0
3783
79.7M
    }
<regex_automata::dfa::dense::TransitionTable<&[u32]>>::is_valid
Line
Count
Source
3780
3.03M
    fn is_valid(&self, id: StateID) -> bool {
3781
3.03M
        let id = id.as_usize();
3782
3.03M
        id < self.table().len() && id % self.stride() == 0
3783
3.03M
    }
3784
3785
    /// Return the memory usage, in bytes, of this transition table.
3786
    ///
3787
    /// This does not include the size of a `TransitionTable` value itself.
3788
852k
    fn memory_usage(&self) -> usize {
3789
852k
        self.table().len() * StateID::SIZE
3790
852k
    }
3791
}
3792
3793
#[cfg(feature = "dfa-build")]
3794
impl<T: AsMut<[u32]>> TransitionTable<T> {
3795
    /// Returns the table as a slice of state IDs.
3796
87.5k
    fn table_mut(&mut self) -> &mut [StateID] {
3797
87.5k
        wire::u32s_to_state_ids_mut(self.table.as_mut())
3798
87.5k
    }
3799
}
3800
3801
/// The set of all possible starting states in a DFA.
3802
///
3803
/// The set of starting states corresponds to the possible choices one can make
3804
/// in terms of starting a DFA. That is, before following the first transition,
3805
/// you first need to select the state that you start in.
3806
///
3807
/// Normally, a DFA converted from an NFA that has a single starting state
3808
/// would itself just have one starting state. However, our support for look
3809
/// around generally requires more starting states. The correct starting state
3810
/// is chosen based on certain properties of the position at which we begin
3811
/// our search.
3812
///
3813
/// Before listing those properties, we first must define two terms:
3814
///
3815
/// * `haystack` - The bytes to execute the search. The search always starts
3816
///   at the beginning of `haystack` and ends before or at the end of
3817
///   `haystack`.
3818
/// * `context` - The (possibly empty) bytes surrounding `haystack`. `haystack`
3819
///   must be contained within `context` such that `context` is at least as big
3820
///   as `haystack`.
3821
///
3822
/// This split is crucial for dealing with look-around. For example, consider
3823
/// the context `foobarbaz`, the haystack `bar` and the regex `^bar$`. This
3824
/// regex should _not_ match the haystack since `bar` does not appear at the
3825
/// beginning of the input. Similarly, the regex `\Bbar\B` should match the
3826
/// haystack because `bar` is not surrounded by word boundaries. But a search
3827
/// that does not take context into account would not permit `\B` to match
3828
/// since the beginning of any string matches a word boundary. Similarly, a
3829
/// search that does not take context into account when searching `^bar$` in
3830
/// the haystack `bar` would produce a match when it shouldn't.
3831
///
3832
/// Thus, it follows that the starting state is chosen based on the following
3833
/// criteria, derived from the position at which the search starts in the
3834
/// `context` (corresponding to the start of `haystack`):
3835
///
3836
/// 1. If the search starts at the beginning of `context`, then the `Text`
3837
///    start state is used. (Since `^` corresponds to
3838
///    `hir::Anchor::Start`.)
3839
/// 2. If the search starts at a position immediately following a line
3840
///    terminator, then the `Line` start state is used. (Since `(?m:^)`
3841
///    corresponds to `hir::Anchor::StartLF`.)
3842
/// 3. If the search starts at a position immediately following a byte
3843
///    classified as a "word" character (`[_0-9a-zA-Z]`), then the `WordByte`
3844
///    start state is used. (Since `(?-u:\b)` corresponds to a word boundary.)
3845
/// 4. Otherwise, if the search starts at a position immediately following
3846
///    a byte that is not classified as a "word" character (`[^_0-9a-zA-Z]`),
3847
///    then the `NonWordByte` start state is used. (Since `(?-u:\B)`
3848
///    corresponds to a not-word-boundary.)
3849
///
3850
/// (N.B. Unicode word boundaries are not supported by the DFA because they
3851
/// require multi-byte look-around and this is difficult to support in a DFA.)
3852
///
3853
/// To further complicate things, we also support constructing individual
3854
/// anchored start states for each pattern in the DFA. (Which is required to
3855
/// implement overlapping regexes correctly, but is also generally useful.)
3856
/// Thus, when individual start states for each pattern are enabled, then the
3857
/// total number of start states represented is `4 + (4 * #patterns)`, where
3858
/// the 4 comes from each of the 4 possibilities above. The first 4 represents
3859
/// the starting states for the entire DFA, which support searching for
3860
/// multiple patterns simultaneously (possibly unanchored).
3861
///
3862
/// If individual start states are disabled, then this will only store 4
3863
/// start states. Typically, individual start states are only enabled when
3864
/// constructing the reverse DFA for regex matching. But they are also useful
3865
/// for building DFAs that can search for a specific pattern or even to support
3866
/// both anchored and unanchored searches with the same DFA.
3867
///
3868
/// Note though that while the start table always has either `4` or
3869
/// `4 + (4 * #patterns)` starting state *ids*, the total number of states
3870
/// might be considerably smaller. That is, many of the IDs may be duplicative.
3871
/// (For example, if a regex doesn't have a `\b` sub-pattern, then there's no
3872
/// reason to generate a unique starting state for handling word boundaries.
3873
/// Similarly for start/end anchors.)
3874
#[derive(Clone)]
3875
pub(crate) struct StartTable<T> {
3876
    /// The initial start state IDs.
3877
    ///
3878
    /// In practice, T is either `Vec<u32>` or `&[u32]`.
3879
    ///
3880
    /// The first `2 * stride` (currently always 8) entries always correspond
3881
    /// to the starts states for the entire DFA, with the first 4 entries being
3882
    /// for unanchored searches and the second 4 entries being for anchored
3883
    /// searches. To keep things simple, we always use 8 entries even if the
3884
    /// `StartKind` is not both.
3885
    ///
3886
    /// After that, there are `stride * patterns` state IDs, where `patterns`
3887
    /// may be zero in the case of a DFA with no patterns or in the case where
3888
    /// the DFA was built without enabling starting states for each pattern.
3889
    table: T,
3890
    /// The starting state configuration supported. When 'both', both
3891
    /// unanchored and anchored searches work. When 'unanchored', anchored
3892
    /// searches panic. When 'anchored', unanchored searches panic.
3893
    kind: StartKind,
3894
    /// The start state configuration for every possible byte.
3895
    start_map: StartByteMap,
3896
    /// The number of starting state IDs per pattern.
3897
    stride: usize,
3898
    /// The total number of patterns for which starting states are encoded.
3899
    /// This is `None` for DFAs that were built without start states for each
3900
    /// pattern. Thus, one cannot use this field to say how many patterns
3901
    /// are in the DFA in all cases. It is specific to how many patterns are
3902
    /// represented in this start table.
3903
    pattern_len: Option<usize>,
3904
    /// The universal starting state for unanchored searches. This is only
3905
    /// present when the DFA supports unanchored searches and when all starting
3906
    /// state IDs for an unanchored search are equivalent.
3907
    universal_start_unanchored: Option<StateID>,
3908
    /// The universal starting state for anchored searches. This is only
3909
    /// present when the DFA supports anchored searches and when all starting
3910
    /// state IDs for an anchored search are equivalent.
3911
    universal_start_anchored: Option<StateID>,
3912
}
3913
3914
#[cfg(feature = "dfa-build")]
3915
impl StartTable<Vec<u32>> {
3916
    /// Create a valid set of start states all pointing to the dead state.
3917
    ///
3918
    /// When the corresponding DFA is constructed with start states for each
3919
    /// pattern, then `patterns` should be the number of patterns. Otherwise,
3920
    /// it should be zero.
3921
    ///
3922
    /// If the total table size could exceed the allocatable limit, then this
3923
    /// returns an error. In practice, this is unlikely to be able to occur,
3924
    /// since it's likely that allocation would have failed long before it got
3925
    /// to this point.
3926
82.1k
    fn dead(
3927
82.1k
        kind: StartKind,
3928
82.1k
        lookm: &LookMatcher,
3929
82.1k
        pattern_len: Option<usize>,
3930
82.1k
    ) -> Result<StartTable<Vec<u32>>, BuildError> {
3931
82.1k
        if let Some(len) = pattern_len {
3932
79.1k
            assert!(len <= PatternID::LIMIT);
3933
3.00k
        }
3934
82.1k
        let stride = Start::len();
3935
        // OK because 2*4 is never going to overflow anything.
3936
82.1k
        let starts_len = stride.checked_mul(2).unwrap();
3937
82.1k
        let pattern_starts_len =
3938
82.1k
            match stride.checked_mul(pattern_len.unwrap_or(0)) {
3939
82.1k
                Some(x) => x,
3940
0
                None => return Err(BuildError::too_many_start_states()),
3941
            };
3942
82.1k
        let table_len = match starts_len.checked_add(pattern_starts_len) {
3943
82.1k
            Some(x) => x,
3944
0
            None => return Err(BuildError::too_many_start_states()),
3945
        };
3946
82.1k
        if let Err(_) = isize::try_from(table_len) {
3947
0
            return Err(BuildError::too_many_start_states());
3948
82.1k
        }
3949
82.1k
        let table = vec![DEAD.as_u32(); table_len];
3950
82.1k
        let start_map = StartByteMap::new(lookm);
3951
82.1k
        Ok(StartTable {
3952
82.1k
            table,
3953
82.1k
            kind,
3954
82.1k
            start_map,
3955
82.1k
            stride,
3956
82.1k
            pattern_len,
3957
82.1k
            universal_start_unanchored: None,
3958
82.1k
            universal_start_anchored: None,
3959
82.1k
        })
3960
82.1k
    }
3961
}
3962
3963
impl<'a> StartTable<&'a [u32]> {
3964
    /// Deserialize a table of start state IDs starting at the beginning of
3965
    /// `slice`. Upon success, return the total number of bytes read along with
3966
    /// the table of starting state IDs.
3967
    ///
3968
    /// If there was a problem deserializing any part of the starting IDs,
3969
    /// then this returns an error. Notably, if the given slice does not have
3970
    /// the same alignment as `StateID`, then this will return an error (among
3971
    /// other possible errors).
3972
    ///
3973
    /// This is guaranteed to execute in constant time.
3974
    ///
3975
    /// # Safety
3976
    ///
3977
    /// This routine is not safe because it does not check the validity of the
3978
    /// starting state IDs themselves. In particular, the number of starting
3979
    /// IDs can be of variable length, so it's possible that checking their
3980
    /// validity cannot be done in constant time. An invalid starting state
3981
    /// ID is not safe because other code may rely on the starting IDs being
3982
    /// correct (such as explicit bounds check elision). Therefore, an invalid
3983
    /// start ID can lead to undefined behavior.
3984
    ///
3985
    /// Callers that use this function must either pass on the safety invariant
3986
    /// or guarantee that the bytes given contain valid starting state IDs.
3987
    /// This guarantee is upheld by the bytes written by `write_to`.
3988
3.37k
    unsafe fn from_bytes_unchecked(
3989
3.37k
        mut slice: &'a [u8],
3990
3.37k
    ) -> Result<(StartTable<&'a [u32]>, usize), DeserializeError> {
3991
3.37k
        let slice_start = slice.as_ptr().as_usize();
3992
3993
3.37k
        let (kind, nr) = StartKind::from_bytes(slice)?;
3994
3.30k
        slice = &slice[nr..];
3995
3996
3.30k
        let (start_map, nr) = StartByteMap::from_bytes(slice)?;
3997
3.24k
        slice = &slice[nr..];
3998
3999
3.23k
        let (stride, nr) =
4000
3.24k
            wire::try_read_u32_as_usize(slice, "start table stride")?;
4001
3.23k
        slice = &slice[nr..];
4002
3.23k
        if stride != Start::len() {
4003
45
            return Err(DeserializeError::generic(
4004
45
                "invalid starting table stride",
4005
45
            ));
4006
3.19k
        }
4007
4008
3.19k
        let (maybe_pattern_len, nr) =
4009
3.19k
            wire::try_read_u32_as_usize(slice, "start table patterns")?;
4010
3.19k
        slice = &slice[nr..];
4011
3.19k
        let pattern_len = if maybe_pattern_len.as_u32() == u32::MAX {
4012
1.22k
            None
4013
        } else {
4014
1.96k
            Some(maybe_pattern_len)
4015
        };
4016
3.19k
        if pattern_len.map_or(false, |len| len > PatternID::LIMIT) {
4017
37
            return Err(DeserializeError::generic(
4018
37
                "invalid number of patterns",
4019
37
            ));
4020
3.15k
        }
4021
4022
3.14k
        let (universal_unanchored, nr) =
4023
3.15k
            wire::try_read_u32(slice, "universal unanchored start")?;
4024
3.14k
        slice = &slice[nr..];
4025
3.14k
        let universal_start_unanchored = if universal_unanchored == u32::MAX {
4026
660
            None
4027
        } else {
4028
2.48k
            Some(StateID::try_from(universal_unanchored).map_err(|e| {
4029
32
                DeserializeError::state_id_error(
4030
32
                    e,
4031
                    "universal unanchored start",
4032
                )
4033
32
            })?)
4034
        };
4035
4036
3.07k
        let (universal_anchored, nr) =
4037
3.11k
            wire::try_read_u32(slice, "universal anchored start")?;
4038
3.07k
        slice = &slice[nr..];
4039
3.07k
        let universal_start_anchored = if universal_anchored == u32::MAX {
4040
61
            None
4041
        } else {
4042
3.01k
            Some(StateID::try_from(universal_anchored).map_err(|e| {
4043
28
                DeserializeError::state_id_error(e, "universal anchored start")
4044
28
            })?)
4045
        };
4046
4047
3.04k
        let pattern_table_size = wire::mul(
4048
3.04k
            stride,
4049
3.04k
            pattern_len.unwrap_or(0),
4050
            "invalid pattern length",
4051
0
        )?;
4052
        // Our start states always start with a two stride of start states for
4053
        // the entire automaton. The first stride is for unanchored starting
4054
        // states and the second stride is for anchored starting states. What
4055
        // follows it are an optional set of start states for each pattern.
4056
3.04k
        let start_state_len = wire::add(
4057
3.04k
            wire::mul(2, stride, "start state stride too big")?,
4058
3.04k
            pattern_table_size,
4059
            "invalid 'any' pattern starts size",
4060
0
        )?;
4061
3.04k
        let table_bytes_len = wire::mul(
4062
3.04k
            start_state_len,
4063
            StateID::SIZE,
4064
            "pattern table bytes length",
4065
0
        )?;
4066
3.04k
        wire::check_slice_len(slice, table_bytes_len, "start ID table")?;
4067
2.99k
        wire::check_alignment::<StateID>(slice)?;
4068
2.99k
        let table_bytes = &slice[..table_bytes_len];
4069
2.99k
        slice = &slice[table_bytes_len..];
4070
        // SAFETY: Since StateID is always representable as a u32, all we need
4071
        // to do is ensure that we have the proper length and alignment. We've
4072
        // checked both above, so the cast below is safe.
4073
        //
4074
        // N.B. This is the only not-safe code in this function.
4075
2.99k
        let table = core::slice::from_raw_parts(
4076
2.99k
            table_bytes.as_ptr().cast::<u32>(),
4077
2.99k
            start_state_len,
4078
        );
4079
2.99k
        let st = StartTable {
4080
2.99k
            table,
4081
2.99k
            kind,
4082
2.99k
            start_map,
4083
2.99k
            stride,
4084
2.99k
            pattern_len,
4085
2.99k
            universal_start_unanchored,
4086
2.99k
            universal_start_anchored,
4087
2.99k
        };
4088
2.99k
        Ok((st, slice.as_ptr().as_usize() - slice_start))
4089
3.37k
    }
4090
}
4091
4092
impl<T: AsRef<[u32]>> StartTable<T> {
4093
    /// Writes a serialized form of this start table to the buffer given. If
4094
    /// the buffer is too small, then an error is returned. To determine how
4095
    /// big the buffer must be, use `write_to_len`.
4096
    fn write_to<E: Endian>(
4097
        &self,
4098
        mut dst: &mut [u8],
4099
    ) -> Result<usize, SerializeError> {
4100
        let nwrite = self.write_to_len();
4101
        if dst.len() < nwrite {
4102
            return Err(SerializeError::buffer_too_small(
4103
                "starting table ids",
4104
            ));
4105
        }
4106
        dst = &mut dst[..nwrite];
4107
4108
        // write start kind
4109
        let nw = self.kind.write_to::<E>(dst)?;
4110
        dst = &mut dst[nw..];
4111
        // write start byte map
4112
        let nw = self.start_map.write_to(dst)?;
4113
        dst = &mut dst[nw..];
4114
        // write stride
4115
        // Unwrap is OK since the stride is always 4 (currently).
4116
        E::write_u32(u32::try_from(self.stride).unwrap(), dst);
4117
        dst = &mut dst[size_of::<u32>()..];
4118
        // write pattern length
4119
        // Unwrap is OK since number of patterns is guaranteed to fit in a u32.
4120
        E::write_u32(
4121
            u32::try_from(self.pattern_len.unwrap_or(0xFFFF_FFFF)).unwrap(),
4122
            dst,
4123
        );
4124
        dst = &mut dst[size_of::<u32>()..];
4125
        // write universal start unanchored state id, u32::MAX if absent
4126
        E::write_u32(
4127
            self.universal_start_unanchored
4128
                .map_or(u32::MAX, |sid| sid.as_u32()),
4129
            dst,
4130
        );
4131
        dst = &mut dst[size_of::<u32>()..];
4132
        // write universal start anchored state id, u32::MAX if absent
4133
        E::write_u32(
4134
            self.universal_start_anchored.map_or(u32::MAX, |sid| sid.as_u32()),
4135
            dst,
4136
        );
4137
        dst = &mut dst[size_of::<u32>()..];
4138
        // write start IDs
4139
        for &sid in self.table() {
4140
            let n = wire::write_state_id::<E>(sid, &mut dst);
4141
            dst = &mut dst[n..];
4142
        }
4143
        Ok(nwrite)
4144
    }
4145
4146
    /// Returns the number of bytes the serialized form of this start ID table
4147
    /// will use.
4148
    fn write_to_len(&self) -> usize {
4149
        self.kind.write_to_len()
4150
        + self.start_map.write_to_len()
4151
        + size_of::<u32>() // stride
4152
        + size_of::<u32>() // # patterns
4153
        + size_of::<u32>() // universal unanchored start
4154
        + size_of::<u32>() // universal anchored start
4155
        + (self.table().len() * StateID::SIZE)
4156
    }
4157
4158
    /// Validates that every state ID in this start table is valid by checking
4159
    /// it against the given transition table (which must be for the same DFA).
4160
    ///
4161
    /// That is, every state ID can be used to correctly index a state.
4162
2.18k
    fn validate(&self, dfa: &DFA<T>) -> Result<(), DeserializeError> {
4163
2.18k
        let tt = &dfa.tt;
4164
2.18k
        if !self.universal_start_unanchored.map_or(true, |s| tt.is_valid(s)) {
4165
21
            return Err(DeserializeError::generic(
4166
21
                "found invalid universal unanchored starting state ID",
4167
21
            ));
4168
2.16k
        }
4169
2.16k
        if !self.universal_start_anchored.map_or(true, |s| tt.is_valid(s)) {
4170
33
            return Err(DeserializeError::generic(
4171
33
                "found invalid universal anchored starting state ID",
4172
33
            ));
4173
2.12k
        }
4174
33.5k
        for &id in self.table() {
4175
33.5k
            if !tt.is_valid(id) {
4176
15
                return Err(DeserializeError::generic(
4177
15
                    "found invalid starting state ID",
4178
15
                ));
4179
33.5k
            }
4180
33.5k
            if dfa.special.is_match_state(id) {
4181
3
                return Err(DeserializeError::generic(
4182
3
                    "start states cannot be match states",
4183
3
                ));
4184
33.5k
            }
4185
        }
4186
2.11k
        Ok(())
4187
2.18k
    }
4188
4189
    /// Converts this start list to a borrowed value.
4190
80.2k
    fn as_ref(&self) -> StartTable<&'_ [u32]> {
4191
80.2k
        StartTable {
4192
80.2k
            table: self.table.as_ref(),
4193
80.2k
            kind: self.kind,
4194
80.2k
            start_map: self.start_map.clone(),
4195
80.2k
            stride: self.stride,
4196
80.2k
            pattern_len: self.pattern_len,
4197
80.2k
            universal_start_unanchored: self.universal_start_unanchored,
4198
80.2k
            universal_start_anchored: self.universal_start_anchored,
4199
80.2k
        }
4200
80.2k
    }
4201
4202
    /// Converts this start list to an owned value.
4203
    #[cfg(feature = "alloc")]
4204
    fn to_owned(&self) -> StartTable<alloc::vec::Vec<u32>> {
4205
        StartTable {
4206
            table: self.table.as_ref().to_vec(),
4207
            kind: self.kind,
4208
            start_map: self.start_map.clone(),
4209
            stride: self.stride,
4210
            pattern_len: self.pattern_len,
4211
            universal_start_unanchored: self.universal_start_unanchored,
4212
            universal_start_anchored: self.universal_start_anchored,
4213
        }
4214
    }
4215
4216
    /// Return the start state for the given input and starting configuration.
4217
    /// This returns an error if the input configuration is not supported by
4218
    /// this DFA. For example, requesting an unanchored search when the DFA was
4219
    /// not built with unanchored starting states. Or asking for an anchored
4220
    /// pattern search with an invalid pattern ID or on a DFA that was not
4221
    /// built with start states for each pattern.
4222
    #[cfg_attr(feature = "perf-inline", inline(always))]
4223
949k
    fn start(
4224
949k
        &self,
4225
949k
        anchored: Anchored,
4226
949k
        start: Start,
4227
949k
    ) -> Result<StateID, StartError> {
4228
949k
        let start_index = start.as_usize();
4229
949k
        let index = match anchored {
4230
            Anchored::No => {
4231
321k
                if !self.kind.has_unanchored() {
4232
109
                    return Err(StartError::unsupported_anchored(anchored));
4233
321k
                }
4234
321k
                start_index
4235
            }
4236
            Anchored::Yes => {
4237
618k
                if !self.kind.has_anchored() {
4238
0
                    return Err(StartError::unsupported_anchored(anchored));
4239
618k
                }
4240
618k
                self.stride + start_index
4241
            }
4242
9.94k
            Anchored::Pattern(pid) => {
4243
9.94k
                let len = match self.pattern_len {
4244
                    None => {
4245
0
                        return Err(StartError::unsupported_anchored(anchored))
4246
                    }
4247
9.94k
                    Some(len) => len,
4248
                };
4249
9.94k
                if pid.as_usize() >= len {
4250
0
                    return Ok(DEAD);
4251
9.94k
                }
4252
9.94k
                (2 * self.stride)
4253
9.94k
                    + (self.stride * pid.as_usize())
4254
9.94k
                    + start_index
4255
            }
4256
        };
4257
949k
        Ok(self.table()[index])
4258
949k
    }
<regex_automata::dfa::dense::StartTable<alloc::vec::Vec<u32>>>::start
Line
Count
Source
4223
931k
    fn start(
4224
931k
        &self,
4225
931k
        anchored: Anchored,
4226
931k
        start: Start,
4227
931k
    ) -> Result<StateID, StartError> {
4228
931k
        let start_index = start.as_usize();
4229
931k
        let index = match anchored {
4230
            Anchored::No => {
4231
303k
                if !self.kind.has_unanchored() {
4232
0
                    return Err(StartError::unsupported_anchored(anchored));
4233
303k
                }
4234
303k
                start_index
4235
            }
4236
            Anchored::Yes => {
4237
618k
                if !self.kind.has_anchored() {
4238
0
                    return Err(StartError::unsupported_anchored(anchored));
4239
618k
                }
4240
618k
                self.stride + start_index
4241
            }
4242
9.94k
            Anchored::Pattern(pid) => {
4243
9.94k
                let len = match self.pattern_len {
4244
                    None => {
4245
0
                        return Err(StartError::unsupported_anchored(anchored))
4246
                    }
4247
9.94k
                    Some(len) => len,
4248
                };
4249
9.94k
                if pid.as_usize() >= len {
4250
0
                    return Ok(DEAD);
4251
9.94k
                }
4252
9.94k
                (2 * self.stride)
4253
9.94k
                    + (self.stride * pid.as_usize())
4254
9.94k
                    + start_index
4255
            }
4256
        };
4257
931k
        Ok(self.table()[index])
4258
931k
    }
<regex_automata::dfa::dense::StartTable<&[u32]>>::start
Line
Count
Source
4223
17.4k
    fn start(
4224
17.4k
        &self,
4225
17.4k
        anchored: Anchored,
4226
17.4k
        start: Start,
4227
17.4k
    ) -> Result<StateID, StartError> {
4228
17.4k
        let start_index = start.as_usize();
4229
17.4k
        let index = match anchored {
4230
            Anchored::No => {
4231
17.4k
                if !self.kind.has_unanchored() {
4232
109
                    return Err(StartError::unsupported_anchored(anchored));
4233
17.3k
                }
4234
17.3k
                start_index
4235
            }
4236
            Anchored::Yes => {
4237
0
                if !self.kind.has_anchored() {
4238
0
                    return Err(StartError::unsupported_anchored(anchored));
4239
0
                }
4240
0
                self.stride + start_index
4241
            }
4242
0
            Anchored::Pattern(pid) => {
4243
0
                let len = match self.pattern_len {
4244
                    None => {
4245
0
                        return Err(StartError::unsupported_anchored(anchored))
4246
                    }
4247
0
                    Some(len) => len,
4248
                };
4249
0
                if pid.as_usize() >= len {
4250
0
                    return Ok(DEAD);
4251
0
                }
4252
0
                (2 * self.stride)
4253
0
                    + (self.stride * pid.as_usize())
4254
0
                    + start_index
4255
            }
4256
        };
4257
17.3k
        Ok(self.table()[index])
4258
17.4k
    }
4259
4260
    /// Returns an iterator over all start state IDs in this table.
4261
    ///
4262
    /// Each item is a triple of: start state ID, the start state type and the
4263
    /// pattern ID (if any).
4264
80.2k
    fn iter(&self) -> StartStateIter<'_> {
4265
80.2k
        StartStateIter { st: self.as_ref(), i: 0 }
4266
80.2k
    }
4267
4268
    /// Returns the table as a slice of state IDs.
4269
3.31M
    fn table(&self) -> &[StateID] {
4270
3.31M
        wire::u32s_to_state_ids(self.table.as_ref())
4271
3.31M
    }
<regex_automata::dfa::dense::StartTable<alloc::vec::Vec<u32>>>::table
Line
Count
Source
4269
1.78M
    fn table(&self) -> &[StateID] {
4270
1.78M
        wire::u32s_to_state_ids(self.table.as_ref())
4271
1.78M
    }
<regex_automata::dfa::dense::StartTable<&[u32]>>::table
Line
Count
Source
4269
1.50M
    fn table(&self) -> &[StateID] {
4270
1.50M
        wire::u32s_to_state_ids(self.table.as_ref())
4271
1.50M
    }
<regex_automata::dfa::dense::StartTable<&[u32]>>::table
Line
Count
Source
4269
17.3k
    fn table(&self) -> &[StateID] {
4270
17.3k
        wire::u32s_to_state_ids(self.table.as_ref())
4271
17.3k
    }
4272
4273
    /// Return the memory usage, in bytes, of this start list.
4274
    ///
4275
    /// This does not include the size of a `StartList` value itself.
4276
852k
    fn memory_usage(&self) -> usize {
4277
852k
        self.table().len() * StateID::SIZE
4278
852k
    }
4279
}
4280
4281
#[cfg(feature = "dfa-build")]
4282
impl<T: AsMut<[u32]>> StartTable<T> {
4283
    /// Set the start state for the given index and pattern.
4284
    ///
4285
    /// If the pattern ID or state ID are not valid, then this will panic.
4286
1.20M
    fn set_start(&mut self, anchored: Anchored, start: Start, id: StateID) {
4287
1.20M
        let start_index = start.as_usize();
4288
1.20M
        let index = match anchored {
4289
242k
            Anchored::No => start_index,
4290
492k
            Anchored::Yes => self.stride + start_index,
4291
474k
            Anchored::Pattern(pid) => {
4292
474k
                let pid = pid.as_usize();
4293
474k
                let len = self
4294
474k
                    .pattern_len
4295
474k
                    .expect("start states for each pattern enabled");
4296
474k
                assert!(pid < len, "invalid pattern ID {pid:?}");
4297
474k
                self.stride
4298
474k
                    .checked_mul(pid)
4299
474k
                    .unwrap()
4300
474k
                    .checked_add(self.stride.checked_mul(2).unwrap())
4301
474k
                    .unwrap()
4302
474k
                    .checked_add(start_index)
4303
474k
                    .unwrap()
4304
            }
4305
        };
4306
1.20M
        self.table_mut()[index] = id;
4307
1.20M
    }
4308
4309
    /// Returns the table as a mutable slice of state IDs.
4310
1.29M
    fn table_mut(&mut self) -> &mut [StateID] {
4311
1.29M
        wire::u32s_to_state_ids_mut(self.table.as_mut())
4312
1.29M
    }
4313
}
4314
4315
/// An iterator over start state IDs.
4316
///
4317
/// This iterator yields a triple of start state ID, the anchored mode and the
4318
/// start state type. If a pattern ID is relevant, then the anchored mode will
4319
/// contain it. Start states with an anchored mode containing a pattern ID will
4320
/// only occur when the DFA was compiled with start states for each pattern
4321
/// (which is disabled by default).
4322
pub(crate) struct StartStateIter<'a> {
4323
    st: StartTable<&'a [u32]>,
4324
    i: usize,
4325
}
4326
4327
impl<'a> Iterator for StartStateIter<'a> {
4328
    type Item = (StateID, Anchored, Start);
4329
4330
1.50M
    fn next(&mut self) -> Option<(StateID, Anchored, Start)> {
4331
1.50M
        let i = self.i;
4332
1.50M
        let table = self.st.table();
4333
1.50M
        if i >= table.len() {
4334
80.2k
            return None;
4335
1.42M
        }
4336
1.42M
        self.i += 1;
4337
4338
        // This unwrap is okay since the stride of the starting state table
4339
        // must always match the number of start state types.
4340
1.42M
        let start_type = Start::from_usize(i % self.st.stride).unwrap();
4341
1.42M
        let anchored = if i < self.st.stride {
4342
481k
            Anchored::No
4343
945k
        } else if i < (2 * self.st.stride) {
4344
481k
            Anchored::Yes
4345
        } else {
4346
463k
            let pid = (i - (2 * self.st.stride)) / self.st.stride;
4347
463k
            Anchored::Pattern(PatternID::new(pid).unwrap())
4348
        };
4349
1.42M
        Some((table[i], anchored, start_type))
4350
1.50M
    }
4351
}
4352
4353
/// This type represents that patterns that should be reported whenever a DFA
4354
/// enters a match state. This structure exists to support DFAs that search for
4355
/// matches for multiple regexes.
4356
///
4357
/// This structure relies on the fact that all match states in a DFA occur
4358
/// contiguously in the DFA's transition table. (See dfa/special.rs for a more
4359
/// detailed breakdown of the representation.) Namely, when a match occurs, we
4360
/// know its state ID. Since we know the start and end of the contiguous region
4361
/// of match states, we can use that to compute the position at which the match
4362
/// state occurs. That in turn is used as an offset into this structure.
4363
#[derive(Clone, Debug)]
4364
struct MatchStates<T> {
4365
    /// Slices is a flattened sequence of pairs, where each pair points to a
4366
    /// sub-slice of pattern_ids. The first element of the pair is an offset
4367
    /// into pattern_ids and the second element of the pair is the number
4368
    /// of 32-bit pattern IDs starting at that position. That is, each pair
4369
    /// corresponds to a single DFA match state and its corresponding match
4370
    /// IDs. The number of pairs always corresponds to the number of distinct
4371
    /// DFA match states.
4372
    ///
4373
    /// In practice, T is either Vec<u32> or &[u32].
4374
    slices: T,
4375
    /// A flattened sequence of pattern IDs for each DFA match state. The only
4376
    /// way to correctly read this sequence is indirectly via `slices`.
4377
    ///
4378
    /// In practice, T is either Vec<u32> or &[u32].
4379
    pattern_ids: T,
4380
    /// The total number of unique patterns represented by these match states.
4381
    pattern_len: usize,
4382
}
4383
4384
impl<'a> MatchStates<&'a [u32]> {
4385
2.99k
    unsafe fn from_bytes_unchecked(
4386
2.99k
        mut slice: &'a [u8],
4387
2.99k
    ) -> Result<(MatchStates<&'a [u32]>, usize), DeserializeError> {
4388
2.99k
        let slice_start = slice.as_ptr().as_usize();
4389
4390
        // Read the total number of match states.
4391
2.98k
        let (state_len, nr) =
4392
2.99k
            wire::try_read_u32_as_usize(slice, "match state length")?;
4393
2.98k
        slice = &slice[nr..];
4394
4395
        // Read the slice start/length pairs.
4396
2.98k
        let pair_len = wire::mul(2, state_len, "match state offset pairs")?;
4397
2.98k
        let slices_bytes_len = wire::mul(
4398
2.98k
            pair_len,
4399
            PatternID::SIZE,
4400
            "match state slice offset byte length",
4401
0
        )?;
4402
2.98k
        wire::check_slice_len(slice, slices_bytes_len, "match state slices")?;
4403
2.94k
        wire::check_alignment::<PatternID>(slice)?;
4404
2.94k
        let slices_bytes = &slice[..slices_bytes_len];
4405
2.94k
        slice = &slice[slices_bytes_len..];
4406
        // SAFETY: Since PatternID is always representable as a u32, all we
4407
        // need to do is ensure that we have the proper length and alignment.
4408
        // We've checked both above, so the cast below is safe.
4409
        //
4410
        // N.B. This is one of the few not-safe snippets in this function,
4411
        // so we mark it explicitly to call it out.
4412
2.94k
        let slices = core::slice::from_raw_parts(
4413
2.94k
            slices_bytes.as_ptr().cast::<u32>(),
4414
2.94k
            pair_len,
4415
        );
4416
4417
        // Read the total number of unique pattern IDs (which is always 1 more
4418
        // than the maximum pattern ID in this automaton, since pattern IDs are
4419
        // handed out contiguously starting at 0).
4420
2.93k
        let (pattern_len, nr) =
4421
2.94k
            wire::try_read_u32_as_usize(slice, "pattern length")?;
4422
2.93k
        slice = &slice[nr..];
4423
4424
        // Now read the pattern ID length. We don't need to store this
4425
        // explicitly, but we need it to know how many pattern IDs to read.
4426
2.93k
        let (idlen, nr) =
4427
2.93k
            wire::try_read_u32_as_usize(slice, "pattern ID length")?;
4428
2.93k
        slice = &slice[nr..];
4429
4430
        // Read the actual pattern IDs.
4431
2.93k
        let pattern_ids_len =
4432
2.93k
            wire::mul(idlen, PatternID::SIZE, "pattern ID byte length")?;
4433
2.93k
        wire::check_slice_len(slice, pattern_ids_len, "match pattern IDs")?;
4434
2.89k
        wire::check_alignment::<PatternID>(slice)?;
4435
2.89k
        let pattern_ids_bytes = &slice[..pattern_ids_len];
4436
2.89k
        slice = &slice[pattern_ids_len..];
4437
        // SAFETY: Since PatternID is always representable as a u32, all we
4438
        // need to do is ensure that we have the proper length and alignment.
4439
        // We've checked both above, so the cast below is safe.
4440
        //
4441
        // N.B. This is one of the few not-safe snippets in this function,
4442
        // so we mark it explicitly to call it out.
4443
2.89k
        let pattern_ids = core::slice::from_raw_parts(
4444
2.89k
            pattern_ids_bytes.as_ptr().cast::<u32>(),
4445
2.89k
            idlen,
4446
        );
4447
4448
2.89k
        let ms = MatchStates { slices, pattern_ids, pattern_len };
4449
2.89k
        Ok((ms, slice.as_ptr().as_usize() - slice_start))
4450
2.99k
    }
4451
}
4452
4453
#[cfg(feature = "dfa-build")]
4454
impl MatchStates<Vec<u32>> {
4455
169k
    fn empty(pattern_len: usize) -> MatchStates<Vec<u32>> {
4456
169k
        assert!(pattern_len <= PatternID::LIMIT);
4457
169k
        MatchStates { slices: vec![], pattern_ids: vec![], pattern_len }
4458
169k
    }
4459
4460
87.5k
    fn new(
4461
87.5k
        matches: &BTreeMap<StateID, Vec<PatternID>>,
4462
87.5k
        pattern_len: usize,
4463
87.5k
    ) -> Result<MatchStates<Vec<u32>>, BuildError> {
4464
87.5k
        let mut m = MatchStates::empty(pattern_len);
4465
131k
        for (_, pids) in matches.iter() {
4466
131k
            let start = PatternID::new(m.pattern_ids.len())
4467
131k
                .map_err(|_| BuildError::too_many_match_pattern_ids())?;
4468
131k
            m.slices.push(start.as_u32());
4469
            // This is always correct since the number of patterns in a single
4470
            // match state can never exceed maximum number of allowable
4471
            // patterns. Why? Because a pattern can only appear once in a
4472
            // particular match state, by construction. (And since our pattern
4473
            // ID limit is one less than u32::MAX, we're guaranteed that the
4474
            // length fits in a u32.)
4475
131k
            m.slices.push(u32::try_from(pids.len()).unwrap());
4476
263k
            for &pid in pids {
4477
131k
                m.pattern_ids.push(pid.as_u32());
4478
131k
            }
4479
        }
4480
87.5k
        m.pattern_len = pattern_len;
4481
87.5k
        Ok(m)
4482
87.5k
    }
4483
4484
87.5k
    fn new_with_map(
4485
87.5k
        &self,
4486
87.5k
        matches: &BTreeMap<StateID, Vec<PatternID>>,
4487
87.5k
    ) -> Result<MatchStates<Vec<u32>>, BuildError> {
4488
87.5k
        MatchStates::new(matches, self.pattern_len)
4489
87.5k
    }
4490
}
4491
4492
impl<T: AsRef<[u32]>> MatchStates<T> {
4493
    /// Writes a serialized form of these match states to the buffer given. If
4494
    /// the buffer is too small, then an error is returned. To determine how
4495
    /// big the buffer must be, use `write_to_len`.
4496
    fn write_to<E: Endian>(
4497
        &self,
4498
        mut dst: &mut [u8],
4499
    ) -> Result<usize, SerializeError> {
4500
        let nwrite = self.write_to_len();
4501
        if dst.len() < nwrite {
4502
            return Err(SerializeError::buffer_too_small("match states"));
4503
        }
4504
        dst = &mut dst[..nwrite];
4505
4506
        // write state ID length
4507
        // Unwrap is OK since number of states is guaranteed to fit in a u32.
4508
        E::write_u32(u32::try_from(self.len()).unwrap(), dst);
4509
        dst = &mut dst[size_of::<u32>()..];
4510
4511
        // write slice offset pairs
4512
        for &pid in self.slices() {
4513
            let n = wire::write_pattern_id::<E>(pid, &mut dst);
4514
            dst = &mut dst[n..];
4515
        }
4516
4517
        // write unique pattern ID length
4518
        // Unwrap is OK since number of patterns is guaranteed to fit in a u32.
4519
        E::write_u32(u32::try_from(self.pattern_len).unwrap(), dst);
4520
        dst = &mut dst[size_of::<u32>()..];
4521
4522
        // write pattern ID length
4523
        // Unwrap is OK since we check at construction (and deserialization)
4524
        // that the number of patterns is representable as a u32.
4525
        E::write_u32(u32::try_from(self.pattern_ids().len()).unwrap(), dst);
4526
        dst = &mut dst[size_of::<u32>()..];
4527
4528
        // write pattern IDs
4529
        for &pid in self.pattern_ids() {
4530
            let n = wire::write_pattern_id::<E>(pid, &mut dst);
4531
            dst = &mut dst[n..];
4532
        }
4533
4534
        Ok(nwrite)
4535
    }
4536
4537
    /// Returns the number of bytes the serialized form of these match states
4538
    /// will use.
4539
    fn write_to_len(&self) -> usize {
4540
        size_of::<u32>()   // match state length
4541
        + (self.slices().len() * PatternID::SIZE)
4542
        + size_of::<u32>() // unique pattern ID length
4543
        + size_of::<u32>() // pattern ID length
4544
        + (self.pattern_ids().len() * PatternID::SIZE)
4545
    }
4546
4547
    /// Validates that the match state info is itself internally consistent and
4548
    /// consistent with the recorded match state region in the given DFA.
4549
2.27k
    fn validate(&self, dfa: &DFA<T>) -> Result<(), DeserializeError> {
4550
2.27k
        if self.len() != dfa.special.match_len(dfa.stride()) {
4551
22
            return Err(DeserializeError::generic(
4552
22
                "match state length mismatch",
4553
22
            ));
4554
2.24k
        }
4555
2.24k
        for si in 0..self.len() {
4556
631
            let start = self.slices()[si * 2].as_usize();
4557
631
            let len = self.slices()[si * 2 + 1].as_usize();
4558
631
            if start >= self.pattern_ids().len() {
4559
1
                return Err(DeserializeError::generic(
4560
1
                    "invalid pattern ID start offset",
4561
1
                ));
4562
630
            }
4563
630
            if start + len > self.pattern_ids().len() {
4564
32
                return Err(DeserializeError::generic(
4565
32
                    "invalid pattern ID length",
4566
32
                ));
4567
598
            }
4568
2.78k
            for mi in 0..len {
4569
2.78k
                let pid = self.pattern_id(si, mi);
4570
2.78k
                if pid.as_usize() >= self.pattern_len {
4571
1
                    return Err(DeserializeError::generic(
4572
1
                        "invalid pattern ID",
4573
1
                    ));
4574
2.78k
                }
4575
            }
4576
        }
4577
2.21k
        Ok(())
4578
2.27k
    }
4579
4580
    /// Converts these match states back into their map form. This is useful
4581
    /// when shuffling states, as the normal MatchStates representation is not
4582
    /// amenable to easy state swapping. But with this map, to swap id1 and
4583
    /// id2, all you need to do is:
4584
    ///
4585
    /// if let Some(pids) = map.remove(&id1) {
4586
    ///     map.insert(id2, pids);
4587
    /// }
4588
    ///
4589
    /// Once shuffling is done, use MatchStates::new to convert back.
4590
    #[cfg(feature = "dfa-build")]
4591
7.25k
    fn to_map(&self, dfa: &DFA<T>) -> BTreeMap<StateID, Vec<PatternID>> {
4592
7.25k
        let mut map = BTreeMap::new();
4593
21.8k
        for i in 0..self.len() {
4594
21.8k
            let mut pids = vec![];
4595
21.8k
            for j in 0..self.pattern_len(i) {
4596
21.8k
                pids.push(self.pattern_id(i, j));
4597
21.8k
            }
4598
21.8k
            map.insert(self.match_state_id(dfa, i), pids);
4599
        }
4600
7.25k
        map
4601
7.25k
    }
4602
4603
    /// Converts these match states to a borrowed value.
4604
    fn as_ref(&self) -> MatchStates<&'_ [u32]> {
4605
        MatchStates {
4606
            slices: self.slices.as_ref(),
4607
            pattern_ids: self.pattern_ids.as_ref(),
4608
            pattern_len: self.pattern_len,
4609
        }
4610
    }
4611
4612
    /// Converts these match states to an owned value.
4613
    #[cfg(feature = "alloc")]
4614
    fn to_owned(&self) -> MatchStates<alloc::vec::Vec<u32>> {
4615
        MatchStates {
4616
            slices: self.slices.as_ref().to_vec(),
4617
            pattern_ids: self.pattern_ids.as_ref().to_vec(),
4618
            pattern_len: self.pattern_len,
4619
        }
4620
    }
4621
4622
    /// Returns the match state ID given the match state index. (Where the
4623
    /// first match state corresponds to index 0.)
4624
    ///
4625
    /// This panics if there is no match state at the given index.
4626
21.8k
    fn match_state_id(&self, dfa: &DFA<T>, index: usize) -> StateID {
4627
21.8k
        assert!(dfa.special.matches(), "no match states to index");
4628
        // This is one of the places where we rely on the fact that match
4629
        // states are contiguous in the transition table. Namely, that the
4630
        // first match state ID always corresponds to dfa.special.min_start.
4631
        // From there, since we know the stride, we can compute the ID of any
4632
        // match state given its index.
4633
21.8k
        let stride2 = u32::try_from(dfa.stride2()).unwrap();
4634
21.8k
        let offset = index.checked_shl(stride2).unwrap();
4635
21.8k
        let id = dfa.special.min_match.as_usize().checked_add(offset).unwrap();
4636
21.8k
        let sid = StateID::new(id).unwrap();
4637
21.8k
        assert!(dfa.is_match_state(sid));
4638
21.8k
        sid
4639
21.8k
    }
4640
4641
    /// Returns the pattern ID at the given match index for the given match
4642
    /// state.
4643
    ///
4644
    /// The match state index is the state index minus the state index of the
4645
    /// first match state in the DFA.
4646
    ///
4647
    /// The match index is the index of the pattern ID for the given state.
4648
    /// The index must be less than `self.pattern_len(state_index)`.
4649
    #[cfg_attr(feature = "perf-inline", inline(always))]
4650
148k
    fn pattern_id(&self, state_index: usize, match_index: usize) -> PatternID {
4651
148k
        self.pattern_id_slice(state_index)[match_index]
4652
148k
    }
<regex_automata::dfa::dense::MatchStates<alloc::vec::Vec<u32>>>::pattern_id
Line
Count
Source
4650
21.8k
    fn pattern_id(&self, state_index: usize, match_index: usize) -> PatternID {
4651
21.8k
        self.pattern_id_slice(state_index)[match_index]
4652
21.8k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::pattern_id
Line
Count
Source
4650
2.78k
    fn pattern_id(&self, state_index: usize, match_index: usize) -> PatternID {
4651
2.78k
        self.pattern_id_slice(state_index)[match_index]
4652
2.78k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::pattern_id
Line
Count
Source
4650
124k
    fn pattern_id(&self, state_index: usize, match_index: usize) -> PatternID {
4651
124k
        self.pattern_id_slice(state_index)[match_index]
4652
124k
    }
4653
4654
    /// Returns the number of patterns in the given match state.
4655
    ///
4656
    /// The match state index is the state index minus the state index of the
4657
    /// first match state in the DFA.
4658
    #[cfg_attr(feature = "perf-inline", inline(always))]
4659
171k
    fn pattern_len(&self, state_index: usize) -> usize {
4660
171k
        self.slices()[state_index * 2 + 1].as_usize()
4661
171k
    }
<regex_automata::dfa::dense::MatchStates<alloc::vec::Vec<u32>>>::pattern_len
Line
Count
Source
4659
43.6k
    fn pattern_len(&self, state_index: usize) -> usize {
4660
43.6k
        self.slices()[state_index * 2 + 1].as_usize()
4661
43.6k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::pattern_len
Line
Count
Source
4659
3.36k
    fn pattern_len(&self, state_index: usize) -> usize {
4660
3.36k
        self.slices()[state_index * 2 + 1].as_usize()
4661
3.36k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::pattern_len
Line
Count
Source
4659
124k
    fn pattern_len(&self, state_index: usize) -> usize {
4660
124k
        self.slices()[state_index * 2 + 1].as_usize()
4661
124k
    }
4662
4663
    /// Returns all of the pattern IDs for the given match state index.
4664
    ///
4665
    /// The match state index is the state index minus the state index of the
4666
    /// first match state in the DFA.
4667
    #[cfg_attr(feature = "perf-inline", inline(always))]
4668
148k
    fn pattern_id_slice(&self, state_index: usize) -> &[PatternID] {
4669
148k
        let start = self.slices()[state_index * 2].as_usize();
4670
148k
        let len = self.pattern_len(state_index);
4671
148k
        &self.pattern_ids()[start..start + len]
4672
148k
    }
<regex_automata::dfa::dense::MatchStates<alloc::vec::Vec<u32>>>::pattern_id_slice
Line
Count
Source
4668
21.8k
    fn pattern_id_slice(&self, state_index: usize) -> &[PatternID] {
4669
21.8k
        let start = self.slices()[state_index * 2].as_usize();
4670
21.8k
        let len = self.pattern_len(state_index);
4671
21.8k
        &self.pattern_ids()[start..start + len]
4672
21.8k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::pattern_id_slice
Line
Count
Source
4668
2.78k
    fn pattern_id_slice(&self, state_index: usize) -> &[PatternID] {
4669
2.78k
        let start = self.slices()[state_index * 2].as_usize();
4670
2.78k
        let len = self.pattern_len(state_index);
4671
2.78k
        &self.pattern_ids()[start..start + len]
4672
2.78k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::pattern_id_slice
Line
Count
Source
4668
124k
    fn pattern_id_slice(&self, state_index: usize) -> &[PatternID] {
4669
124k
        let start = self.slices()[state_index * 2].as_usize();
4670
124k
        let len = self.pattern_len(state_index);
4671
124k
        &self.pattern_ids()[start..start + len]
4672
124k
    }
4673
4674
    /// Returns the pattern ID offset slice of u32 as a slice of PatternID.
4675
    #[cfg_attr(feature = "perf-inline", inline(always))]
4676
1.19M
    fn slices(&self) -> &[PatternID] {
4677
1.19M
        wire::u32s_to_pattern_ids(self.slices.as_ref())
4678
1.19M
    }
<regex_automata::dfa::dense::MatchStates<alloc::vec::Vec<u32>>>::slices
Line
Count
Source
4676
932k
    fn slices(&self) -> &[PatternID] {
4677
932k
        wire::u32s_to_pattern_ids(self.slices.as_ref())
4678
932k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::slices
Line
Count
Source
4676
16.4k
    fn slices(&self) -> &[PatternID] {
4677
16.4k
        wire::u32s_to_pattern_ids(self.slices.as_ref())
4678
16.4k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::slices
Line
Count
Source
4676
248k
    fn slices(&self) -> &[PatternID] {
4677
248k
        wire::u32s_to_pattern_ids(self.slices.as_ref())
4678
248k
    }
4679
4680
    /// Returns the total number of match states.
4681
    #[cfg_attr(feature = "perf-inline", inline(always))]
4682
11.7k
    fn len(&self) -> usize {
4683
11.7k
        assert_eq!(0, self.slices().len() % 2);
4684
11.7k
        self.slices().len() / 2
4685
11.7k
    }
<regex_automata::dfa::dense::MatchStates<alloc::vec::Vec<u32>>>::len
Line
Count
Source
4682
7.25k
    fn len(&self) -> usize {
4683
7.25k
        assert_eq!(0, self.slices().len() % 2);
4684
7.25k
        self.slices().len() / 2
4685
7.25k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::len
Line
Count
Source
4682
4.52k
    fn len(&self) -> usize {
4683
4.52k
        assert_eq!(0, self.slices().len() % 2);
4684
4.52k
        self.slices().len() / 2
4685
4.52k
    }
4686
4687
    /// Returns the pattern ID slice of u32 as a slice of PatternID.
4688
    #[cfg_attr(feature = "perf-inline", inline(always))]
4689
1.00M
    fn pattern_ids(&self) -> &[PatternID] {
4690
1.00M
        wire::u32s_to_pattern_ids(self.pattern_ids.as_ref())
4691
1.00M
    }
<regex_automata::dfa::dense::MatchStates<alloc::vec::Vec<u32>>>::pattern_ids
Line
Count
Source
4689
874k
    fn pattern_ids(&self) -> &[PatternID] {
4690
874k
        wire::u32s_to_pattern_ids(self.pattern_ids.as_ref())
4691
874k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::pattern_ids
Line
Count
Source
4689
4.04k
    fn pattern_ids(&self) -> &[PatternID] {
4690
4.04k
        wire::u32s_to_pattern_ids(self.pattern_ids.as_ref())
4691
4.04k
    }
<regex_automata::dfa::dense::MatchStates<&[u32]>>::pattern_ids
Line
Count
Source
4689
124k
    fn pattern_ids(&self) -> &[PatternID] {
4690
124k
        wire::u32s_to_pattern_ids(self.pattern_ids.as_ref())
4691
124k
    }
4692
4693
    /// Return the memory usage, in bytes, of these match pairs.
4694
852k
    fn memory_usage(&self) -> usize {
4695
852k
        (self.slices().len() + self.pattern_ids().len()) * PatternID::SIZE
4696
852k
    }
4697
}
4698
4699
/// A common set of flags for both dense and sparse DFAs. This primarily
4700
/// centralizes the serialization format of these flags at a bitset.
4701
#[derive(Clone, Copy, Debug)]
4702
pub(crate) struct Flags {
4703
    /// Whether the DFA can match the empty string. When this is false, all
4704
    /// matches returned by this DFA are guaranteed to have non-zero length.
4705
    pub(crate) has_empty: bool,
4706
    /// Whether the DFA should only produce matches with spans that correspond
4707
    /// to valid UTF-8. This also includes omitting any zero-width matches that
4708
    /// split the UTF-8 encoding of a codepoint.
4709
    pub(crate) is_utf8: bool,
4710
    /// Whether the DFA is always anchored or not, regardless of `Input`
4711
    /// configuration. This is useful for avoiding a reverse scan even when
4712
    /// executing unanchored searches.
4713
    pub(crate) is_always_start_anchored: bool,
4714
}
4715
4716
impl Flags {
4717
    /// Creates a set of flags for a DFA from an NFA.
4718
    ///
4719
    /// N.B. This constructor was defined at the time of writing because all
4720
    /// of the flags are derived directly from the NFA. If this changes in the
4721
    /// future, we might be more thoughtful about how the `Flags` value is
4722
    /// itself built.
4723
    #[cfg(feature = "dfa-build")]
4724
82.1k
    fn from_nfa(nfa: &thompson::NFA) -> Flags {
4725
82.1k
        Flags {
4726
82.1k
            has_empty: nfa.has_empty(),
4727
82.1k
            is_utf8: nfa.is_utf8(),
4728
82.1k
            is_always_start_anchored: nfa.is_always_start_anchored(),
4729
82.1k
        }
4730
82.1k
    }
4731
4732
    /// Deserializes the flags from the given slice. On success, this also
4733
    /// returns the number of bytes read from the slice.
4734
6.49k
    pub(crate) fn from_bytes(
4735
6.49k
        slice: &[u8],
4736
6.49k
    ) -> Result<(Flags, usize), DeserializeError> {
4737
6.49k
        let (bits, nread) = wire::try_read_u32(slice, "flag bitset")?;
4738
6.48k
        let flags = Flags {
4739
6.48k
            has_empty: bits & (1 << 0) != 0,
4740
6.48k
            is_utf8: bits & (1 << 1) != 0,
4741
6.48k
            is_always_start_anchored: bits & (1 << 2) != 0,
4742
6.48k
        };
4743
6.48k
        Ok((flags, nread))
4744
6.49k
    }
4745
4746
    /// Writes these flags to the given byte slice. If the buffer is too small,
4747
    /// then an error is returned. To determine how big the buffer must be,
4748
    /// use `write_to_len`.
4749
    pub(crate) fn write_to<E: Endian>(
4750
        &self,
4751
        dst: &mut [u8],
4752
    ) -> Result<usize, SerializeError> {
4753
0
        fn bool_to_int(b: bool) -> u32 {
4754
0
            if b {
4755
0
                1
4756
            } else {
4757
0
                0
4758
            }
4759
0
        }
4760
4761
        let nwrite = self.write_to_len();
4762
        if dst.len() < nwrite {
4763
            return Err(SerializeError::buffer_too_small("flag bitset"));
4764
        }
4765
        let bits = (bool_to_int(self.has_empty) << 0)
4766
            | (bool_to_int(self.is_utf8) << 1)
4767
            | (bool_to_int(self.is_always_start_anchored) << 2);
4768
        E::write_u32(bits, dst);
4769
        Ok(nwrite)
4770
    }
4771
4772
    /// Returns the number of bytes the serialized form of these flags
4773
    /// will use.
4774
0
    pub(crate) fn write_to_len(&self) -> usize {
4775
0
        size_of::<u32>()
4776
0
    }
4777
}
4778
4779
/// An iterator over all states in a DFA.
4780
///
4781
/// This iterator yields a tuple for each state. The first element of the
4782
/// tuple corresponds to a state's identifier, and the second element
4783
/// corresponds to the state itself (comprised of its transitions).
4784
///
4785
/// `'a` corresponding to the lifetime of original DFA, `T` corresponds to
4786
/// the type of the transition table itself.
4787
pub(crate) struct StateIter<'a, T> {
4788
    tt: &'a TransitionTable<T>,
4789
    it: iter::Enumerate<slice::Chunks<'a, StateID>>,
4790
}
4791
4792
impl<'a, T: AsRef<[u32]>> Iterator for StateIter<'a, T> {
4793
    type Item = State<'a>;
4794
4795
2.48M
    fn next(&mut self) -> Option<State<'a>> {
4796
2.48M
        self.it.next().map(|(index, _)| {
4797
2.40M
            let id = self.tt.to_state_id(index);
4798
2.40M
            self.tt.state(id)
4799
2.40M
        })
<regex_automata::dfa::dense::StateIter<alloc::vec::Vec<u32>> as core::iter::traits::iterator::Iterator>::next::{closure#0}
Line
Count
Source
4796
910k
        self.it.next().map(|(index, _)| {
4797
910k
            let id = self.tt.to_state_id(index);
4798
910k
            self.tt.state(id)
4799
910k
        })
<regex_automata::dfa::dense::StateIter<&[u32]> as core::iter::traits::iterator::Iterator>::next::{closure#0}
Line
Count
Source
4796
1.49M
        self.it.next().map(|(index, _)| {
4797
1.49M
            let id = self.tt.to_state_id(index);
4798
1.49M
            self.tt.state(id)
4799
1.49M
        })
4800
2.48M
    }
<regex_automata::dfa::dense::StateIter<alloc::vec::Vec<u32>> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
4795
987k
    fn next(&mut self) -> Option<State<'a>> {
4796
987k
        self.it.next().map(|(index, _)| {
4797
            let id = self.tt.to_state_id(index);
4798
            self.tt.state(id)
4799
        })
4800
987k
    }
<regex_automata::dfa::dense::StateIter<&[u32]> as core::iter::traits::iterator::Iterator>::next
Line
Count
Source
4795
1.49M
    fn next(&mut self) -> Option<State<'a>> {
4796
1.49M
        self.it.next().map(|(index, _)| {
4797
            let id = self.tt.to_state_id(index);
4798
            self.tt.state(id)
4799
        })
4800
1.49M
    }
4801
}
4802
4803
/// An immutable representation of a single DFA state.
4804
///
4805
/// `'a` corresponding to the lifetime of a DFA's transition table.
4806
pub(crate) struct State<'a> {
4807
    id: StateID,
4808
    stride2: usize,
4809
    transitions: &'a [StateID],
4810
}
4811
4812
impl<'a> State<'a> {
4813
    /// Return an iterator over all transitions in this state. This yields
4814
    /// a number of transitions equivalent to the alphabet length of the
4815
    /// corresponding DFA.
4816
    ///
4817
    /// Each transition is represented by a tuple. The first element is
4818
    /// the input byte for that transition and the second element is the
4819
    /// transitions itself.
4820
1.65M
    pub(crate) fn transitions(&self) -> StateTransitionIter<'_> {
4821
1.65M
        StateTransitionIter {
4822
1.65M
            len: self.transitions.len(),
4823
1.65M
            it: self.transitions.iter().enumerate(),
4824
1.65M
        }
4825
1.65M
    }
4826
4827
    /// Return an iterator over a sparse representation of the transitions in
4828
    /// this state. Only non-dead transitions are returned.
4829
    ///
4830
    /// The "sparse" representation in this case corresponds to a sequence of
4831
    /// triples. The first two elements of the triple comprise an inclusive
4832
    /// byte range while the last element corresponds to the transition taken
4833
    /// for all bytes in the range.
4834
    ///
4835
    /// This is somewhat more condensed than the classical sparse
4836
    /// representation (where you have an element for every non-dead
4837
    /// transition), but in practice, checking if a byte is in a range is very
4838
    /// cheap and using ranges tends to conserve quite a bit more space.
4839
0
    pub(crate) fn sparse_transitions(&self) -> StateSparseTransitionIter<'_> {
4840
0
        StateSparseTransitionIter { dense: self.transitions(), cur: None }
4841
0
    }
4842
4843
    /// Returns the identifier for this state.
4844
4.20M
    pub(crate) fn id(&self) -> StateID {
4845
4.20M
        self.id
4846
4.20M
    }
4847
4848
    /// Analyzes this state to determine whether it can be accelerated. If so,
4849
    /// it returns an accelerator that contains at least one byte.
4850
    #[cfg(feature = "dfa-build")]
4851
910k
    fn accelerate(&self, classes: &ByteClasses) -> Option<Accel> {
4852
        // We just try to add bytes to our accelerator. Once adding fails
4853
        // (because we've added too many bytes), then give up.
4854
910k
        let mut accel = Accel::new();
4855
2.61M
        for (class, id) in self.transitions() {
4856
2.61M
            if id == self.id() {
4857
1.49M
                continue;
4858
1.12M
            }
4859
3.30M
            for unit in classes.elements(class) {
4860
3.30M
                if let Some(byte) = unit.as_u8() {
4861
3.29M
                    if !accel.add(byte) {
4862
817k
                        return None;
4863
2.47M
                    }
4864
15.3k
                }
4865
            }
4866
        }
4867
92.6k
        if accel.is_empty() {
4868
79.7k
            None
4869
        } else {
4870
12.9k
            Some(accel)
4871
        }
4872
910k
    }
4873
}
4874
4875
impl<'a> fmt::Debug for State<'a> {
4876
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4877
0
        for (i, (start, end, sid)) in self.sparse_transitions().enumerate() {
4878
0
            let id = if f.alternate() {
4879
0
                sid.as_usize()
4880
            } else {
4881
0
                sid.as_usize() >> self.stride2
4882
            };
4883
0
            if i > 0 {
4884
0
                write!(f, ", ")?;
4885
0
            }
4886
0
            if start == end {
4887
0
                write!(f, "{start:?} => {id:?}")?;
4888
            } else {
4889
0
                write!(f, "{start:?}-{end:?} => {id:?}")?;
4890
            }
4891
        }
4892
0
        Ok(())
4893
0
    }
4894
}
4895
4896
/// An iterator over all transitions in a single DFA state. This yields
4897
/// a number of transitions equivalent to the alphabet length of the
4898
/// corresponding DFA.
4899
///
4900
/// Each transition is represented by a tuple. The first element is the input
4901
/// byte for that transition and the second element is the transition itself.
4902
#[derive(Debug)]
4903
pub(crate) struct StateTransitionIter<'a> {
4904
    len: usize,
4905
    it: iter::Enumerate<slice::Iter<'a, StateID>>,
4906
}
4907
4908
impl<'a> Iterator for StateTransitionIter<'a> {
4909
    type Item = (alphabet::Unit, StateID);
4910
4911
4.96M
    fn next(&mut self) -> Option<(alphabet::Unit, StateID)> {
4912
4.96M
        self.it.next().map(|(i, &id)| {
4913
4.12M
            let unit = if i + 1 == self.len {
4914
840k
                alphabet::Unit::eoi(i)
4915
            } else {
4916
3.28M
                let b = u8::try_from(i)
4917
3.28M
                    .expect("raw byte alphabet is never exceeded");
4918
3.28M
                alphabet::Unit::u8(b)
4919
            };
4920
4.12M
            (unit, id)
4921
4.12M
        })
4922
4.96M
    }
4923
}
4924
4925
/// An iterator over all non-DEAD transitions in a single DFA state using a
4926
/// sparse representation.
4927
///
4928
/// Each transition is represented by a triple. The first two elements of the
4929
/// triple comprise an inclusive byte range while the last element corresponds
4930
/// to the transition taken for all bytes in the range.
4931
///
4932
/// As a convenience, this always returns `alphabet::Unit` values of the same
4933
/// type. That is, you'll never get a (byte, EOI) or a (EOI, byte). Only (byte,
4934
/// byte) and (EOI, EOI) values are yielded.
4935
#[derive(Debug)]
4936
pub(crate) struct StateSparseTransitionIter<'a> {
4937
    dense: StateTransitionIter<'a>,
4938
    cur: Option<(alphabet::Unit, alphabet::Unit, StateID)>,
4939
}
4940
4941
impl<'a> Iterator for StateSparseTransitionIter<'a> {
4942
    type Item = (alphabet::Unit, alphabet::Unit, StateID);
4943
4944
0
    fn next(&mut self) -> Option<(alphabet::Unit, alphabet::Unit, StateID)> {
4945
0
        while let Some((unit, next)) = self.dense.next() {
4946
0
            let (prev_start, prev_end, prev_next) = match self.cur {
4947
0
                Some(t) => t,
4948
                None => {
4949
0
                    self.cur = Some((unit, unit, next));
4950
0
                    continue;
4951
                }
4952
            };
4953
0
            if prev_next == next && !unit.is_eoi() {
4954
0
                self.cur = Some((prev_start, unit, prev_next));
4955
0
            } else {
4956
0
                self.cur = Some((unit, unit, next));
4957
0
                if prev_next != DEAD {
4958
0
                    return Some((prev_start, prev_end, prev_next));
4959
0
                }
4960
            }
4961
        }
4962
0
        if let Some((start, end, next)) = self.cur.take() {
4963
0
            if next != DEAD {
4964
0
                return Some((start, end, next));
4965
0
            }
4966
0
        }
4967
0
        None
4968
0
    }
4969
}
4970
4971
/// An error that occurred during the construction of a DFA.
4972
///
4973
/// This error does not provide many introspection capabilities. There are
4974
/// generally only two things you can do with it:
4975
///
4976
/// * Obtain a human readable message via its `std::fmt::Display` impl.
4977
/// * Access an underlying [`nfa::thompson::BuildError`](thompson::BuildError)
4978
/// type from its `source` method via the `std::error::Error` trait. This error
4979
/// only occurs when using convenience routines for building a DFA directly
4980
/// from a pattern string.
4981
///
4982
/// When the `std` feature is enabled, this implements the `std::error::Error`
4983
/// trait.
4984
#[cfg(feature = "dfa-build")]
4985
#[derive(Clone, Debug)]
4986
pub struct BuildError {
4987
    kind: BuildErrorKind,
4988
}
4989
4990
#[cfg(feature = "dfa-build")]
4991
impl BuildError {
4992
    /// Returns true if and only if this error corresponds to an error with DFA
4993
    /// construction that occurred because of exceeding a size limit.
4994
    ///
4995
    /// While this can occur when size limits like [`Config::dfa_size_limit`]
4996
    /// or [`Config::determinize_size_limit`] are exceeded, this can also occur
4997
    /// when the number of states or patterns exceeds a hard-coded maximum.
4998
    /// (Where these maximums are derived based on the values representable by
4999
    /// [`StateID`] and [`PatternID`].)
5000
    ///
5001
    /// This predicate is useful in contexts where you want to distinguish
5002
    /// between errors related to something provided by an end user (for
5003
    /// example, an invalid regex pattern) and errors related to configured
5004
    /// heuristics. For example, building a DFA might be an optimization that
5005
    /// you want to skip if construction fails because of an exceeded size
5006
    /// limit, but where you want to bubble up an error if it fails for some
5007
    /// other reason.
5008
    ///
5009
    /// # Example
5010
    ///
5011
    /// ```
5012
    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
5013
    /// # if !cfg!(target_pointer_width = "64") { return Ok(()); } // see #1039
5014
    /// use regex_automata::{dfa::{dense, Automaton}, Input};
5015
    ///
5016
    /// let err = dense::Builder::new()
5017
    ///     .configure(dense::Config::new()
5018
    ///         .determinize_size_limit(Some(100_000))
5019
    ///     )
5020
    ///     .build(r"\w{20}")
5021
    ///     .unwrap_err();
5022
    /// // This error occurs because a size limit was exceeded.
5023
    /// // But things are otherwise valid.
5024
    /// assert!(err.is_size_limit_exceeded());
5025
    ///
5026
    /// let err = dense::Builder::new()
5027
    ///     .build(r"\bxyz\b")
5028
    ///     .unwrap_err();
5029
    /// // This error occurs because a Unicode word boundary
5030
    /// // was used without enabling heuristic support for it.
5031
    /// // So... not related to size limits.
5032
    /// assert!(!err.is_size_limit_exceeded());
5033
    ///
5034
    /// let err = dense::Builder::new()
5035
    ///     .build(r"(xyz")
5036
    ///     .unwrap_err();
5037
    /// // This error occurs because the pattern is invalid.
5038
    /// // So... not related to size limits.
5039
    /// assert!(!err.is_size_limit_exceeded());
5040
    ///
5041
    /// # Ok::<(), Box<dyn std::error::Error>>(())
5042
    /// ```
5043
    #[inline]
5044
    pub fn is_size_limit_exceeded(&self) -> bool {
5045
        use self::BuildErrorKind::*;
5046
5047
        match self.kind {
5048
            NFA(_) | Unsupported(_) => false,
5049
            TooManyStates
5050
            | TooManyStartStates
5051
            | TooManyMatchPatternIDs
5052
            | DFAExceededSizeLimit { .. }
5053
            | DeterminizeExceededSizeLimit { .. } => true,
5054
        }
5055
    }
5056
}
5057
5058
/// The kind of error that occurred during the construction of a DFA.
5059
///
5060
/// Note that this error is non-exhaustive. Adding new variants is not
5061
/// considered a breaking change.
5062
#[cfg(feature = "dfa-build")]
5063
#[derive(Clone, Debug)]
5064
enum BuildErrorKind {
5065
    /// An error that occurred while constructing an NFA as a precursor step
5066
    /// before a DFA is compiled.
5067
    NFA(thompson::BuildError),
5068
    /// An error that occurred because an unsupported regex feature was used.
5069
    /// The message string describes which unsupported feature was used.
5070
    ///
5071
    /// The primary regex feature that is unsupported by DFAs is the Unicode
5072
    /// word boundary look-around assertion (`\b`). This can be worked around
5073
    /// by either using an ASCII word boundary (`(?-u:\b)`) or by enabling
5074
    /// Unicode word boundaries when building a DFA.
5075
    Unsupported(&'static str),
5076
    /// An error that occurs if too many states are produced while building a
5077
    /// DFA.
5078
    TooManyStates,
5079
    /// An error that occurs if too many start states are needed while building
5080
    /// a DFA.
5081
    ///
5082
    /// This is a kind of oddball error that occurs when building a DFA with
5083
    /// start states enabled for each pattern and enough patterns to cause
5084
    /// the table of start states to overflow `usize`.
5085
    TooManyStartStates,
5086
    /// This is another oddball error that can occur if there are too many
5087
    /// patterns spread out across too many match states.
5088
    TooManyMatchPatternIDs,
5089
    /// An error that occurs if the DFA got too big during determinization.
5090
    DFAExceededSizeLimit { limit: usize },
5091
    /// An error that occurs if auxiliary storage (not the DFA) used during
5092
    /// determinization got too big.
5093
    DeterminizeExceededSizeLimit { limit: usize },
5094
}
5095
5096
#[cfg(feature = "dfa-build")]
5097
impl BuildError {
5098
    /// Return the kind of this error.
5099
0
    fn kind(&self) -> &BuildErrorKind {
5100
0
        &self.kind
5101
0
    }
5102
5103
0
    pub(crate) fn nfa(err: thompson::BuildError) -> BuildError {
5104
0
        BuildError { kind: BuildErrorKind::NFA(err) }
5105
0
    }
5106
5107
0
    pub(crate) fn unsupported_dfa_word_boundary_unicode() -> BuildError {
5108
0
        let msg = "cannot build DFAs for regexes with Unicode word \
5109
0
                   boundaries; switch to ASCII word boundaries, or \
5110
0
                   heuristically enable Unicode word boundaries or use a \
5111
0
                   different regex engine";
5112
0
        BuildError { kind: BuildErrorKind::Unsupported(msg) }
5113
0
    }
5114
5115
0
    pub(crate) fn too_many_states() -> BuildError {
5116
0
        BuildError { kind: BuildErrorKind::TooManyStates }
5117
0
    }
5118
5119
0
    pub(crate) fn too_many_start_states() -> BuildError {
5120
0
        BuildError { kind: BuildErrorKind::TooManyStartStates }
5121
0
    }
5122
5123
0
    pub(crate) fn too_many_match_pattern_ids() -> BuildError {
5124
0
        BuildError { kind: BuildErrorKind::TooManyMatchPatternIDs }
5125
0
    }
5126
5127
1.76k
    pub(crate) fn dfa_exceeded_size_limit(limit: usize) -> BuildError {
5128
1.76k
        BuildError { kind: BuildErrorKind::DFAExceededSizeLimit { limit } }
5129
1.76k
    }
5130
5131
65
    pub(crate) fn determinize_exceeded_size_limit(limit: usize) -> BuildError {
5132
65
        BuildError {
5133
65
            kind: BuildErrorKind::DeterminizeExceededSizeLimit { limit },
5134
65
        }
5135
65
    }
5136
}
5137
5138
#[cfg(all(feature = "std", feature = "dfa-build"))]
5139
impl std::error::Error for BuildError {
5140
0
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
5141
0
        match self.kind() {
5142
0
            BuildErrorKind::NFA(ref err) => Some(err),
5143
0
            _ => None,
5144
        }
5145
0
    }
5146
}
5147
5148
#[cfg(feature = "dfa-build")]
5149
impl core::fmt::Display for BuildError {
5150
0
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
5151
0
        match self.kind() {
5152
0
            BuildErrorKind::NFA(_) => write!(f, "error building NFA"),
5153
0
            BuildErrorKind::Unsupported(ref msg) => {
5154
0
                write!(f, "unsupported regex feature for DFAs: {msg}")
5155
            }
5156
0
            BuildErrorKind::TooManyStates => write!(
5157
0
                f,
5158
0
                "number of DFA states exceeds limit of {}",
5159
                StateID::LIMIT,
5160
            ),
5161
            BuildErrorKind::TooManyStartStates => {
5162
0
                let stride = Start::len();
5163
                // The start table has `stride` entries for starting states for
5164
                // the entire DFA, and then `stride` entries for each pattern
5165
                // if start states for each pattern are enabled (which is the
5166
                // only way this error can occur). Thus, the total number of
5167
                // patterns that can fit in the table is `stride` less than
5168
                // what we can allocate.
5169
0
                let max = usize::try_from(core::isize::MAX).unwrap();
5170
0
                let limit = (max - stride) / stride;
5171
0
                write!(
5172
0
                    f,
5173
0
                    "compiling DFA with start states exceeds pattern \
5174
0
                     pattern limit of {}",
5175
                    limit,
5176
                )
5177
            }
5178
0
            BuildErrorKind::TooManyMatchPatternIDs => write!(
5179
0
                f,
5180
0
                "compiling DFA with total patterns in all match states \
5181
0
                 exceeds limit of {}",
5182
                PatternID::LIMIT,
5183
            ),
5184
0
            BuildErrorKind::DFAExceededSizeLimit { limit } => write!(
5185
0
                f,
5186
0
                "DFA exceeded size limit of {limit:?} during determinization",
5187
            ),
5188
0
            BuildErrorKind::DeterminizeExceededSizeLimit { limit } => {
5189
0
                write!(f, "determinization exceeded size limit of {limit:?}")
5190
            }
5191
        }
5192
0
    }
5193
}
5194
5195
#[cfg(all(test, feature = "syntax", feature = "dfa-build"))]
5196
mod tests {
5197
    use crate::{Input, MatchError};
5198
5199
    use super::*;
5200
5201
    #[test]
5202
    fn errors_with_unicode_word_boundary() {
5203
        let pattern = r"\b";
5204
        assert!(Builder::new().build(pattern).is_err());
5205
    }
5206
5207
    #[test]
5208
    fn roundtrip_never_match() {
5209
        let dfa = DFA::never_match().unwrap();
5210
        let (buf, _) = dfa.to_bytes_native_endian();
5211
        let dfa: DFA<&[u32]> = DFA::from_bytes(&buf).unwrap().0;
5212
5213
        assert_eq!(None, dfa.try_search_fwd(&Input::new("foo12345")).unwrap());
5214
    }
5215
5216
    #[test]
5217
    fn roundtrip_always_match() {
5218
        use crate::HalfMatch;
5219
5220
        let dfa = DFA::always_match().unwrap();
5221
        let (buf, _) = dfa.to_bytes_native_endian();
5222
        let dfa: DFA<&[u32]> = DFA::from_bytes(&buf).unwrap().0;
5223
5224
        assert_eq!(
5225
            Some(HalfMatch::must(0, 0)),
5226
            dfa.try_search_fwd(&Input::new("foo12345")).unwrap()
5227
        );
5228
    }
5229
5230
    // See the analogous test in src/hybrid/dfa.rs.
5231
    #[test]
5232
    fn heuristic_unicode_reverse() {
5233
        let dfa = DFA::builder()
5234
            .configure(DFA::config().unicode_word_boundary(true))
5235
            .thompson(thompson::Config::new().reverse(true))
5236
            .build(r"\b[0-9]+\b")
5237
            .unwrap();
5238
5239
        let input = Input::new("β123").range(2..);
5240
        let expected = MatchError::quit(0xB2, 1);
5241
        let got = dfa.try_search_rev(&input);
5242
        assert_eq!(Err(expected), got);
5243
5244
        let input = Input::new("123β").range(..3);
5245
        let expected = MatchError::quit(0xCE, 3);
5246
        let got = dfa.try_search_rev(&input);
5247
        assert_eq!(Err(expected), got);
5248
    }
5249
5250
    // This panics in `TransitionTable::validate` if the match states are not
5251
    // validated first.
5252
    //
5253
    // See: https://github.com/rust-lang/regex/pull/1295
5254
    #[test]
5255
    fn regression_validation_order() {
5256
        let mut dfa = DFA::new("abc").unwrap();
5257
        dfa.ms = MatchStates {
5258
            slices: vec![],
5259
            pattern_ids: vec![],
5260
            pattern_len: 1,
5261
        };
5262
        let (buf, _) = dfa.to_bytes_native_endian();
5263
        DFA::from_bytes(&buf).unwrap_err();
5264
    }
5265
5266
    // A starting state can never be a match state, since all matches are
5267
    // delayed by one byte. The search routines rely on this and assert it,
5268
    // so `from_bytes` must reject a serialized DFA whose start table points
5269
    // at a match state. The sparse DFA already rejected this; the dense DFA
5270
    // did not, so searching with such a DFA tripped the assertion in
5271
    // `dfa::search::init_fwd`.
5272
    #[test]
5273
    fn regression_start_state_not_match() {
5274
        let mut dfa = DFA::new("abc").unwrap();
5275
        let min_match = dfa.special.min_match;
5276
        for id in dfa.st.table_mut() {
5277
            *id = min_match;
5278
        }
5279
        let (buf, _) = dfa.to_bytes_native_endian();
5280
        DFA::from_bytes(&buf).unwrap_err();
5281
    }
5282
}