Skip to main content

regex_automata/meta/
regex.rs

1use core::{
2    borrow::Borrow,
3    panic::{RefUnwindSafe, UnwindSafe},
4};
5
6use alloc::{boxed::Box, sync::Arc, vec, vec::Vec};
7
8use regex_syntax::{
9    ast,
10    hir::{self, Hir},
11};
12
13use crate::{
14    meta::{
15        error::BuildError,
16        strategy::{self, Strategy},
17        wrappers,
18    },
19    nfa::thompson::{self, WhichCaptures},
20    util::{
21        captures::{Captures, GroupInfo},
22        iter,
23        look::LookMatcher,
24        pool::{Pool, PoolGuard},
25        prefilter::Prefilter,
26        primitives::{NonMaxUsize, PatternID},
27        search::{HalfMatch, Input, Match, MatchKind, PatternSet, Span},
28    },
29};
30
31/// A type alias for our pool of meta::Cache that fixes the type parameters to
32/// what we use for the meta regex below.
33type CachePool = Pool<Cache, CachePoolFn>;
34
35/// Same as above, but for the guard returned by a pool.
36type CachePoolGuard<'a> = PoolGuard<'a, Cache, CachePoolFn>;
37
38/// The type of the closure we use to create new caches. We need to spell out
39/// all of the marker traits or else we risk leaking !MARKER impls.
40type CachePoolFn =
41    Box<dyn Fn() -> Cache + Send + Sync + UnwindSafe + RefUnwindSafe>;
42
43/// A regex matcher that works by composing several other regex matchers
44/// automatically.
45///
46/// In effect, a meta regex papers over a lot of the quirks or performance
47/// problems in each of the regex engines in this crate. Its goal is to provide
48/// an infallible and simple API that "just does the right thing" in the common
49/// case.
50///
51/// A meta regex is the implementation of a `Regex` in the `regex` crate.
52/// Indeed, the `regex` crate API is essentially just a light wrapper over
53/// this type. This includes the `regex` crate's `RegexSet` API!
54///
55/// # Composition
56///
57/// This is called a "meta" matcher precisely because it uses other regex
58/// matchers to provide a convenient high level regex API. Here are some
59/// examples of how other regex matchers are composed:
60///
61/// * When calling [`Regex::captures`], instead of immediately
62/// running a slower but more capable regex engine like the
63/// [`PikeVM`](crate::nfa::thompson::pikevm::PikeVM), the meta regex engine
64/// will usually first look for the bounds of a match with a higher throughput
65/// regex engine like a [lazy DFA](crate::hybrid). Only when a match is found
66/// is a slower engine like `PikeVM` used to find the matching span for each
67/// capture group.
68/// * While higher throughout engines like the lazy DFA cannot handle
69/// Unicode word boundaries in general, they can still be used on pure ASCII
70/// haystacks by pretending that Unicode word boundaries are just plain ASCII
71/// word boundaries. However, if a haystack is not ASCII, the meta regex engine
72/// will automatically switch to a (possibly slower) regex engine that supports
73/// Unicode word boundaries in general.
74/// * In some cases where a regex pattern is just a simple literal or a small
75/// set of literals, an actual regex engine won't be used at all. Instead,
76/// substring or multi-substring search algorithms will be employed.
77///
78/// There are many other forms of composition happening too, but the above
79/// should give a general idea. In particular, it may perhaps be surprising
80/// that *multiple* regex engines might get executed for a single search. That
81/// is, the decision of what regex engine to use is not _just_ based on the
82/// pattern, but also based on the dynamic execution of the search itself.
83///
84/// The primary reason for this composition is performance. The fundamental
85/// tension is that the faster engines tend to be less capable, and the more
86/// capable engines tend to be slower.
87///
88/// Note that the forms of composition that are allowed are determined by
89/// compile time crate features and configuration. For example, if the `hybrid`
90/// feature isn't enabled, or if [`Config::hybrid`] has been disabled, then the
91/// meta regex engine will never use a lazy DFA.
92///
93/// # Synchronization and cloning
94///
95/// Most of the regex engines in this crate require some kind of mutable
96/// "scratch" space to read and write from while performing a search. Since
97/// a meta regex composes these regex engines, a meta regex also requires
98/// mutable scratch space. This scratch space is called a [`Cache`].
99///
100/// Most regex engines _also_ usually have a read-only component, typically
101/// a [Thompson `NFA`](crate::nfa::thompson::NFA).
102///
103/// In order to make the `Regex` API convenient, most of the routines hide
104/// the fact that a `Cache` is needed at all. To achieve this, a [memory
105/// pool](crate::util::pool::Pool) is used internally to retrieve `Cache`
106/// values in a thread safe way that also permits reuse. This in turn implies
107/// that every such search call requires some form of synchronization. Usually
108/// this synchronization is fast enough to not notice, but in some cases, it
109/// can be a bottleneck. This typically occurs when all of the following are
110/// true:
111///
112/// * The same `Regex` is shared across multiple threads simultaneously,
113/// usually via a [`util::lazy::Lazy`](crate::util::lazy::Lazy) or something
114/// similar from the `once_cell` or `lazy_static` crates.
115/// * The primary unit of work in each thread is a regex search.
116/// * Searches are run on very short haystacks.
117///
118/// This particular case can lead to high contention on the pool used by a
119/// `Regex` internally, which can in turn increase latency to a noticeable
120/// effect. This cost can be mitigated in one of the following ways:
121///
122/// * Use a distinct copy of a `Regex` in each thread, usually by cloning it.
123/// Cloning a `Regex` _does not_ do a deep copy of its read-only component.
124/// But it does lead to each `Regex` having its own memory pool, which in
125/// turn eliminates the problem of contention. In general, this technique should
126/// not result in any additional memory usage when compared to sharing the same
127/// `Regex` across multiple threads simultaneously.
128/// * Use lower level APIs, like [`Regex::search_with`], which permit passing
129/// a `Cache` explicitly. In this case, it is up to you to determine how best
130/// to provide a `Cache`. For example, you might put a `Cache` in thread-local
131/// storage if your use case allows for it.
132///
133/// Overall, this is an issue that happens rarely in practice, but it can
134/// happen.
135///
136/// # Warning: spin-locks may be used in alloc-only mode
137///
138/// When this crate is built without the `std` feature and the high level APIs
139/// on a `Regex` are used, then a spin-lock will be used to synchronize access
140/// to an internal pool of `Cache` values. This may be undesirable because
141/// a spin-lock is [effectively impossible to implement correctly in user
142/// space][spinlocks-are-bad]. That is, more concretely, the spin-lock could
143/// result in a deadlock.
144///
145/// [spinlocks-are-bad]: https://matklad.github.io/2020/01/02/spinlocks-considered-harmful.html
146///
147/// If one wants to avoid the use of spin-locks when the `std` feature is
148/// disabled, then you must use APIs that accept a `Cache` value explicitly.
149/// For example, [`Regex::search_with`].
150///
151/// # Example
152///
153/// ```
154/// use regex_automata::meta::Regex;
155///
156/// let re = Regex::new(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$")?;
157/// assert!(re.is_match("2010-03-14"));
158///
159/// # Ok::<(), Box<dyn std::error::Error>>(())
160/// ```
161///
162/// # Example: anchored search
163///
164/// This example shows how to use [`Input::anchored`] to run an anchored
165/// search, even when the regex pattern itself isn't anchored. An anchored
166/// search guarantees that if a match is found, then the start offset of the
167/// match corresponds to the offset at which the search was started.
168///
169/// ```
170/// use regex_automata::{meta::Regex, Anchored, Input, Match};
171///
172/// let re = Regex::new(r"\bfoo\b")?;
173/// let input = Input::new("xx foo xx").range(3..).anchored(Anchored::Yes);
174/// // The offsets are in terms of the original haystack.
175/// assert_eq!(Some(Match::must(0, 3..6)), re.find(input));
176///
177/// // Notice that no match occurs here, because \b still takes the
178/// // surrounding context into account, even if it means looking back
179/// // before the start of your search.
180/// let hay = "xxfoo xx";
181/// let input = Input::new(hay).range(2..).anchored(Anchored::Yes);
182/// assert_eq!(None, re.find(input));
183/// // Indeed, you cannot achieve the above by simply slicing the
184/// // haystack itself, since the regex engine can't see the
185/// // surrounding context. This is why 'Input' permits setting
186/// // the bounds of a search!
187/// let input = Input::new(&hay[2..]).anchored(Anchored::Yes);
188/// // WRONG!
189/// assert_eq!(Some(Match::must(0, 0..3)), re.find(input));
190///
191/// # Ok::<(), Box<dyn std::error::Error>>(())
192/// ```
193///
194/// # Example: earliest search
195///
196/// This example shows how to use [`Input::earliest`] to run a search that
197/// might stop before finding the typical leftmost match.
198///
199/// ```
200/// use regex_automata::{meta::Regex, Anchored, Input, Match};
201///
202/// let re = Regex::new(r"[a-z]{3}|b")?;
203/// let input = Input::new("abc").earliest(true);
204/// assert_eq!(Some(Match::must(0, 1..2)), re.find(input));
205///
206/// // Note that "earliest" isn't really a match semantic unto itself.
207/// // Instead, it is merely an instruction to whatever regex engine
208/// // gets used internally to quit as soon as it can. For example,
209/// // this regex uses a different search technique, and winds up
210/// // producing a different (but valid) match!
211/// let re = Regex::new(r"abc|b")?;
212/// let input = Input::new("abc").earliest(true);
213/// assert_eq!(Some(Match::must(0, 0..3)), re.find(input));
214///
215/// # Ok::<(), Box<dyn std::error::Error>>(())
216/// ```
217///
218/// # Example: change the line terminator
219///
220/// This example shows how to enable multi-line mode by default and change
221/// the line terminator to the NUL byte:
222///
223/// ```
224/// use regex_automata::{meta::Regex, util::syntax, Match};
225///
226/// let re = Regex::builder()
227///     .syntax(syntax::Config::new().multi_line(true))
228///     .configure(Regex::config().line_terminator(b'\x00'))
229///     .build(r"^foo$")?;
230/// let hay = "\x00foo\x00";
231/// assert_eq!(Some(Match::must(0, 1..4)), re.find(hay));
232///
233/// # Ok::<(), Box<dyn std::error::Error>>(())
234/// ```
235#[derive(Debug)]
236pub struct Regex {
237    /// The actual regex implementation.
238    imp: Arc<RegexI>,
239    /// A thread safe pool of caches.
240    ///
241    /// For the higher level search APIs, a `Cache` is automatically plucked
242    /// from this pool before running a search. The lower level `with` methods
243    /// permit the caller to provide their own cache, thereby bypassing
244    /// accesses to this pool.
245    ///
246    /// Note that we put this outside the `Arc` so that cloning a `Regex`
247    /// results in creating a fresh `CachePool`. This in turn permits callers
248    /// to clone regexes into separate threads where each such regex gets
249    /// the pool's "thread owner" optimization. Otherwise, if one shares the
250    /// `Regex` directly, then the pool will go through a slower mutex path for
251    /// all threads except for the "owner."
252    pool: CachePool,
253}
254
255/// The internal implementation of `Regex`, split out so that it can be wrapped
256/// in an `Arc`.
257#[derive(Debug)]
258struct RegexI {
259    /// The core matching engine.
260    ///
261    /// Why is this reference counted when RegexI is already wrapped in an Arc?
262    /// Well, we need to capture this in a closure to our `Pool` below in order
263    /// to create new `Cache` values when needed. So since it needs to be in
264    /// two places, we make it reference counted.
265    ///
266    /// We make `RegexI` itself reference counted too so that `Regex` itself
267    /// stays extremely small and very cheap to clone.
268    strat: Arc<dyn Strategy>,
269    /// Metadata about the regexes driving the strategy. The metadata is also
270    /// usually stored inside the strategy too, but we put it here as well
271    /// so that we can get quick access to it (without virtual calls) before
272    /// executing the regex engine. For example, we use this metadata to
273    /// detect a subset of cases where we know a match is impossible, and can
274    /// thus avoid calling into the strategy at all.
275    ///
276    /// Since `RegexInfo` is stored in multiple places, it is also reference
277    /// counted.
278    info: RegexInfo,
279}
280
281/// Convenience constructors for a `Regex` using the default configuration.
282impl Regex {
283    /// Builds a `Regex` from a single pattern string using the default
284    /// configuration.
285    ///
286    /// If there was a problem parsing the pattern or a problem turning it into
287    /// a regex matcher, then an error is returned.
288    ///
289    /// If you want to change the configuration of a `Regex`, use a [`Builder`]
290    /// with a [`Config`].
291    ///
292    /// # Example
293    ///
294    /// ```
295    /// use regex_automata::{meta::Regex, Match};
296    ///
297    /// let re = Regex::new(r"(?Rm)^foo$")?;
298    /// let hay = "\r\nfoo\r\n";
299    /// assert_eq!(Some(Match::must(0, 2..5)), re.find(hay));
300    ///
301    /// # Ok::<(), Box<dyn std::error::Error>>(())
302    /// ```
303    pub fn new(pattern: &str) -> Result<Regex, BuildError> {
304        Regex::builder().build(pattern)
305    }
306
307    /// Builds a `Regex` from many pattern strings using the default
308    /// configuration.
309    ///
310    /// If there was a problem parsing any of the patterns or a problem turning
311    /// them into a regex matcher, then an error is returned.
312    ///
313    /// If you want to change the configuration of a `Regex`, use a [`Builder`]
314    /// with a [`Config`].
315    ///
316    /// # Example: simple lexer
317    ///
318    /// This simplistic example leverages the multi-pattern support to build a
319    /// simple little lexer. The pattern ID in the match tells you which regex
320    /// matched, which in turn might be used to map back to the "type" of the
321    /// token returned by the lexer.
322    ///
323    /// ```
324    /// use regex_automata::{meta::Regex, Match};
325    ///
326    /// let re = Regex::new_many(&[
327    ///     r"[[:space:]]",
328    ///     r"[A-Za-z0-9][A-Za-z0-9_]+",
329    ///     r"->",
330    ///     r".",
331    /// ])?;
332    /// let haystack = "fn is_boss(bruce: i32, springsteen: String) -> bool;";
333    /// let matches: Vec<Match> = re.find_iter(haystack).collect();
334    /// assert_eq!(matches, vec![
335    ///     Match::must(1, 0..2),   // 'fn'
336    ///     Match::must(0, 2..3),   // ' '
337    ///     Match::must(1, 3..10),  // 'is_boss'
338    ///     Match::must(3, 10..11), // '('
339    ///     Match::must(1, 11..16), // 'bruce'
340    ///     Match::must(3, 16..17), // ':'
341    ///     Match::must(0, 17..18), // ' '
342    ///     Match::must(1, 18..21), // 'i32'
343    ///     Match::must(3, 21..22), // ','
344    ///     Match::must(0, 22..23), // ' '
345    ///     Match::must(1, 23..34), // 'springsteen'
346    ///     Match::must(3, 34..35), // ':'
347    ///     Match::must(0, 35..36), // ' '
348    ///     Match::must(1, 36..42), // 'String'
349    ///     Match::must(3, 42..43), // ')'
350    ///     Match::must(0, 43..44), // ' '
351    ///     Match::must(2, 44..46), // '->'
352    ///     Match::must(0, 46..47), // ' '
353    ///     Match::must(1, 47..51), // 'bool'
354    ///     Match::must(3, 51..52), // ';'
355    /// ]);
356    ///
357    /// # Ok::<(), Box<dyn std::error::Error>>(())
358    /// ```
359    ///
360    /// One can write a lexer like the above using a regex like
361    /// `(?P<space>[[:space:]])|(?P<ident>[A-Za-z0-9][A-Za-z0-9_]+)|...`,
362    /// but then you need to ask whether capture group matched to determine
363    /// which branch in the regex matched, and thus, which token the match
364    /// corresponds to. In contrast, the above example includes the pattern ID
365    /// in the match. There's no need to use capture groups at all.
366    ///
367    /// # Example: finding the pattern that caused an error
368    ///
369    /// When a syntax error occurs, it is possible to ask which pattern
370    /// caused the syntax error.
371    ///
372    /// ```
373    /// use regex_automata::{meta::Regex, PatternID};
374    ///
375    /// let err = Regex::new_many(&["a", "b", r"\p{Foo}", "c"]).unwrap_err();
376    /// assert_eq!(Some(PatternID::must(2)), err.pattern());
377    /// ```
378    ///
379    /// # Example: zero patterns is valid
380    ///
381    /// Building a regex with zero patterns results in a regex that never
382    /// matches anything. Because this routine is generic, passing an empty
383    /// slice usually requires a turbo-fish (or something else to help type
384    /// inference).
385    ///
386    /// ```
387    /// use regex_automata::{meta::Regex, util::syntax, Match};
388    ///
389    /// let re = Regex::new_many::<&str>(&[])?;
390    /// assert_eq!(None, re.find(""));
391    ///
392    /// # Ok::<(), Box<dyn std::error::Error>>(())
393    /// ```
394    pub fn new_many<P: AsRef<str>>(
395        patterns: &[P],
396    ) -> Result<Regex, BuildError> {
397        Regex::builder().build_many(patterns)
398    }
399
400    /// Return a default configuration for a `Regex`.
401    ///
402    /// This is a convenience routine to avoid needing to import the [`Config`]
403    /// type when customizing the construction of a `Regex`.
404    ///
405    /// # Example: lower the NFA size limit
406    ///
407    /// In some cases, the default size limit might be too big. The size limit
408    /// can be lowered, which will prevent large regex patterns from compiling.
409    ///
410    /// ```
411    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
412    /// use regex_automata::meta::Regex;
413    ///
414    /// let result = Regex::builder()
415    ///     .configure(Regex::config().nfa_size_limit(Some(20 * (1<<10))))
416    ///     // Not even 20KB is enough to build a single large Unicode class!
417    ///     .build(r"\pL");
418    /// assert!(result.is_err());
419    ///
420    /// # Ok::<(), Box<dyn std::error::Error>>(())
421    /// ```
422    pub fn config() -> Config {
423        Config::new()
424    }
425
426    /// Return a builder for configuring the construction of a `Regex`.
427    ///
428    /// This is a convenience routine to avoid needing to import the
429    /// [`Builder`] type in common cases.
430    ///
431    /// # Example: change the line terminator
432    ///
433    /// This example shows how to enable multi-line mode by default and change
434    /// the line terminator to the NUL byte:
435    ///
436    /// ```
437    /// use regex_automata::{meta::Regex, util::syntax, Match};
438    ///
439    /// let re = Regex::builder()
440    ///     .syntax(syntax::Config::new().multi_line(true))
441    ///     .configure(Regex::config().line_terminator(b'\x00'))
442    ///     .build(r"^foo$")?;
443    /// let hay = "\x00foo\x00";
444    /// assert_eq!(Some(Match::must(0, 1..4)), re.find(hay));
445    ///
446    /// # Ok::<(), Box<dyn std::error::Error>>(())
447    /// ```
448    pub fn builder() -> Builder {
449        Builder::new()
450    }
451}
452
453/// High level convenience routines for using a regex to search a haystack.
454impl Regex {
455    /// Returns true if and only if this regex matches the given haystack.
456    ///
457    /// This routine may short circuit if it knows that scanning future input
458    /// will never lead to a different result. (Consider how this might make
459    /// a difference given the regex `a+` on the haystack `aaaaaaaaaaaaaaa`.
460    /// This routine _may_ stop after it sees the first `a`, but routines like
461    /// `find` need to continue searching because `+` is greedy by default.)
462    ///
463    /// # Example
464    ///
465    /// ```
466    /// use regex_automata::meta::Regex;
467    ///
468    /// let re = Regex::new("foo[0-9]+bar")?;
469    ///
470    /// assert!(re.is_match("foo12345bar"));
471    /// assert!(!re.is_match("foobar"));
472    ///
473    /// # Ok::<(), Box<dyn std::error::Error>>(())
474    /// ```
475    ///
476    /// # Example: consistency with search APIs
477    ///
478    /// `is_match` is guaranteed to return `true` whenever `find` returns a
479    /// match. This includes searches that are executed entirely within a
480    /// codepoint:
481    ///
482    /// ```
483    /// use regex_automata::{meta::Regex, Input};
484    ///
485    /// let re = Regex::new("a*")?;
486    ///
487    /// // This doesn't match because the default configuration bans empty
488    /// // matches from splitting a codepoint.
489    /// assert!(!re.is_match(Input::new("☃").span(1..2)));
490    /// assert_eq!(None, re.find(Input::new("☃").span(1..2)));
491    ///
492    /// # Ok::<(), Box<dyn std::error::Error>>(())
493    /// ```
494    ///
495    /// Notice that when UTF-8 mode is disabled, then the above reports a
496    /// match because the restriction against zero-width matches that split a
497    /// codepoint has been lifted:
498    ///
499    /// ```
500    /// use regex_automata::{meta::Regex, Input, Match};
501    ///
502    /// let re = Regex::builder()
503    ///     .configure(Regex::config().utf8_empty(false))
504    ///     .build("a*")?;
505    ///
506    /// assert!(re.is_match(Input::new("☃").span(1..2)));
507    /// assert_eq!(
508    ///     Some(Match::must(0, 1..1)),
509    ///     re.find(Input::new("☃").span(1..2)),
510    /// );
511    ///
512    /// # Ok::<(), Box<dyn std::error::Error>>(())
513    /// ```
514    ///
515    /// A similar idea applies when using line anchors with CRLF mode enabled,
516    /// which prevents them from matching between a `\r` and a `\n`.
517    ///
518    /// ```
519    /// use regex_automata::{meta::Regex, Input, Match};
520    ///
521    /// let re = Regex::new(r"(?Rm:$)")?;
522    /// assert!(!re.is_match(Input::new("\r\n").span(1..1)));
523    /// // A regular line anchor, which only considers \n as a
524    /// // line terminator, will match.
525    /// let re = Regex::new(r"(?m:$)")?;
526    /// assert!(re.is_match(Input::new("\r\n").span(1..1)));
527    ///
528    /// # Ok::<(), Box<dyn std::error::Error>>(())
529    /// ```
530    #[inline]
531    pub fn is_match<'h, I: Into<Input<'h>>>(&self, input: I) -> bool {
532        let input = input.into().earliest(true);
533        if self.imp.info.is_impossible(&input) {
534            return false;
535        }
536        let mut guard = self.pool.get();
537        let result = self.imp.strat.is_match(&mut guard, &input);
538        // See 'Regex::search' for why we put the guard back explicitly.
539        PoolGuard::put(guard);
540        result
541    }
542
543    /// Executes a leftmost search and returns the first match that is found,
544    /// if one exists.
545    ///
546    /// # Example
547    ///
548    /// ```
549    /// use regex_automata::{meta::Regex, Match};
550    ///
551    /// let re = Regex::new("foo[0-9]+")?;
552    /// assert_eq!(Some(Match::must(0, 0..8)), re.find("foo12345"));
553    ///
554    /// # Ok::<(), Box<dyn std::error::Error>>(())
555    /// ```
556    #[inline]
557    pub fn find<'h, I: Into<Input<'h>>>(&self, input: I) -> Option<Match> {
558        self.search(&input.into())
559    }
560
561    /// Executes a leftmost forward search and writes the spans of capturing
562    /// groups that participated in a match into the provided [`Captures`]
563    /// value. If no match was found, then [`Captures::is_match`] is guaranteed
564    /// to return `false`.
565    ///
566    /// # Example
567    ///
568    /// ```
569    /// use regex_automata::{meta::Regex, Span};
570    ///
571    /// let re = Regex::new(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})$")?;
572    /// let mut caps = re.create_captures();
573    ///
574    /// re.captures("2010-03-14", &mut caps);
575    /// assert!(caps.is_match());
576    /// assert_eq!(Some(Span::from(0..4)), caps.get_group(1));
577    /// assert_eq!(Some(Span::from(5..7)), caps.get_group(2));
578    /// assert_eq!(Some(Span::from(8..10)), caps.get_group(3));
579    ///
580    /// # Ok::<(), Box<dyn std::error::Error>>(())
581    /// ```
582    #[inline]
583    pub fn captures<'h, I: Into<Input<'h>>>(
584        &self,
585        input: I,
586        caps: &mut Captures,
587    ) {
588        self.search_captures(&input.into(), caps)
589    }
590
591    /// Returns an iterator over all non-overlapping leftmost matches in
592    /// the given haystack. If no match exists, then the iterator yields no
593    /// elements.
594    ///
595    /// # Example
596    ///
597    /// ```
598    /// use regex_automata::{meta::Regex, Match};
599    ///
600    /// let re = Regex::new("foo[0-9]+")?;
601    /// let haystack = "foo1 foo12 foo123";
602    /// let matches: Vec<Match> = re.find_iter(haystack).collect();
603    /// assert_eq!(matches, vec![
604    ///     Match::must(0, 0..4),
605    ///     Match::must(0, 5..10),
606    ///     Match::must(0, 11..17),
607    /// ]);
608    /// # Ok::<(), Box<dyn std::error::Error>>(())
609    /// ```
610    #[inline]
611    pub fn find_iter<'r, 'h, I: Into<Input<'h>>>(
612        &'r self,
613        input: I,
614    ) -> FindMatches<'r, 'h> {
615        let cache = self.pool.get();
616        let it = iter::Searcher::new(input.into());
617        FindMatches { re: self, cache, it }
618    }
619
620    /// Returns an iterator over all non-overlapping `Captures` values. If no
621    /// match exists, then the iterator yields no elements.
622    ///
623    /// This yields the same matches as [`Regex::find_iter`], but it includes
624    /// the spans of all capturing groups that participate in each match.
625    ///
626    /// **Tip:** See [`util::iter::Searcher`](crate::util::iter::Searcher) for
627    /// how to correctly iterate over all matches in a haystack while avoiding
628    /// the creation of a new `Captures` value for every match. (Which you are
629    /// forced to do with an `Iterator`.)
630    ///
631    /// # Example
632    ///
633    /// ```
634    /// use regex_automata::{meta::Regex, Span};
635    ///
636    /// let re = Regex::new("foo(?P<numbers>[0-9]+)")?;
637    ///
638    /// let haystack = "foo1 foo12 foo123";
639    /// let matches: Vec<Span> = re
640    ///     .captures_iter(haystack)
641    ///     // The unwrap is OK since 'numbers' matches if the pattern matches.
642    ///     .map(|caps| caps.get_group_by_name("numbers").unwrap())
643    ///     .collect();
644    /// assert_eq!(matches, vec![
645    ///     Span::from(3..4),
646    ///     Span::from(8..10),
647    ///     Span::from(14..17),
648    /// ]);
649    /// # Ok::<(), Box<dyn std::error::Error>>(())
650    /// ```
651    #[inline]
652    pub fn captures_iter<'r, 'h, I: Into<Input<'h>>>(
653        &'r self,
654        input: I,
655    ) -> CapturesMatches<'r, 'h> {
656        let cache = self.pool.get();
657        let caps = self.create_captures();
658        let it = iter::Searcher::new(input.into());
659        CapturesMatches { re: self, cache, caps, it }
660    }
661
662    /// Returns an iterator of spans of the haystack given, delimited by a
663    /// match of the regex. Namely, each element of the iterator corresponds to
664    /// a part of the haystack that *isn't* matched by the regular expression.
665    ///
666    /// # Example
667    ///
668    /// To split a string delimited by arbitrary amounts of spaces or tabs:
669    ///
670    /// ```
671    /// use regex_automata::meta::Regex;
672    ///
673    /// let re = Regex::new(r"[ \t]+")?;
674    /// let hay = "a b \t  c\td    e";
675    /// let fields: Vec<&str> = re.split(hay).map(|span| &hay[span]).collect();
676    /// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]);
677    ///
678    /// # Ok::<(), Box<dyn std::error::Error>>(())
679    /// ```
680    ///
681    /// # Example: more cases
682    ///
683    /// Basic usage:
684    ///
685    /// ```
686    /// use regex_automata::meta::Regex;
687    ///
688    /// let re = Regex::new(r" ")?;
689    /// let hay = "Mary had a little lamb";
690    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
691    /// assert_eq!(got, vec!["Mary", "had", "a", "little", "lamb"]);
692    ///
693    /// let re = Regex::new(r"X")?;
694    /// let hay = "";
695    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
696    /// assert_eq!(got, vec![""]);
697    ///
698    /// let re = Regex::new(r"X")?;
699    /// let hay = "lionXXtigerXleopard";
700    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
701    /// assert_eq!(got, vec!["lion", "", "tiger", "leopard"]);
702    ///
703    /// let re = Regex::new(r"::")?;
704    /// let hay = "lion::tiger::leopard";
705    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
706    /// assert_eq!(got, vec!["lion", "tiger", "leopard"]);
707    ///
708    /// # Ok::<(), Box<dyn std::error::Error>>(())
709    /// ```
710    ///
711    /// If a haystack contains multiple contiguous matches, you will end up
712    /// with empty spans yielded by the iterator:
713    ///
714    /// ```
715    /// use regex_automata::meta::Regex;
716    ///
717    /// let re = Regex::new(r"X")?;
718    /// let hay = "XXXXaXXbXc";
719    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
720    /// assert_eq!(got, vec!["", "", "", "", "a", "", "b", "c"]);
721    ///
722    /// let re = Regex::new(r"/")?;
723    /// let hay = "(///)";
724    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
725    /// assert_eq!(got, vec!["(", "", "", ")"]);
726    ///
727    /// # Ok::<(), Box<dyn std::error::Error>>(())
728    /// ```
729    ///
730    /// Separators at the start or end of a haystack are neighbored by empty
731    /// spans.
732    ///
733    /// ```
734    /// use regex_automata::meta::Regex;
735    ///
736    /// let re = Regex::new(r"0")?;
737    /// let hay = "010";
738    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
739    /// assert_eq!(got, vec!["", "1", ""]);
740    ///
741    /// # Ok::<(), Box<dyn std::error::Error>>(())
742    /// ```
743    ///
744    /// When the empty string is used as a regex, it splits at every valid
745    /// UTF-8 boundary by default (which includes the beginning and end of the
746    /// haystack):
747    ///
748    /// ```
749    /// use regex_automata::meta::Regex;
750    ///
751    /// let re = Regex::new(r"")?;
752    /// let hay = "rust";
753    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
754    /// assert_eq!(got, vec!["", "r", "u", "s", "t", ""]);
755    ///
756    /// // Splitting by an empty string is UTF-8 aware by default!
757    /// let re = Regex::new(r"")?;
758    /// let hay = "☃";
759    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
760    /// assert_eq!(got, vec!["", "☃", ""]);
761    ///
762    /// # Ok::<(), Box<dyn std::error::Error>>(())
763    /// ```
764    ///
765    /// But note that UTF-8 mode for empty strings can be disabled, which will
766    /// then result in a match at every byte offset in the haystack,
767    /// including between every UTF-8 code unit.
768    ///
769    /// ```
770    /// use regex_automata::meta::Regex;
771    ///
772    /// let re = Regex::builder()
773    ///     .configure(Regex::config().utf8_empty(false))
774    ///     .build(r"")?;
775    /// let hay = "☃".as_bytes();
776    /// let got: Vec<&[u8]> = re.split(hay).map(|sp| &hay[sp]).collect();
777    /// assert_eq!(got, vec![
778    ///     // Writing byte string slices is just brutal. The problem is that
779    ///     // b"foo" has type &[u8; 3] instead of &[u8].
780    ///     &[][..], &[b'\xE2'][..], &[b'\x98'][..], &[b'\x83'][..], &[][..],
781    /// ]);
782    ///
783    /// # Ok::<(), Box<dyn std::error::Error>>(())
784    /// ```
785    ///
786    /// Contiguous separators (commonly shows up with whitespace), can lead to
787    /// possibly surprising behavior. For example, this code is correct:
788    ///
789    /// ```
790    /// use regex_automata::meta::Regex;
791    ///
792    /// let re = Regex::new(r" ")?;
793    /// let hay = "    a  b c";
794    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
795    /// assert_eq!(got, vec!["", "", "", "", "a", "", "b", "c"]);
796    ///
797    /// # Ok::<(), Box<dyn std::error::Error>>(())
798    /// ```
799    ///
800    /// It does *not* give you `["a", "b", "c"]`. For that behavior, you'd want
801    /// to match contiguous space characters:
802    ///
803    /// ```
804    /// use regex_automata::meta::Regex;
805    ///
806    /// let re = Regex::new(r" +")?;
807    /// let hay = "    a  b c";
808    /// let got: Vec<&str> = re.split(hay).map(|sp| &hay[sp]).collect();
809    /// // N.B. This does still include a leading empty span because ' +'
810    /// // matches at the beginning of the haystack.
811    /// assert_eq!(got, vec!["", "a", "b", "c"]);
812    ///
813    /// # Ok::<(), Box<dyn std::error::Error>>(())
814    /// ```
815    #[inline]
816    pub fn split<'r, 'h, I: Into<Input<'h>>>(
817        &'r self,
818        input: I,
819    ) -> Split<'r, 'h> {
820        Split { finder: self.find_iter(input), last: 0 }
821    }
822
823    /// Returns an iterator of at most `limit` spans of the haystack given,
824    /// delimited by a match of the regex. (A `limit` of `0` will return no
825    /// spans.) Namely, each element of the iterator corresponds to a part
826    /// of the haystack that *isn't* matched by the regular expression. The
827    /// remainder of the haystack that is not split will be the last element in
828    /// the iterator.
829    ///
830    /// # Example
831    ///
832    /// Get the first two words in some haystack:
833    ///
834    /// ```
835    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
836    /// use regex_automata::meta::Regex;
837    ///
838    /// let re = Regex::new(r"\W+").unwrap();
839    /// let hay = "Hey! How are you?";
840    /// let fields: Vec<&str> =
841    ///     re.splitn(hay, 3).map(|span| &hay[span]).collect();
842    /// assert_eq!(fields, vec!["Hey", "How", "are you?"]);
843    ///
844    /// # Ok::<(), Box<dyn std::error::Error>>(())
845    /// ```
846    ///
847    /// # Examples: more cases
848    ///
849    /// ```
850    /// use regex_automata::meta::Regex;
851    ///
852    /// let re = Regex::new(r" ")?;
853    /// let hay = "Mary had a little lamb";
854    /// let got: Vec<&str> = re.splitn(hay, 3).map(|sp| &hay[sp]).collect();
855    /// assert_eq!(got, vec!["Mary", "had", "a little lamb"]);
856    ///
857    /// let re = Regex::new(r"X")?;
858    /// let hay = "";
859    /// let got: Vec<&str> = re.splitn(hay, 3).map(|sp| &hay[sp]).collect();
860    /// assert_eq!(got, vec![""]);
861    ///
862    /// let re = Regex::new(r"X")?;
863    /// let hay = "lionXXtigerXleopard";
864    /// let got: Vec<&str> = re.splitn(hay, 3).map(|sp| &hay[sp]).collect();
865    /// assert_eq!(got, vec!["lion", "", "tigerXleopard"]);
866    ///
867    /// let re = Regex::new(r"::")?;
868    /// let hay = "lion::tiger::leopard";
869    /// let got: Vec<&str> = re.splitn(hay, 2).map(|sp| &hay[sp]).collect();
870    /// assert_eq!(got, vec!["lion", "tiger::leopard"]);
871    ///
872    /// let re = Regex::new(r"X")?;
873    /// let hay = "abcXdef";
874    /// let got: Vec<&str> = re.splitn(hay, 1).map(|sp| &hay[sp]).collect();
875    /// assert_eq!(got, vec!["abcXdef"]);
876    ///
877    /// let re = Regex::new(r"X")?;
878    /// let hay = "abcdef";
879    /// let got: Vec<&str> = re.splitn(hay, 2).map(|sp| &hay[sp]).collect();
880    /// assert_eq!(got, vec!["abcdef"]);
881    ///
882    /// let re = Regex::new(r"X")?;
883    /// let hay = "abcXdef";
884    /// let got: Vec<&str> = re.splitn(hay, 0).map(|sp| &hay[sp]).collect();
885    /// assert!(got.is_empty());
886    ///
887    /// # Ok::<(), Box<dyn std::error::Error>>(())
888    /// ```
889    pub fn splitn<'r, 'h, I: Into<Input<'h>>>(
890        &'r self,
891        input: I,
892        limit: usize,
893    ) -> SplitN<'r, 'h> {
894        SplitN { splits: self.split(input), limit }
895    }
896}
897
898/// Lower level search routines that give more control.
899impl Regex {
900    /// Returns the start and end offset of the leftmost match. If no match
901    /// exists, then `None` is returned.
902    ///
903    /// This is like [`Regex::find`] but, but it accepts a concrete `&Input`
904    /// instead of an `Into<Input>`.
905    ///
906    /// # Example
907    ///
908    /// ```
909    /// use regex_automata::{meta::Regex, Input, Match};
910    ///
911    /// let re = Regex::new(r"Samwise|Sam")?;
912    /// let input = Input::new(
913    ///     "one of the chief characters, Samwise the Brave",
914    /// );
915    /// assert_eq!(Some(Match::must(0, 29..36)), re.search(&input));
916    ///
917    /// # Ok::<(), Box<dyn std::error::Error>>(())
918    /// ```
919    #[inline]
920    pub fn search(&self, input: &Input<'_>) -> Option<Match> {
921        if self.imp.info.captures_disabled()
922            || self.imp.info.is_impossible(input)
923        {
924            return None;
925        }
926        let mut guard = self.pool.get();
927        let result = self.imp.strat.search(&mut guard, input);
928        // We do this dance with the guard and explicitly put it back in the
929        // pool because it seems to result in better codegen. If we let the
930        // guard's Drop impl put it back in the pool, then functions like
931        // ptr::drop_in_place get called and they *don't* get inlined. This
932        // isn't usually a big deal, but in latency sensitive benchmarks the
933        // extra function call can matter.
934        //
935        // I used `rebar measure -f '^grep/every-line$' -e meta` to measure
936        // the effects here.
937        //
938        // Note that this doesn't eliminate the latency effects of using the
939        // pool. There is still some (minor) cost for the "thread owner" of the
940        // pool. (i.e., The thread that first calls a regex search routine.)
941        // However, for other threads using the regex, the pool access can be
942        // quite expensive as it goes through a mutex. Callers can avoid this
943        // by either cloning the Regex (which creates a distinct copy of the
944        // pool), or callers can use the lower level APIs that accept a 'Cache'
945        // directly and do their own handling.
946        PoolGuard::put(guard);
947        result
948    }
949
950    /// Returns the end offset of the leftmost match. If no match exists, then
951    /// `None` is returned.
952    ///
953    /// This is distinct from [`Regex::search`] in that it only returns the end
954    /// of a match and not the start of the match. Depending on a variety of
955    /// implementation details, this _may_ permit the regex engine to do less
956    /// overall work. For example, if a DFA is being used to execute a search,
957    /// then the start of a match usually requires running a separate DFA in
958    /// reverse to the find the start of a match. If one only needs the end of
959    /// a match, then the separate reverse scan to find the start of a match
960    /// can be skipped. (Note that the reverse scan is avoided even when using
961    /// `Regex::search` when possible, for example, in the case of an anchored
962    /// search.)
963    ///
964    /// # Example
965    ///
966    /// ```
967    /// use regex_automata::{meta::Regex, Input, HalfMatch};
968    ///
969    /// let re = Regex::new(r"Samwise|Sam")?;
970    /// let input = Input::new(
971    ///     "one of the chief characters, Samwise the Brave",
972    /// );
973    /// assert_eq!(Some(HalfMatch::must(0, 36)), re.search_half(&input));
974    ///
975    /// # Ok::<(), Box<dyn std::error::Error>>(())
976    /// ```
977    #[inline]
978    pub fn search_half(&self, input: &Input<'_>) -> Option<HalfMatch> {
979        if self.imp.info.captures_disabled()
980            || self.imp.info.is_impossible(input)
981        {
982            return None;
983        }
984        let mut guard = self.pool.get();
985        let result = self.imp.strat.search_half(&mut guard, input);
986        // See 'Regex::search' for why we put the guard back explicitly.
987        PoolGuard::put(guard);
988        result
989    }
990
991    /// Executes a leftmost forward search and writes the spans of capturing
992    /// groups that participated in a match into the provided [`Captures`]
993    /// value. If no match was found, then [`Captures::is_match`] is guaranteed
994    /// to return `false`.
995    ///
996    /// This is like [`Regex::captures`], but it accepts a concrete `&Input`
997    /// instead of an `Into<Input>`.
998    ///
999    /// # Example: specific pattern search
1000    ///
1001    /// This example shows how to build a multi-pattern `Regex` that permits
1002    /// searching for specific patterns.
1003    ///
1004    /// ```
1005    /// use regex_automata::{
1006    ///     meta::Regex,
1007    ///     Anchored, Match, PatternID, Input,
1008    /// };
1009    ///
1010    /// let re = Regex::new_many(&["[a-z0-9]{6}", "[a-z][a-z0-9]{5}"])?;
1011    /// let mut caps = re.create_captures();
1012    /// let haystack = "foo123";
1013    ///
1014    /// // Since we are using the default leftmost-first match and both
1015    /// // patterns match at the same starting position, only the first pattern
1016    /// // will be returned in this case when doing a search for any of the
1017    /// // patterns.
1018    /// let expected = Some(Match::must(0, 0..6));
1019    /// re.search_captures(&Input::new(haystack), &mut caps);
1020    /// assert_eq!(expected, caps.get_match());
1021    ///
1022    /// // But if we want to check whether some other pattern matches, then we
1023    /// // can provide its pattern ID.
1024    /// let expected = Some(Match::must(1, 0..6));
1025    /// let input = Input::new(haystack)
1026    ///     .anchored(Anchored::Pattern(PatternID::must(1)));
1027    /// re.search_captures(&input, &mut caps);
1028    /// assert_eq!(expected, caps.get_match());
1029    ///
1030    /// # Ok::<(), Box<dyn std::error::Error>>(())
1031    /// ```
1032    ///
1033    /// # Example: specifying the bounds of a search
1034    ///
1035    /// This example shows how providing the bounds of a search can produce
1036    /// different results than simply sub-slicing the haystack.
1037    ///
1038    /// ```
1039    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1040    /// use regex_automata::{meta::Regex, Match, Input};
1041    ///
1042    /// let re = Regex::new(r"\b[0-9]{3}\b")?;
1043    /// let mut caps = re.create_captures();
1044    /// let haystack = "foo123bar";
1045    ///
1046    /// // Since we sub-slice the haystack, the search doesn't know about
1047    /// // the larger context and assumes that `123` is surrounded by word
1048    /// // boundaries. And of course, the match position is reported relative
1049    /// // to the sub-slice as well, which means we get `0..3` instead of
1050    /// // `3..6`.
1051    /// let expected = Some(Match::must(0, 0..3));
1052    /// let input = Input::new(&haystack[3..6]);
1053    /// re.search_captures(&input, &mut caps);
1054    /// assert_eq!(expected, caps.get_match());
1055    ///
1056    /// // But if we provide the bounds of the search within the context of the
1057    /// // entire haystack, then the search can take the surrounding context
1058    /// // into account. (And if we did find a match, it would be reported
1059    /// // as a valid offset into `haystack` instead of its sub-slice.)
1060    /// let expected = None;
1061    /// let input = Input::new(haystack).range(3..6);
1062    /// re.search_captures(&input, &mut caps);
1063    /// assert_eq!(expected, caps.get_match());
1064    ///
1065    /// # Ok::<(), Box<dyn std::error::Error>>(())
1066    /// ```
1067    #[inline]
1068    pub fn search_captures(&self, input: &Input<'_>, caps: &mut Captures) {
1069        caps.set_pattern(None);
1070        let pid = self.search_slots(input, caps.slots_mut());
1071        caps.set_pattern(pid);
1072    }
1073
1074    /// Executes a leftmost forward search and writes the spans of capturing
1075    /// groups that participated in a match into the provided `slots`, and
1076    /// returns the matching pattern ID. The contents of the slots for patterns
1077    /// other than the matching pattern are unspecified. If no match was found,
1078    /// then `None` is returned and the contents of `slots` is unspecified.
1079    ///
1080    /// This is like [`Regex::search`], but it accepts a raw slots slice
1081    /// instead of a `Captures` value. This is useful in contexts where you
1082    /// don't want or need to allocate a `Captures`.
1083    ///
1084    /// It is legal to pass _any_ number of slots to this routine. If the regex
1085    /// engine would otherwise write a slot offset that doesn't fit in the
1086    /// provided slice, then it is simply skipped. In general though, there are
1087    /// usually three slice lengths you might want to use:
1088    ///
1089    /// * An empty slice, if you only care about which pattern matched.
1090    /// * A slice with [`pattern_len() * 2`](Regex::pattern_len) slots, if you
1091    /// only care about the overall match spans for each matching pattern.
1092    /// * A slice with
1093    /// [`slot_len()`](crate::util::captures::GroupInfo::slot_len) slots, which
1094    /// permits recording match offsets for every capturing group in every
1095    /// pattern.
1096    ///
1097    /// # Example
1098    ///
1099    /// This example shows how to find the overall match offsets in a
1100    /// multi-pattern search without allocating a `Captures` value. Indeed, we
1101    /// can put our slots right on the stack.
1102    ///
1103    /// ```
1104    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1105    /// use regex_automata::{meta::Regex, PatternID, Input};
1106    ///
1107    /// let re = Regex::new_many(&[
1108    ///     r"\pL+",
1109    ///     r"\d+",
1110    /// ])?;
1111    /// let input = Input::new("!@#123");
1112    ///
1113    /// // We only care about the overall match offsets here, so we just
1114    /// // allocate two slots for each pattern. Each slot records the start
1115    /// // and end of the match.
1116    /// let mut slots = [None; 4];
1117    /// let pid = re.search_slots(&input, &mut slots);
1118    /// assert_eq!(Some(PatternID::must(1)), pid);
1119    ///
1120    /// // The overall match offsets are always at 'pid * 2' and 'pid * 2 + 1'.
1121    /// // See 'GroupInfo' for more details on the mapping between groups and
1122    /// // slot indices.
1123    /// let slot_start = pid.unwrap().as_usize() * 2;
1124    /// let slot_end = slot_start + 1;
1125    /// assert_eq!(Some(3), slots[slot_start].map(|s| s.get()));
1126    /// assert_eq!(Some(6), slots[slot_end].map(|s| s.get()));
1127    ///
1128    /// # Ok::<(), Box<dyn std::error::Error>>(())
1129    /// ```
1130    #[inline]
1131    pub fn search_slots(
1132        &self,
1133        input: &Input<'_>,
1134        slots: &mut [Option<NonMaxUsize>],
1135    ) -> Option<PatternID> {
1136        if self.imp.info.captures_disabled()
1137            || self.imp.info.is_impossible(input)
1138        {
1139            return None;
1140        }
1141        let mut guard = self.pool.get();
1142        let result = self.imp.strat.search_slots(&mut guard, input, slots);
1143        // See 'Regex::search' for why we put the guard back explicitly.
1144        PoolGuard::put(guard);
1145        result
1146    }
1147
1148    /// Writes the set of patterns that match anywhere in the given search
1149    /// configuration to `patset`. If multiple patterns match at the same
1150    /// position and this `Regex` was configured with [`MatchKind::All`]
1151    /// semantics, then all matching patterns are written to the given set.
1152    ///
1153    /// Unless all of the patterns in this `Regex` are anchored, then generally
1154    /// speaking, this will scan the entire haystack.
1155    ///
1156    /// This search routine *does not* clear the pattern set. This gives some
1157    /// flexibility to the caller (e.g., running multiple searches with the
1158    /// same pattern set), but does make the API bug-prone if you're reusing
1159    /// the same pattern set for multiple searches but intended them to be
1160    /// independent.
1161    ///
1162    /// If a pattern ID matched but the given `PatternSet` does not have
1163    /// sufficient capacity to store it, then it is not inserted and silently
1164    /// dropped.
1165    ///
1166    /// # Example
1167    ///
1168    /// This example shows how to find all matching patterns in a haystack,
1169    /// even when some patterns match at the same position as other patterns.
1170    /// It is important that we configure the `Regex` with [`MatchKind::All`]
1171    /// semantics here, or else overlapping matches will not be reported.
1172    ///
1173    /// ```
1174    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1175    /// use regex_automata::{meta::Regex, Input, MatchKind, PatternSet};
1176    ///
1177    /// let patterns = &[
1178    ///     r"\w+", r"\d+", r"\pL+", r"foo", r"bar", r"barfoo", r"foobar",
1179    /// ];
1180    /// let re = Regex::builder()
1181    ///     .configure(Regex::config().match_kind(MatchKind::All))
1182    ///     .build_many(patterns)?;
1183    ///
1184    /// let input = Input::new("foobar");
1185    /// let mut patset = PatternSet::new(re.pattern_len());
1186    /// re.which_overlapping_matches(&input, &mut patset);
1187    /// let expected = vec![0, 2, 3, 4, 6];
1188    /// let got: Vec<usize> = patset.iter().map(|p| p.as_usize()).collect();
1189    /// assert_eq!(expected, got);
1190    ///
1191    /// # Ok::<(), Box<dyn std::error::Error>>(())
1192    /// ```
1193    #[inline]
1194    pub fn which_overlapping_matches(
1195        &self,
1196        input: &Input<'_>,
1197        patset: &mut PatternSet,
1198    ) {
1199        if self.imp.info.is_impossible(input) {
1200            return;
1201        }
1202        let mut guard = self.pool.get();
1203        let result = self
1204            .imp
1205            .strat
1206            .which_overlapping_matches(&mut guard, input, patset);
1207        // See 'Regex::search' for why we put the guard back explicitly.
1208        PoolGuard::put(guard);
1209        result
1210    }
1211}
1212
1213/// Lower level search routines that give more control, and require the caller
1214/// to provide an explicit [`Cache`] parameter.
1215impl Regex {
1216    /// This is like [`Regex::is_match`], but requires the caller to
1217    /// explicitly pass a [`Cache`].
1218    ///
1219    /// # Why pass a `Cache` explicitly?
1220    ///
1221    /// Passing a `Cache` explicitly will bypass the use of an internal memory
1222    /// pool used by `Regex` to get a `Cache` for a search. The use of this
1223    /// pool can be slower in some cases when a `Regex` is used from multiple
1224    /// threads simultaneously. Typically, performance only becomes an issue
1225    /// when there is heavy contention, which in turn usually only occurs
1226    /// when each thread's primary unit of work is a regex search on a small
1227    /// haystack.
1228    ///
1229    /// Owning the `Cache` also lets the caller decide how long it lives and
1230    /// how much memory it may use, for example by keeping a bounded number of
1231    /// caches per thread instead of one per thread per regex in the pool.
1232    ///
1233    /// # Example
1234    ///
1235    /// ```
1236    /// use regex_automata::{meta::Regex, Input};
1237    ///
1238    /// let re = Regex::new(r"Samwise|Sam")?;
1239    /// let mut cache = re.create_cache();
1240    /// let input = Input::new(
1241    ///     "one of the chief characters, Samwise the Brave",
1242    /// );
1243    /// assert!(re.is_match_with(&mut cache, &input));
1244    ///
1245    /// # Ok::<(), Box<dyn std::error::Error>>(())
1246    /// ```
1247    ///
1248    /// # Example: capture groups are disabled
1249    ///
1250    /// Unlike the other search routines in this group, this one still works
1251    /// when capture groups are disabled via
1252    /// [`Config::which_captures`](crate::meta::Config::which_captures), since
1253    /// it doesn't need to report match offsets:
1254    ///
1255    /// ```
1256    /// use regex_automata::{meta::Regex, nfa::thompson::WhichCaptures, Input};
1257    ///
1258    /// let re = Regex::builder()
1259    ///     .configure(Regex::config().which_captures(WhichCaptures::None))
1260    ///     .build(r"Samwise|Sam")?;
1261    /// let mut cache = re.create_cache();
1262    /// let input = Input::new(
1263    ///     "one of the chief characters, Samwise the Brave",
1264    /// );
1265    /// assert!(re.is_match_with(&mut cache, &input));
1266    /// // Routines that report match offsets require capture groups.
1267    /// assert_eq!(None, re.search_half_with(&mut cache, &input));
1268    ///
1269    /// # Ok::<(), Box<dyn std::error::Error>>(())
1270    /// ```
1271    #[inline]
1272    pub fn is_match_with(&self, cache: &mut Cache, input: &Input<'_>) -> bool {
1273        let input = input.clone().earliest(true);
1274        if self.imp.info.is_impossible(&input) {
1275            return false;
1276        }
1277        self.imp.strat.is_match(cache, &input)
1278    }
1279
1280    /// This is like [`Regex::search`], but requires the caller to
1281    /// explicitly pass a [`Cache`].
1282    ///
1283    /// # Why pass a `Cache` explicitly?
1284    ///
1285    /// Passing a `Cache` explicitly will bypass the use of an internal memory
1286    /// pool used by `Regex` to get a `Cache` for a search. The use of this
1287    /// pool can be slower in some cases when a `Regex` is used from multiple
1288    /// threads simultaneously. Typically, performance only becomes an issue
1289    /// when there is heavy contention, which in turn usually only occurs
1290    /// when each thread's primary unit of work is a regex search on a small
1291    /// haystack.
1292    ///
1293    /// # Example
1294    ///
1295    /// ```
1296    /// use regex_automata::{meta::Regex, Input, Match};
1297    ///
1298    /// let re = Regex::new(r"Samwise|Sam")?;
1299    /// let mut cache = re.create_cache();
1300    /// let input = Input::new(
1301    ///     "one of the chief characters, Samwise the Brave",
1302    /// );
1303    /// assert_eq!(
1304    ///     Some(Match::must(0, 29..36)),
1305    ///     re.search_with(&mut cache, &input),
1306    /// );
1307    ///
1308    /// # Ok::<(), Box<dyn std::error::Error>>(())
1309    /// ```
1310    #[inline]
1311    pub fn search_with(
1312        &self,
1313        cache: &mut Cache,
1314        input: &Input<'_>,
1315    ) -> Option<Match> {
1316        if self.imp.info.captures_disabled()
1317            || self.imp.info.is_impossible(input)
1318        {
1319            return None;
1320        }
1321        self.imp.strat.search(cache, input)
1322    }
1323
1324    /// This is like [`Regex::search_half`], but requires the caller to
1325    /// explicitly pass a [`Cache`].
1326    ///
1327    /// # Why pass a `Cache` explicitly?
1328    ///
1329    /// Passing a `Cache` explicitly will bypass the use of an internal memory
1330    /// pool used by `Regex` to get a `Cache` for a search. The use of this
1331    /// pool can be slower in some cases when a `Regex` is used from multiple
1332    /// threads simultaneously. Typically, performance only becomes an issue
1333    /// when there is heavy contention, which in turn usually only occurs
1334    /// when each thread's primary unit of work is a regex search on a small
1335    /// haystack.
1336    ///
1337    /// # Example
1338    ///
1339    /// ```
1340    /// use regex_automata::{meta::Regex, Input, HalfMatch};
1341    ///
1342    /// let re = Regex::new(r"Samwise|Sam")?;
1343    /// let mut cache = re.create_cache();
1344    /// let input = Input::new(
1345    ///     "one of the chief characters, Samwise the Brave",
1346    /// );
1347    /// assert_eq!(
1348    ///     Some(HalfMatch::must(0, 36)),
1349    ///     re.search_half_with(&mut cache, &input),
1350    /// );
1351    ///
1352    /// # Ok::<(), Box<dyn std::error::Error>>(())
1353    /// ```
1354    #[inline]
1355    pub fn search_half_with(
1356        &self,
1357        cache: &mut Cache,
1358        input: &Input<'_>,
1359    ) -> Option<HalfMatch> {
1360        if self.imp.info.captures_disabled()
1361            || self.imp.info.is_impossible(input)
1362        {
1363            return None;
1364        }
1365        self.imp.strat.search_half(cache, input)
1366    }
1367
1368    /// This is like [`Regex::search_captures`], but requires the caller to
1369    /// explicitly pass a [`Cache`].
1370    ///
1371    /// # Why pass a `Cache` explicitly?
1372    ///
1373    /// Passing a `Cache` explicitly will bypass the use of an internal memory
1374    /// pool used by `Regex` to get a `Cache` for a search. The use of this
1375    /// pool can be slower in some cases when a `Regex` is used from multiple
1376    /// threads simultaneously. Typically, performance only becomes an issue
1377    /// when there is heavy contention, which in turn usually only occurs
1378    /// when each thread's primary unit of work is a regex search on a small
1379    /// haystack.
1380    ///
1381    /// # Example: specific pattern search
1382    ///
1383    /// This example shows how to build a multi-pattern `Regex` that permits
1384    /// searching for specific patterns.
1385    ///
1386    /// ```
1387    /// use regex_automata::{
1388    ///     meta::Regex,
1389    ///     Anchored, Match, PatternID, Input,
1390    /// };
1391    ///
1392    /// let re = Regex::new_many(&["[a-z0-9]{6}", "[a-z][a-z0-9]{5}"])?;
1393    /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
1394    /// let haystack = "foo123";
1395    ///
1396    /// // Since we are using the default leftmost-first match and both
1397    /// // patterns match at the same starting position, only the first pattern
1398    /// // will be returned in this case when doing a search for any of the
1399    /// // patterns.
1400    /// let expected = Some(Match::must(0, 0..6));
1401    /// re.search_captures_with(&mut cache, &Input::new(haystack), &mut caps);
1402    /// assert_eq!(expected, caps.get_match());
1403    ///
1404    /// // But if we want to check whether some other pattern matches, then we
1405    /// // can provide its pattern ID.
1406    /// let expected = Some(Match::must(1, 0..6));
1407    /// let input = Input::new(haystack)
1408    ///     .anchored(Anchored::Pattern(PatternID::must(1)));
1409    /// re.search_captures_with(&mut cache, &input, &mut caps);
1410    /// assert_eq!(expected, caps.get_match());
1411    ///
1412    /// # Ok::<(), Box<dyn std::error::Error>>(())
1413    /// ```
1414    ///
1415    /// # Example: specifying the bounds of a search
1416    ///
1417    /// This example shows how providing the bounds of a search can produce
1418    /// different results than simply sub-slicing the haystack.
1419    ///
1420    /// ```
1421    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1422    /// use regex_automata::{meta::Regex, Match, Input};
1423    ///
1424    /// let re = Regex::new(r"\b[0-9]{3}\b")?;
1425    /// let (mut cache, mut caps) = (re.create_cache(), re.create_captures());
1426    /// let haystack = "foo123bar";
1427    ///
1428    /// // Since we sub-slice the haystack, the search doesn't know about
1429    /// // the larger context and assumes that `123` is surrounded by word
1430    /// // boundaries. And of course, the match position is reported relative
1431    /// // to the sub-slice as well, which means we get `0..3` instead of
1432    /// // `3..6`.
1433    /// let expected = Some(Match::must(0, 0..3));
1434    /// let input = Input::new(&haystack[3..6]);
1435    /// re.search_captures_with(&mut cache, &input, &mut caps);
1436    /// assert_eq!(expected, caps.get_match());
1437    ///
1438    /// // But if we provide the bounds of the search within the context of the
1439    /// // entire haystack, then the search can take the surrounding context
1440    /// // into account. (And if we did find a match, it would be reported
1441    /// // as a valid offset into `haystack` instead of its sub-slice.)
1442    /// let expected = None;
1443    /// let input = Input::new(haystack).range(3..6);
1444    /// re.search_captures_with(&mut cache, &input, &mut caps);
1445    /// assert_eq!(expected, caps.get_match());
1446    ///
1447    /// # Ok::<(), Box<dyn std::error::Error>>(())
1448    /// ```
1449    #[inline]
1450    pub fn search_captures_with(
1451        &self,
1452        cache: &mut Cache,
1453        input: &Input<'_>,
1454        caps: &mut Captures,
1455    ) {
1456        caps.set_pattern(None);
1457        let pid = self.search_slots_with(cache, input, caps.slots_mut());
1458        caps.set_pattern(pid);
1459    }
1460
1461    /// This is like [`Regex::search_slots`], but requires the caller to
1462    /// explicitly pass a [`Cache`].
1463    ///
1464    /// # Why pass a `Cache` explicitly?
1465    ///
1466    /// Passing a `Cache` explicitly will bypass the use of an internal memory
1467    /// pool used by `Regex` to get a `Cache` for a search. The use of this
1468    /// pool can be slower in some cases when a `Regex` is used from multiple
1469    /// threads simultaneously. Typically, performance only becomes an issue
1470    /// when there is heavy contention, which in turn usually only occurs
1471    /// when each thread's primary unit of work is a regex search on a small
1472    /// haystack.
1473    ///
1474    /// # Example
1475    ///
1476    /// This example shows how to find the overall match offsets in a
1477    /// multi-pattern search without allocating a `Captures` value. Indeed, we
1478    /// can put our slots right on the stack.
1479    ///
1480    /// ```
1481    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1482    /// use regex_automata::{meta::Regex, PatternID, Input};
1483    ///
1484    /// let re = Regex::new_many(&[
1485    ///     r"\pL+",
1486    ///     r"\d+",
1487    /// ])?;
1488    /// let mut cache = re.create_cache();
1489    /// let input = Input::new("!@#123");
1490    ///
1491    /// // We only care about the overall match offsets here, so we just
1492    /// // allocate two slots for each pattern. Each slot records the start
1493    /// // and end of the match.
1494    /// let mut slots = [None; 4];
1495    /// let pid = re.search_slots_with(&mut cache, &input, &mut slots);
1496    /// assert_eq!(Some(PatternID::must(1)), pid);
1497    ///
1498    /// // The overall match offsets are always at 'pid * 2' and 'pid * 2 + 1'.
1499    /// // See 'GroupInfo' for more details on the mapping between groups and
1500    /// // slot indices.
1501    /// let slot_start = pid.unwrap().as_usize() * 2;
1502    /// let slot_end = slot_start + 1;
1503    /// assert_eq!(Some(3), slots[slot_start].map(|s| s.get()));
1504    /// assert_eq!(Some(6), slots[slot_end].map(|s| s.get()));
1505    ///
1506    /// # Ok::<(), Box<dyn std::error::Error>>(())
1507    /// ```
1508    #[inline]
1509    pub fn search_slots_with(
1510        &self,
1511        cache: &mut Cache,
1512        input: &Input<'_>,
1513        slots: &mut [Option<NonMaxUsize>],
1514    ) -> Option<PatternID> {
1515        if self.imp.info.captures_disabled()
1516            || self.imp.info.is_impossible(input)
1517        {
1518            return None;
1519        }
1520        self.imp.strat.search_slots(cache, input, slots)
1521    }
1522
1523    /// This is like [`Regex::which_overlapping_matches`], but requires the
1524    /// caller to explicitly pass a [`Cache`].
1525    ///
1526    /// Passing a `Cache` explicitly will bypass the use of an internal memory
1527    /// pool used by `Regex` to get a `Cache` for a search. The use of this
1528    /// pool can be slower in some cases when a `Regex` is used from multiple
1529    /// threads simultaneously. Typically, performance only becomes an issue
1530    /// when there is heavy contention, which in turn usually only occurs
1531    /// when each thread's primary unit of work is a regex search on a small
1532    /// haystack.
1533    ///
1534    /// # Why pass a `Cache` explicitly?
1535    ///
1536    /// # Example
1537    ///
1538    /// ```
1539    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1540    /// use regex_automata::{meta::Regex, Input, MatchKind, PatternSet};
1541    ///
1542    /// let patterns = &[
1543    ///     r"\w+", r"\d+", r"\pL+", r"foo", r"bar", r"barfoo", r"foobar",
1544    /// ];
1545    /// let re = Regex::builder()
1546    ///     .configure(Regex::config().match_kind(MatchKind::All))
1547    ///     .build_many(patterns)?;
1548    /// let mut cache = re.create_cache();
1549    ///
1550    /// let input = Input::new("foobar");
1551    /// let mut patset = PatternSet::new(re.pattern_len());
1552    /// re.which_overlapping_matches_with(&mut cache, &input, &mut patset);
1553    /// let expected = vec![0, 2, 3, 4, 6];
1554    /// let got: Vec<usize> = patset.iter().map(|p| p.as_usize()).collect();
1555    /// assert_eq!(expected, got);
1556    ///
1557    /// # Ok::<(), Box<dyn std::error::Error>>(())
1558    /// ```
1559    #[inline]
1560    pub fn which_overlapping_matches_with(
1561        &self,
1562        cache: &mut Cache,
1563        input: &Input<'_>,
1564        patset: &mut PatternSet,
1565    ) {
1566        if self.imp.info.is_impossible(input) {
1567            return;
1568        }
1569        self.imp.strat.which_overlapping_matches(cache, input, patset)
1570    }
1571}
1572
1573/// Various non-search routines for querying properties of a `Regex` and
1574/// convenience routines for creating [`Captures`] and [`Cache`] values.
1575impl Regex {
1576    /// Creates a new object for recording capture group offsets. This is used
1577    /// in search APIs like [`Regex::captures`] and [`Regex::search_captures`].
1578    ///
1579    /// This is a convenience routine for
1580    /// `Captures::all(re.group_info().clone())`. Callers may build other types
1581    /// of `Captures` values that record less information (and thus require
1582    /// less work from the regex engine) using [`Captures::matches`] and
1583    /// [`Captures::empty`].
1584    ///
1585    /// # Example
1586    ///
1587    /// This shows some alternatives to [`Regex::create_captures`]:
1588    ///
1589    /// ```
1590    /// use regex_automata::{
1591    ///     meta::Regex,
1592    ///     util::captures::Captures,
1593    ///     Match, PatternID, Span,
1594    /// };
1595    ///
1596    /// let re = Regex::new(r"(?<first>[A-Z][a-z]+) (?<last>[A-Z][a-z]+)")?;
1597    ///
1598    /// // This is equivalent to Regex::create_captures. It stores matching
1599    /// // offsets for all groups in the regex.
1600    /// let mut all = Captures::all(re.group_info().clone());
1601    /// re.captures("Bruce Springsteen", &mut all);
1602    /// assert_eq!(Some(Match::must(0, 0..17)), all.get_match());
1603    /// assert_eq!(Some(Span::from(0..5)), all.get_group_by_name("first"));
1604    /// assert_eq!(Some(Span::from(6..17)), all.get_group_by_name("last"));
1605    ///
1606    /// // In this version, we only care about the implicit groups, which
1607    /// // means offsets for the explicit groups will be unavailable. It can
1608    /// // sometimes be faster to ask for fewer groups, since the underlying
1609    /// // regex engine needs to do less work to keep track of them.
1610    /// let mut matches = Captures::matches(re.group_info().clone());
1611    /// re.captures("Bruce Springsteen", &mut matches);
1612    /// // We still get the overall match info.
1613    /// assert_eq!(Some(Match::must(0, 0..17)), matches.get_match());
1614    /// // But now the explicit groups are unavailable.
1615    /// assert_eq!(None, matches.get_group_by_name("first"));
1616    /// assert_eq!(None, matches.get_group_by_name("last"));
1617    ///
1618    /// // Finally, in this version, we don't ask to keep track of offsets for
1619    /// // *any* groups. All we get back is whether a match occurred, and if
1620    /// // so, the ID of the pattern that matched.
1621    /// let mut empty = Captures::empty(re.group_info().clone());
1622    /// re.captures("Bruce Springsteen", &mut empty);
1623    /// // it's a match!
1624    /// assert!(empty.is_match());
1625    /// // for pattern ID 0
1626    /// assert_eq!(Some(PatternID::ZERO), empty.pattern());
1627    /// // Match offsets are unavailable.
1628    /// assert_eq!(None, empty.get_match());
1629    /// // And of course, explicit groups are unavailable too.
1630    /// assert_eq!(None, empty.get_group_by_name("first"));
1631    /// assert_eq!(None, empty.get_group_by_name("last"));
1632    ///
1633    /// # Ok::<(), Box<dyn std::error::Error>>(())
1634    /// ```
1635    pub fn create_captures(&self) -> Captures {
1636        Captures::all(self.group_info().clone())
1637    }
1638
1639    /// Creates a new cache for use with lower level search APIs like
1640    /// [`Regex::search_with`].
1641    ///
1642    /// The cache returned should only be used for searches for this `Regex`.
1643    /// If you want to reuse the cache for another `Regex`, then you must call
1644    /// [`Cache::reset`] with that `Regex`.
1645    ///
1646    /// This is a convenience routine for [`Cache::new`].
1647    ///
1648    /// # Example
1649    ///
1650    /// ```
1651    /// use regex_automata::{meta::Regex, Input, Match};
1652    ///
1653    /// let re = Regex::new(r"(?-u)m\w+\s+m\w+")?;
1654    /// let mut cache = re.create_cache();
1655    /// let input = Input::new("crazy janey and her mission man");
1656    /// assert_eq!(
1657    ///     Some(Match::must(0, 20..31)),
1658    ///     re.search_with(&mut cache, &input),
1659    /// );
1660    ///
1661    /// # Ok::<(), Box<dyn std::error::Error>>(())
1662    /// ```
1663    pub fn create_cache(&self) -> Cache {
1664        self.imp.strat.create_cache()
1665    }
1666
1667    /// Returns the total number of patterns in this regex.
1668    ///
1669    /// The standard [`Regex::new`] constructor always results in a `Regex`
1670    /// with a single pattern, but [`Regex::new_many`] permits building a
1671    /// multi-pattern regex.
1672    ///
1673    /// A `Regex` guarantees that the maximum possible `PatternID` returned in
1674    /// any match is `Regex::pattern_len() - 1`. In the case where the number
1675    /// of patterns is `0`, a match is impossible.
1676    ///
1677    /// # Example
1678    ///
1679    /// ```
1680    /// use regex_automata::meta::Regex;
1681    ///
1682    /// let re = Regex::new(r"(?m)^[a-z]$")?;
1683    /// assert_eq!(1, re.pattern_len());
1684    ///
1685    /// let re = Regex::new_many::<&str>(&[])?;
1686    /// assert_eq!(0, re.pattern_len());
1687    ///
1688    /// let re = Regex::new_many(&["a", "b", "c"])?;
1689    /// assert_eq!(3, re.pattern_len());
1690    ///
1691    /// # Ok::<(), Box<dyn std::error::Error>>(())
1692    /// ```
1693    pub fn pattern_len(&self) -> usize {
1694        self.imp.info.pattern_len()
1695    }
1696
1697    /// Returns the total number of capturing groups.
1698    ///
1699    /// This includes the implicit capturing group corresponding to the
1700    /// entire match. Therefore, the minimum value returned is `1`.
1701    ///
1702    /// # Example
1703    ///
1704    /// This shows a few patterns and how many capture groups they have.
1705    ///
1706    /// ```
1707    /// use regex_automata::meta::Regex;
1708    ///
1709    /// let len = |pattern| {
1710    ///     Regex::new(pattern).map(|re| re.captures_len())
1711    /// };
1712    ///
1713    /// assert_eq!(1, len("a")?);
1714    /// assert_eq!(2, len("(a)")?);
1715    /// assert_eq!(3, len("(a)|(b)")?);
1716    /// assert_eq!(5, len("(a)(b)|(c)(d)")?);
1717    /// assert_eq!(2, len("(a)|b")?);
1718    /// assert_eq!(2, len("a|(b)")?);
1719    /// assert_eq!(2, len("(b)*")?);
1720    /// assert_eq!(2, len("(b)+")?);
1721    ///
1722    /// # Ok::<(), Box<dyn std::error::Error>>(())
1723    /// ```
1724    ///
1725    /// # Example: multiple patterns
1726    ///
1727    /// This routine also works for multiple patterns. The total number is
1728    /// the sum of the capture groups of each pattern.
1729    ///
1730    /// ```
1731    /// use regex_automata::meta::Regex;
1732    ///
1733    /// let len = |patterns| {
1734    ///     Regex::new_many(patterns).map(|re| re.captures_len())
1735    /// };
1736    ///
1737    /// assert_eq!(2, len(&["a", "b"])?);
1738    /// assert_eq!(4, len(&["(a)", "(b)"])?);
1739    /// assert_eq!(6, len(&["(a)|(b)", "(c)|(d)"])?);
1740    /// assert_eq!(8, len(&["(a)(b)|(c)(d)", "(x)(y)"])?);
1741    /// assert_eq!(3, len(&["(a)", "b"])?);
1742    /// assert_eq!(3, len(&["a", "(b)"])?);
1743    /// assert_eq!(4, len(&["(a)", "(b)*"])?);
1744    /// assert_eq!(4, len(&["(a)+", "(b)+"])?);
1745    ///
1746    /// # Ok::<(), Box<dyn std::error::Error>>(())
1747    /// ```
1748    pub fn captures_len(&self) -> usize {
1749        self.imp
1750            .info
1751            .props_union()
1752            .explicit_captures_len()
1753            .saturating_add(self.pattern_len())
1754    }
1755
1756    /// Returns the total number of capturing groups that appear in every
1757    /// possible match.
1758    ///
1759    /// If the number of capture groups can vary depending on the match, then
1760    /// this returns `None`. That is, a value is only returned when the number
1761    /// of matching groups is invariant or "static."
1762    ///
1763    /// Note that like [`Regex::captures_len`], this **does** include the
1764    /// implicit capturing group corresponding to the entire match. Therefore,
1765    /// when a non-None value is returned, it is guaranteed to be at least `1`.
1766    /// Stated differently, a return value of `Some(0)` is impossible.
1767    ///
1768    /// # Example
1769    ///
1770    /// This shows a few cases where a static number of capture groups is
1771    /// available and a few cases where it is not.
1772    ///
1773    /// ```
1774    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1775    ///
1776    /// use regex_automata::meta::Regex;
1777    ///
1778    /// let len = |pattern| {
1779    ///     Regex::new(pattern).map(|re| re.static_captures_len())
1780    /// };
1781    ///
1782    /// assert_eq!(Some(1), len("a")?);
1783    /// assert_eq!(Some(2), len("(a)")?);
1784    /// assert_eq!(Some(2), len("(a)|(b)")?);
1785    /// assert_eq!(Some(3), len("(a)(b)|(c)(d)")?);
1786    /// assert_eq!(None, len("(a)|b")?);
1787    /// assert_eq!(None, len("a|(b)")?);
1788    /// assert_eq!(None, len("(b)*")?);
1789    /// assert_eq!(Some(2), len("(b)+")?);
1790    ///
1791    /// # Ok::<(), Box<dyn std::error::Error>>(())
1792    /// ```
1793    ///
1794    /// # Example: multiple patterns
1795    ///
1796    /// This property extends to regexes with multiple patterns as well. In
1797    /// order for their to be a static number of capture groups in this case,
1798    /// every pattern must have the same static number.
1799    ///
1800    /// ```
1801    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
1802    ///
1803    /// use regex_automata::meta::Regex;
1804    ///
1805    /// let len = |patterns| {
1806    ///     Regex::new_many(patterns).map(|re| re.static_captures_len())
1807    /// };
1808    ///
1809    /// assert_eq!(Some(1), len(&["a", "b"])?);
1810    /// assert_eq!(Some(2), len(&["(a)", "(b)"])?);
1811    /// assert_eq!(Some(2), len(&["(a)|(b)", "(c)|(d)"])?);
1812    /// assert_eq!(Some(3), len(&["(a)(b)|(c)(d)", "(x)(y)"])?);
1813    /// assert_eq!(None, len(&["(a)", "b"])?);
1814    /// assert_eq!(None, len(&["a", "(b)"])?);
1815    /// assert_eq!(None, len(&["(a)", "(b)*"])?);
1816    /// assert_eq!(Some(2), len(&["(a)+", "(b)+"])?);
1817    ///
1818    /// # Ok::<(), Box<dyn std::error::Error>>(())
1819    /// ```
1820    #[inline]
1821    pub fn static_captures_len(&self) -> Option<usize> {
1822        self.imp
1823            .info
1824            .props_union()
1825            .static_explicit_captures_len()
1826            .map(|len| len.saturating_add(1))
1827    }
1828
1829    /// Return information about the capture groups in this `Regex`.
1830    ///
1831    /// A `GroupInfo` is an immutable object that can be cheaply cloned. It
1832    /// is responsible for maintaining a mapping between the capture groups
1833    /// in the concrete syntax of zero or more regex patterns and their
1834    /// internal representation used by some of the regex matchers. It is also
1835    /// responsible for maintaining a mapping between the name of each group
1836    /// (if one exists) and its corresponding group index.
1837    ///
1838    /// A `GroupInfo` is ultimately what is used to build a [`Captures`] value,
1839    /// which is some mutable space where group offsets are stored as a result
1840    /// of a search.
1841    ///
1842    /// # Example
1843    ///
1844    /// This shows some alternatives to [`Regex::create_captures`]:
1845    ///
1846    /// ```
1847    /// use regex_automata::{
1848    ///     meta::Regex,
1849    ///     util::captures::Captures,
1850    ///     Match, PatternID, Span,
1851    /// };
1852    ///
1853    /// let re = Regex::new(r"(?<first>[A-Z][a-z]+) (?<last>[A-Z][a-z]+)")?;
1854    ///
1855    /// // This is equivalent to Regex::create_captures. It stores matching
1856    /// // offsets for all groups in the regex.
1857    /// let mut all = Captures::all(re.group_info().clone());
1858    /// re.captures("Bruce Springsteen", &mut all);
1859    /// assert_eq!(Some(Match::must(0, 0..17)), all.get_match());
1860    /// assert_eq!(Some(Span::from(0..5)), all.get_group_by_name("first"));
1861    /// assert_eq!(Some(Span::from(6..17)), all.get_group_by_name("last"));
1862    ///
1863    /// // In this version, we only care about the implicit groups, which
1864    /// // means offsets for the explicit groups will be unavailable. It can
1865    /// // sometimes be faster to ask for fewer groups, since the underlying
1866    /// // regex engine needs to do less work to keep track of them.
1867    /// let mut matches = Captures::matches(re.group_info().clone());
1868    /// re.captures("Bruce Springsteen", &mut matches);
1869    /// // We still get the overall match info.
1870    /// assert_eq!(Some(Match::must(0, 0..17)), matches.get_match());
1871    /// // But now the explicit groups are unavailable.
1872    /// assert_eq!(None, matches.get_group_by_name("first"));
1873    /// assert_eq!(None, matches.get_group_by_name("last"));
1874    ///
1875    /// // Finally, in this version, we don't ask to keep track of offsets for
1876    /// // *any* groups. All we get back is whether a match occurred, and if
1877    /// // so, the ID of the pattern that matched.
1878    /// let mut empty = Captures::empty(re.group_info().clone());
1879    /// re.captures("Bruce Springsteen", &mut empty);
1880    /// // it's a match!
1881    /// assert!(empty.is_match());
1882    /// // for pattern ID 0
1883    /// assert_eq!(Some(PatternID::ZERO), empty.pattern());
1884    /// // Match offsets are unavailable.
1885    /// assert_eq!(None, empty.get_match());
1886    /// // And of course, explicit groups are unavailable too.
1887    /// assert_eq!(None, empty.get_group_by_name("first"));
1888    /// assert_eq!(None, empty.get_group_by_name("last"));
1889    ///
1890    /// # Ok::<(), Box<dyn std::error::Error>>(())
1891    /// ```
1892    #[inline]
1893    pub fn group_info(&self) -> &GroupInfo {
1894        self.imp.strat.group_info()
1895    }
1896
1897    /// Returns the configuration object used to build this `Regex`.
1898    ///
1899    /// If no configuration object was explicitly passed, then the
1900    /// configuration returned represents the default.
1901    #[inline]
1902    pub fn get_config(&self) -> &Config {
1903        self.imp.info.config()
1904    }
1905
1906    /// Returns true if this regex has a high chance of being "accelerated."
1907    ///
1908    /// The precise meaning of "accelerated" is specifically left unspecified,
1909    /// but the general meaning is that the search is a high likelihood of
1910    /// running faster than a character-at-a-time loop inside a standard
1911    /// regex engine.
1912    ///
1913    /// When a regex is accelerated, it is only a *probabilistic* claim. That
1914    /// is, just because the regex is believed to be accelerated, that doesn't
1915    /// mean it will definitely execute searches very fast. Similarly, if a
1916    /// regex is *not* accelerated, that is also a probabilistic claim. That
1917    /// is, a regex for which `is_accelerated` returns `false` could still run
1918    /// searches more quickly than a regex for which `is_accelerated` returns
1919    /// `true`.
1920    ///
1921    /// Whether a regex is marked as accelerated or not is dependent on
1922    /// implementations details that may change in a semver compatible release.
1923    /// That is, a regex that is accelerated in a `x.y.1` release might not be
1924    /// accelerated in a `x.y.2` release.
1925    ///
1926    /// Basically, the value of acceleration boils down to a hedge: a hodge
1927    /// podge of internal heuristics combine to make a probabilistic guess
1928    /// that this regex search may run "fast." The value in knowing this from
1929    /// a caller's perspective is that it may act as a signal that no further
1930    /// work should be done to accelerate a search. For example, a grep-like
1931    /// tool might try to do some extra work extracting literals from a regex
1932    /// to create its own heuristic acceleration strategies. But it might
1933    /// choose to defer to this crate's acceleration strategy if one exists.
1934    /// This routine permits querying whether such a strategy is active for a
1935    /// particular regex.
1936    ///
1937    /// # Example
1938    ///
1939    /// ```
1940    /// use regex_automata::meta::Regex;
1941    ///
1942    /// // A simple literal is very likely to be accelerated.
1943    /// let re = Regex::new(r"foo")?;
1944    /// assert!(re.is_accelerated());
1945    ///
1946    /// // A regex with no literals is likely to not be accelerated.
1947    /// let re = Regex::new(r"\w")?;
1948    /// assert!(!re.is_accelerated());
1949    ///
1950    /// # Ok::<(), Box<dyn std::error::Error>>(())
1951    /// ```
1952    #[inline]
1953    pub fn is_accelerated(&self) -> bool {
1954        self.imp.strat.is_accelerated()
1955    }
1956
1957    /// Return the total approximate heap memory, in bytes, used by this `Regex`.
1958    ///
1959    /// Note that currently, there is no high level configuration for setting
1960    /// a limit on the specific value returned by this routine. Instead, the
1961    /// following routines can be used to control heap memory at a bit of a
1962    /// lower level:
1963    ///
1964    /// * [`Config::nfa_size_limit`] controls how big _any_ of the NFAs are
1965    /// allowed to be.
1966    /// * [`Config::onepass_size_limit`] controls how big the one-pass DFA is
1967    /// allowed to be.
1968    /// * [`Config::hybrid_cache_capacity`] controls how much memory the lazy
1969    /// DFA is permitted to allocate to store its transition table.
1970    /// * [`Config::dfa_size_limit`] controls how big a fully compiled DFA is
1971    /// allowed to be.
1972    /// * [`Config::dfa_state_limit`] controls the conditions under which the
1973    /// meta regex engine will even attempt to build a fully compiled DFA.
1974    #[inline]
1975    pub fn memory_usage(&self) -> usize {
1976        self.imp.strat.memory_usage()
1977    }
1978}
1979
1980impl Clone for Regex {
1981    fn clone(&self) -> Regex {
1982        let imp = Arc::clone(&self.imp);
1983        let pool = {
1984            let strat = Arc::clone(&imp.strat);
1985            let create: CachePoolFn = Box::new(move || strat.create_cache());
1986            Pool::with_capacity(
1987                self.imp.info.config().get_pool_capacity(),
1988                create,
1989            )
1990        };
1991        Regex { imp, pool }
1992    }
1993}
1994
1995#[derive(Clone, Debug)]
1996pub(crate) struct RegexInfo(Arc<RegexInfoI>);
1997
1998#[derive(Clone, Debug)]
1999struct RegexInfoI {
2000    config: Config,
2001    props: Vec<hir::Properties>,
2002    props_union: hir::Properties,
2003}
2004
2005impl RegexInfo {
2006    /// Creates a new `RegexInfo` from the configuration and HIRs that make up
2007    /// a meta regex.
2008    ///
2009    /// This is exported for use in some tests.
2010    pub(super) fn new(config: Config, hirs: &[&Hir]) -> RegexInfo {
2011        // Collect all of the properties from each of the HIRs, and also
2012        // union them into one big set of properties representing all HIRs
2013        // as if they were in one big alternation.
2014        let mut props = vec![];
2015        for hir in hirs.iter() {
2016            props.push(hir.properties().clone());
2017        }
2018        let props_union = hir::Properties::union(&props);
2019
2020        RegexInfo(Arc::new(RegexInfoI { config, props, props_union }))
2021    }
2022
2023    pub(crate) fn config(&self) -> &Config {
2024        &self.0.config
2025    }
2026
2027    pub(crate) fn props(&self) -> &[hir::Properties] {
2028        &self.0.props
2029    }
2030
2031    pub(crate) fn props_union(&self) -> &hir::Properties {
2032        &self.0.props_union
2033    }
2034
2035    pub(crate) fn pattern_len(&self) -> usize {
2036        self.props().len()
2037    }
2038
2039    pub(crate) fn memory_usage(&self) -> usize {
2040        self.props().iter().map(|p| p.memory_usage()).sum::<usize>()
2041            + self.props_union().memory_usage()
2042    }
2043
2044    /// Returns true when the search is guaranteed to be anchored. That is,
2045    /// when a match is reported, its offset is guaranteed to correspond to
2046    /// the start of the search.
2047    ///
2048    /// This includes returning true when `input` _isn't_ anchored but the
2049    /// underlying regex is.
2050    #[cfg_attr(feature = "perf-inline", inline(always))]
2051    pub(crate) fn is_anchored_start(&self, input: &Input<'_>) -> bool {
2052        input.get_anchored().is_anchored() || self.is_always_anchored_start()
2053    }
2054
2055    /// Returns true when this regex is always anchored to the start of a
2056    /// search. And in particular, that regardless of an `Input` configuration,
2057    /// if any match is reported it must start at `0`.
2058    #[cfg_attr(feature = "perf-inline", inline(always))]
2059    pub(crate) fn is_always_anchored_start(&self) -> bool {
2060        use regex_syntax::hir::Look;
2061        self.props_union().look_set_prefix().contains(Look::Start)
2062    }
2063
2064    /// Returns true when this regex is always anchored to the end of a
2065    /// search. And in particular, that regardless of an `Input` configuration,
2066    /// if any match is reported it must end at the end of the haystack.
2067    #[cfg_attr(feature = "perf-inline", inline(always))]
2068    pub(crate) fn is_always_anchored_end(&self) -> bool {
2069        use regex_syntax::hir::Look;
2070        self.props_union().look_set_suffix().contains(Look::End)
2071    }
2072
2073    /// Returns true when the regex's NFA lacks capture states.
2074    ///
2075    /// In this case, some regex engines (like the PikeVM) are unable to report
2076    /// match offsets, while some (like the lazy DFA can). To avoid whether a
2077    /// match or not is reported based on engine selection, routines that
2078    /// return match offsets will _always_ report `None` when this is true.
2079    ///
2080    /// Yes, this is a weird case and it's a little fucked up. But
2081    /// `WhichCaptures::None` comes with an appropriate warning.
2082    fn captures_disabled(&self) -> bool {
2083        matches!(self.config().get_which_captures(), WhichCaptures::None)
2084    }
2085
2086    /// Returns true if and only if it is known that a match is impossible
2087    /// for the given input. This is useful for short-circuiting and avoiding
2088    /// running the regex engine if it's known no match can be reported.
2089    ///
2090    /// Note that this doesn't necessarily detect every possible case. For
2091    /// example, when `pattern_len() == 0`, a match is impossible, but that
2092    /// case is so rare that it's fine to be handled by the regex engine
2093    /// itself. That is, it's not worth the cost of adding it here in order to
2094    /// make it a little faster. The reason is that this is called for every
2095    /// search. so there is some cost to adding checks here. Arguably, some of
2096    /// the checks that are here already probably shouldn't be here...
2097    #[cfg_attr(feature = "perf-inline", inline(always))]
2098    fn is_impossible(&self, input: &Input<'_>) -> bool {
2099        // The underlying regex is anchored, so if we don't start the search
2100        // at position 0, a match is impossible, because the anchor can only
2101        // match at position 0.
2102        if input.start() > 0 && self.is_always_anchored_start() {
2103            return true;
2104        }
2105        // Same idea, but for the end anchor.
2106        if input.end() < input.haystack().len()
2107            && self.is_always_anchored_end()
2108        {
2109            return true;
2110        }
2111        // If the haystack is smaller than the minimum length required, then
2112        // we know there can be no match.
2113        let minlen = match self.props_union().minimum_len() {
2114            None => return false,
2115            Some(minlen) => minlen,
2116        };
2117        if input.get_span().len() < minlen {
2118            return true;
2119        }
2120        // Same idea as minimum, but for maximum. This is trickier. We can
2121        // only apply the maximum when we know the entire span that we're
2122        // searching *has* to match according to the regex (and possibly the
2123        // input configuration). If we know there is too much for the regex
2124        // to match, we can bail early.
2125        //
2126        // I don't think we can apply the maximum otherwise unfortunately.
2127        if self.is_anchored_start(input) && self.is_always_anchored_end() {
2128            let maxlen = match self.props_union().maximum_len() {
2129                None => return false,
2130                Some(maxlen) => maxlen,
2131            };
2132            if input.get_span().len() > maxlen {
2133                return true;
2134            }
2135        }
2136        false
2137    }
2138}
2139
2140/// An iterator over all non-overlapping matches.
2141///
2142/// The iterator yields a [`Match`] value until no more matches could be found.
2143///
2144/// The lifetime parameters are as follows:
2145///
2146/// * `'r` represents the lifetime of the `Regex` that produced this iterator.
2147/// * `'h` represents the lifetime of the haystack being searched.
2148///
2149/// This iterator can be created with the [`Regex::find_iter`] method.
2150#[derive(Debug)]
2151pub struct FindMatches<'r, 'h> {
2152    re: &'r Regex,
2153    cache: CachePoolGuard<'r>,
2154    it: iter::Searcher<'h>,
2155}
2156
2157impl<'r, 'h> FindMatches<'r, 'h> {
2158    /// Returns the `Regex` value that created this iterator.
2159    #[inline]
2160    pub fn regex(&self) -> &'r Regex {
2161        self.re
2162    }
2163
2164    /// Returns the current `Input` associated with this iterator.
2165    ///
2166    /// The `start` position on the given `Input` may change during iteration,
2167    /// but all other values are guaranteed to remain invariant.
2168    #[inline]
2169    pub fn input<'s>(&'s self) -> &'s Input<'h> {
2170        self.it.input()
2171    }
2172}
2173
2174impl<'r, 'h> Iterator for FindMatches<'r, 'h> {
2175    type Item = Match;
2176
2177    #[inline]
2178    fn next(&mut self) -> Option<Match> {
2179        let FindMatches { re, ref mut cache, ref mut it } = *self;
2180        it.advance(|input| Ok(re.search_with(cache, input)))
2181    }
2182
2183    #[inline]
2184    fn count(self) -> usize {
2185        // If all we care about is a count of matches, then we only need to
2186        // find the end position of each match. This can give us a 2x perf
2187        // boost in some cases, because it avoids needing to do a reverse scan
2188        // to find the start of a match.
2189        let FindMatches { re, mut cache, it } = self;
2190        // This does the deref for PoolGuard once instead of every iter.
2191        let cache = &mut *cache;
2192        it.into_half_matches_iter(
2193            |input| Ok(re.search_half_with(cache, input)),
2194        )
2195        .count()
2196    }
2197}
2198
2199impl<'r, 'h> core::iter::FusedIterator for FindMatches<'r, 'h> {}
2200
2201/// An iterator over all non-overlapping leftmost matches with their capturing
2202/// groups.
2203///
2204/// The iterator yields a [`Captures`] value until no more matches could be
2205/// found.
2206///
2207/// The lifetime parameters are as follows:
2208///
2209/// * `'r` represents the lifetime of the `Regex` that produced this iterator.
2210/// * `'h` represents the lifetime of the haystack being searched.
2211///
2212/// This iterator can be created with the [`Regex::captures_iter`] method.
2213#[derive(Debug)]
2214pub struct CapturesMatches<'r, 'h> {
2215    re: &'r Regex,
2216    cache: CachePoolGuard<'r>,
2217    caps: Captures,
2218    it: iter::Searcher<'h>,
2219}
2220
2221impl<'r, 'h> CapturesMatches<'r, 'h> {
2222    /// Returns the `Regex` value that created this iterator.
2223    #[inline]
2224    pub fn regex(&self) -> &'r Regex {
2225        self.re
2226    }
2227
2228    /// Returns the current `Input` associated with this iterator.
2229    ///
2230    /// The `start` position on the given `Input` may change during iteration,
2231    /// but all other values are guaranteed to remain invariant.
2232    #[inline]
2233    pub fn input<'s>(&'s self) -> &'s Input<'h> {
2234        self.it.input()
2235    }
2236}
2237
2238impl<'r, 'h> Iterator for CapturesMatches<'r, 'h> {
2239    type Item = Captures;
2240
2241    #[inline]
2242    fn next(&mut self) -> Option<Captures> {
2243        // Splitting 'self' apart seems necessary to appease borrowck.
2244        let CapturesMatches { re, ref mut cache, ref mut caps, ref mut it } =
2245            *self;
2246        let _ = it.advance(|input| {
2247            re.search_captures_with(cache, input, caps);
2248            Ok(caps.get_match())
2249        });
2250        if caps.is_match() {
2251            Some(caps.clone())
2252        } else {
2253            None
2254        }
2255    }
2256
2257    #[inline]
2258    fn count(self) -> usize {
2259        let CapturesMatches { re, mut cache, it, .. } = self;
2260        // This does the deref for PoolGuard once instead of every iter.
2261        let cache = &mut *cache;
2262        it.into_half_matches_iter(
2263            |input| Ok(re.search_half_with(cache, input)),
2264        )
2265        .count()
2266    }
2267}
2268
2269impl<'r, 'h> core::iter::FusedIterator for CapturesMatches<'r, 'h> {}
2270
2271/// Yields all substrings delimited by a regular expression match.
2272///
2273/// The spans correspond to the offsets between matches.
2274///
2275/// The lifetime parameters are as follows:
2276///
2277/// * `'r` represents the lifetime of the `Regex` that produced this iterator.
2278/// * `'h` represents the lifetime of the haystack being searched.
2279///
2280/// This iterator can be created with the [`Regex::split`] method.
2281#[derive(Debug)]
2282pub struct Split<'r, 'h> {
2283    finder: FindMatches<'r, 'h>,
2284    last: usize,
2285}
2286
2287impl<'r, 'h> Split<'r, 'h> {
2288    /// Returns the current `Input` associated with this iterator.
2289    ///
2290    /// The `start` position on the given `Input` may change during iteration,
2291    /// but all other values are guaranteed to remain invariant.
2292    #[inline]
2293    pub fn input<'s>(&'s self) -> &'s Input<'h> {
2294        self.finder.input()
2295    }
2296}
2297
2298impl<'r, 'h> Iterator for Split<'r, 'h> {
2299    type Item = Span;
2300
2301    fn next(&mut self) -> Option<Span> {
2302        match self.finder.next() {
2303            None => {
2304                let len = self.finder.it.input().haystack().len();
2305                if self.last > len {
2306                    None
2307                } else {
2308                    let span = Span::from(self.last..len);
2309                    self.last = len + 1; // Next call will return None
2310                    Some(span)
2311                }
2312            }
2313            Some(m) => {
2314                let span = Span::from(self.last..m.start());
2315                self.last = m.end();
2316                Some(span)
2317            }
2318        }
2319    }
2320}
2321
2322impl<'r, 'h> core::iter::FusedIterator for Split<'r, 'h> {}
2323
2324/// Yields at most `N` spans delimited by a regular expression match.
2325///
2326/// The spans correspond to the offsets between matches. The last span will be
2327/// whatever remains after splitting.
2328///
2329/// The lifetime parameters are as follows:
2330///
2331/// * `'r` represents the lifetime of the `Regex` that produced this iterator.
2332/// * `'h` represents the lifetime of the haystack being searched.
2333///
2334/// This iterator can be created with the [`Regex::splitn`] method.
2335#[derive(Debug)]
2336pub struct SplitN<'r, 'h> {
2337    splits: Split<'r, 'h>,
2338    limit: usize,
2339}
2340
2341impl<'r, 'h> SplitN<'r, 'h> {
2342    /// Returns the current `Input` associated with this iterator.
2343    ///
2344    /// The `start` position on the given `Input` may change during iteration,
2345    /// but all other values are guaranteed to remain invariant.
2346    #[inline]
2347    pub fn input<'s>(&'s self) -> &'s Input<'h> {
2348        self.splits.input()
2349    }
2350}
2351
2352impl<'r, 'h> Iterator for SplitN<'r, 'h> {
2353    type Item = Span;
2354
2355    fn next(&mut self) -> Option<Span> {
2356        if self.limit == 0 {
2357            return None;
2358        }
2359
2360        self.limit -= 1;
2361        if self.limit > 0 {
2362            return self.splits.next();
2363        }
2364
2365        let len = self.splits.finder.it.input().haystack().len();
2366        if self.splits.last > len {
2367            // We've already returned all substrings.
2368            None
2369        } else {
2370            // self.n == 0, so future calls will return None immediately
2371            Some(Span::from(self.splits.last..len))
2372        }
2373    }
2374
2375    fn size_hint(&self) -> (usize, Option<usize>) {
2376        (0, Some(self.limit))
2377    }
2378}
2379
2380impl<'r, 'h> core::iter::FusedIterator for SplitN<'r, 'h> {}
2381
2382/// Represents mutable scratch space used by regex engines during a search.
2383///
2384/// Most of the regex engines in this crate require some kind of
2385/// mutable state in order to execute a search. This mutable state is
2386/// explicitly separated from the core regex object (such as a
2387/// [`thompson::NFA`](crate::nfa::thompson::NFA)) so that the read-only regex
2388/// object can be shared across multiple threads simultaneously without any
2389/// synchronization. Conversely, a `Cache` must either be duplicated if using
2390/// the same `Regex` from multiple threads, or else there must be some kind of
2391/// synchronization that guarantees exclusive access while it's in use by one
2392/// thread.
2393///
2394/// A `Regex` attempts to do this synchronization for you by using a thread
2395/// pool internally. Its size scales roughly with the number of simultaneous
2396/// regex searches.
2397///
2398/// For cases where one does not want to rely on a `Regex`'s internal thread
2399/// pool, lower level routines such as [`Regex::search_with`] are provided
2400/// that permit callers to pass a `Cache` into the search routine explicitly.
2401///
2402/// General advice is that the thread pool is often more than good enough.
2403/// However, it may be possible to observe the effects of its latency,
2404/// especially when searching many small haystacks from many threads
2405/// simultaneously.
2406///
2407/// Caches can be created from their corresponding `Regex` via
2408/// [`Regex::create_cache`]. A cache can only be used with either the `Regex`
2409/// that created it, or the `Regex` that was most recently used to reset it
2410/// with [`Cache::reset`]. Using a cache with any other `Regex` may result in
2411/// panics or incorrect results.
2412///
2413/// # Example
2414///
2415/// ```
2416/// use regex_automata::{meta::Regex, Input, Match};
2417///
2418/// let re = Regex::new(r"(?-u)m\w+\s+m\w+")?;
2419/// let mut cache = re.create_cache();
2420/// let input = Input::new("crazy janey and her mission man");
2421/// assert_eq!(
2422///     Some(Match::must(0, 20..31)),
2423///     re.search_with(&mut cache, &input),
2424/// );
2425///
2426/// # Ok::<(), Box<dyn std::error::Error>>(())
2427/// ```
2428#[derive(Debug, Clone)]
2429pub struct Cache {
2430    pub(crate) capmatches: Captures,
2431    pub(crate) pikevm: wrappers::PikeVMCache,
2432    pub(crate) backtrack: wrappers::BoundedBacktrackerCache,
2433    pub(crate) onepass: wrappers::OnePassCache,
2434    pub(crate) hybrid: wrappers::HybridCache,
2435    pub(crate) revhybrid: wrappers::ReverseHybridCache,
2436}
2437
2438impl Cache {
2439    /// Creates a new `Cache` for use with this regex.
2440    ///
2441    /// The cache returned should only be used for searches for the given
2442    /// `Regex`. If you want to reuse the cache for another `Regex`, then you
2443    /// must call [`Cache::reset`] with that `Regex`.
2444    pub fn new(re: &Regex) -> Cache {
2445        re.create_cache()
2446    }
2447
2448    /// Reset this cache such that it can be used for searching with the given
2449    /// `Regex` (and only that `Regex`).
2450    ///
2451    /// A cache reset permits potentially reusing memory already allocated in
2452    /// this cache with a different `Regex`.
2453    ///
2454    /// # Example
2455    ///
2456    /// This shows how to re-purpose a cache for use with a different `Regex`.
2457    ///
2458    /// ```
2459    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
2460    /// use regex_automata::{meta::Regex, Match, Input};
2461    ///
2462    /// let re1 = Regex::new(r"\w")?;
2463    /// let re2 = Regex::new(r"\W")?;
2464    ///
2465    /// let mut cache = re1.create_cache();
2466    /// assert_eq!(
2467    ///     Some(Match::must(0, 0..2)),
2468    ///     re1.search_with(&mut cache, &Input::new("Δ")),
2469    /// );
2470    ///
2471    /// // Using 'cache' with re2 is not allowed. It may result in panics or
2472    /// // incorrect results. In order to re-purpose the cache, we must reset
2473    /// // it with the Regex we'd like to use it with.
2474    /// //
2475    /// // Similarly, after this reset, using the cache with 're1' is also not
2476    /// // allowed.
2477    /// cache.reset(&re2);
2478    /// assert_eq!(
2479    ///     Some(Match::must(0, 0..3)),
2480    ///     re2.search_with(&mut cache, &Input::new("☃")),
2481    /// );
2482    ///
2483    /// # Ok::<(), Box<dyn std::error::Error>>(())
2484    /// ```
2485    pub fn reset(&mut self, re: &Regex) {
2486        re.imp.strat.reset_cache(self)
2487    }
2488
2489    /// Returns the heap memory usage, in bytes, of this cache.
2490    ///
2491    /// This does **not** include the stack size used up by this cache. To
2492    /// compute that, use `std::mem::size_of::<Cache>()`.
2493    pub fn memory_usage(&self) -> usize {
2494        let mut bytes = 0;
2495        bytes += self.pikevm.memory_usage();
2496        bytes += self.backtrack.memory_usage();
2497        bytes += self.onepass.memory_usage();
2498        bytes += self.hybrid.memory_usage();
2499        bytes += self.revhybrid.memory_usage();
2500        bytes
2501    }
2502}
2503
2504/// An object describing the configuration of a `Regex`.
2505///
2506/// This configuration only includes options for the
2507/// non-syntax behavior of a `Regex`, and can be applied via the
2508/// [`Builder::configure`] method. For configuring the syntax options, see
2509/// [`util::syntax::Config`](crate::util::syntax::Config).
2510///
2511/// # Example: lower the NFA size limit
2512///
2513/// In some cases, the default size limit might be too big. The size limit can
2514/// be lowered, which will prevent large regex patterns from compiling.
2515///
2516/// ```
2517/// # if cfg!(miri) { return Ok(()); } // miri takes too long
2518/// use regex_automata::meta::Regex;
2519///
2520/// let result = Regex::builder()
2521///     .configure(Regex::config().nfa_size_limit(Some(20 * (1<<10))))
2522///     // Not even 20KB is enough to build a single large Unicode class!
2523///     .build(r"\pL");
2524/// assert!(result.is_err());
2525///
2526/// # Ok::<(), Box<dyn std::error::Error>>(())
2527/// ```
2528#[derive(Clone, Debug, Default)]
2529pub struct Config {
2530    // As with other configuration types in this crate, we put all our knobs
2531    // in options so that we can distinguish between "default" and "not set."
2532    // This makes it possible to easily combine multiple configurations
2533    // without default values overwriting explicitly specified values. See the
2534    // 'overwrite' method.
2535    //
2536    // For docs on the fields below, see the corresponding method setters.
2537    match_kind: Option<MatchKind>,
2538    utf8_empty: Option<bool>,
2539    autopre: Option<bool>,
2540    pre: Option<Option<Prefilter>>,
2541    which_captures: Option<WhichCaptures>,
2542    nfa_size_limit: Option<Option<usize>>,
2543    onepass_size_limit: Option<Option<usize>>,
2544    hybrid_cache_capacity: Option<usize>,
2545    hybrid: Option<bool>,
2546    dfa: Option<bool>,
2547    dfa_size_limit: Option<Option<usize>>,
2548    dfa_state_limit: Option<Option<usize>>,
2549    onepass: Option<bool>,
2550    backtrack: Option<bool>,
2551    byte_classes: Option<bool>,
2552    line_terminator: Option<u8>,
2553    pool_capacity: Option<usize>,
2554}
2555
2556impl Config {
2557    /// Create a new configuration object for a `Regex`.
2558    pub fn new() -> Config {
2559        Config::default()
2560    }
2561
2562    /// Set the match semantics for a `Regex`.
2563    ///
2564    /// The default value is [`MatchKind::LeftmostFirst`].
2565    ///
2566    /// # Example
2567    ///
2568    /// ```
2569    /// use regex_automata::{meta::Regex, Match, MatchKind};
2570    ///
2571    /// // By default, leftmost-first semantics are used, which
2572    /// // disambiguates matches at the same position by selecting
2573    /// // the one that corresponds earlier in the pattern.
2574    /// let re = Regex::new("sam|samwise")?;
2575    /// assert_eq!(Some(Match::must(0, 0..3)), re.find("samwise"));
2576    ///
2577    /// // But with 'all' semantics, match priority is ignored
2578    /// // and all match states are included. When coupled with
2579    /// // a leftmost search, the search will report the last
2580    /// // possible match.
2581    /// let re = Regex::builder()
2582    ///     .configure(Regex::config().match_kind(MatchKind::All))
2583    ///     .build("sam|samwise")?;
2584    /// assert_eq!(Some(Match::must(0, 0..7)), re.find("samwise"));
2585    /// // Beware that this can lead to skipping matches!
2586    /// // Usually 'all' is used for anchored reverse searches
2587    /// // only, or for overlapping searches.
2588    /// assert_eq!(Some(Match::must(0, 4..11)), re.find("sam samwise"));
2589    ///
2590    /// # Ok::<(), Box<dyn std::error::Error>>(())
2591    /// ```
2592    pub fn match_kind(self, kind: MatchKind) -> Config {
2593        Config { match_kind: Some(kind), ..self }
2594    }
2595
2596    /// Toggles whether empty matches are permitted to occur between the code
2597    /// units of a UTF-8 encoded codepoint.
2598    ///
2599    /// This should generally be enabled when search a `&str` or anything that
2600    /// you otherwise know is valid UTF-8. It should be disabled in all other
2601    /// cases. Namely, if the haystack is not valid UTF-8 and this is enabled,
2602    /// then behavior is unspecified.
2603    ///
2604    /// By default, this is enabled.
2605    ///
2606    /// # Example
2607    ///
2608    /// ```
2609    /// use regex_automata::{meta::Regex, Match};
2610    ///
2611    /// let re = Regex::new("")?;
2612    /// let got: Vec<Match> = re.find_iter("☃").collect();
2613    /// // Matches only occur at the beginning and end of the snowman.
2614    /// assert_eq!(got, vec![
2615    ///     Match::must(0, 0..0),
2616    ///     Match::must(0, 3..3),
2617    /// ]);
2618    ///
2619    /// let re = Regex::builder()
2620    ///     .configure(Regex::config().utf8_empty(false))
2621    ///     .build("")?;
2622    /// let got: Vec<Match> = re.find_iter("☃").collect();
2623    /// // Matches now occur at every position!
2624    /// assert_eq!(got, vec![
2625    ///     Match::must(0, 0..0),
2626    ///     Match::must(0, 1..1),
2627    ///     Match::must(0, 2..2),
2628    ///     Match::must(0, 3..3),
2629    /// ]);
2630    ///
2631    /// Ok::<(), Box<dyn std::error::Error>>(())
2632    /// ```
2633    pub fn utf8_empty(self, yes: bool) -> Config {
2634        Config { utf8_empty: Some(yes), ..self }
2635    }
2636
2637    /// Toggles whether automatic prefilter support is enabled.
2638    ///
2639    /// If this is disabled and [`Config::prefilter`] is not set, then the
2640    /// meta regex engine will not use any prefilters. This can sometimes
2641    /// be beneficial in cases where you know (or have measured) that the
2642    /// prefilter leads to overall worse search performance.
2643    ///
2644    /// By default, this is enabled.
2645    ///
2646    /// # Example
2647    ///
2648    /// ```
2649    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
2650    /// use regex_automata::{meta::Regex, Match};
2651    ///
2652    /// let re = Regex::builder()
2653    ///     .configure(Regex::config().auto_prefilter(false))
2654    ///     .build(r"Bruce \w+")?;
2655    /// let hay = "Hello Bruce Springsteen!";
2656    /// assert_eq!(Some(Match::must(0, 6..23)), re.find(hay));
2657    ///
2658    /// Ok::<(), Box<dyn std::error::Error>>(())
2659    /// ```
2660    pub fn auto_prefilter(self, yes: bool) -> Config {
2661        Config { autopre: Some(yes), ..self }
2662    }
2663
2664    /// Overrides and sets the prefilter to use inside a `Regex`.
2665    ///
2666    /// This permits one to forcefully set a prefilter in cases where the
2667    /// caller knows better than whatever the automatic prefilter logic is
2668    /// capable of.
2669    ///
2670    /// By default, this is set to `None` and an automatic prefilter will be
2671    /// used if one could be built. (Assuming [`Config::auto_prefilter`] is
2672    /// enabled, which it is by default.)
2673    ///
2674    /// # Example
2675    ///
2676    /// This example shows how to set your own prefilter. In the case of a
2677    /// pattern like `Bruce \w+`, the automatic prefilter is likely to be
2678    /// constructed in a way that it will look for occurrences of `Bruce `.
2679    /// In most cases, this is the best choice. But in some cases, it may be
2680    /// the case that running `memchr` on `B` is the best choice. One can
2681    /// achieve that behavior by overriding the automatic prefilter logic
2682    /// and providing a prefilter that just matches `B`.
2683    ///
2684    /// ```
2685    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
2686    /// use regex_automata::{
2687    ///     meta::Regex,
2688    ///     util::prefilter::Prefilter,
2689    ///     Match, MatchKind,
2690    /// };
2691    ///
2692    /// let pre = Prefilter::new(MatchKind::LeftmostFirst, &["B"])
2693    ///     .expect("a prefilter");
2694    /// let re = Regex::builder()
2695    ///     .configure(Regex::config().prefilter(Some(pre)))
2696    ///     .build(r"Bruce \w+")?;
2697    /// let hay = "Hello Bruce Springsteen!";
2698    /// assert_eq!(Some(Match::must(0, 6..23)), re.find(hay));
2699    ///
2700    /// # Ok::<(), Box<dyn std::error::Error>>(())
2701    /// ```
2702    ///
2703    /// # Example: incorrect prefilters can lead to incorrect results!
2704    ///
2705    /// Be warned that setting an incorrect prefilter can lead to missed
2706    /// matches. So if you use this option, ensure your prefilter can _never_
2707    /// report false negatives. (A false positive is, on the other hand, quite
2708    /// okay and generally unavoidable.)
2709    ///
2710    /// ```
2711    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
2712    /// use regex_automata::{
2713    ///     meta::Regex,
2714    ///     util::prefilter::Prefilter,
2715    ///     Match, MatchKind,
2716    /// };
2717    ///
2718    /// let pre = Prefilter::new(MatchKind::LeftmostFirst, &["Z"])
2719    ///     .expect("a prefilter");
2720    /// let re = Regex::builder()
2721    ///     .configure(Regex::config().prefilter(Some(pre)))
2722    ///     .build(r"Bruce \w+")?;
2723    /// let hay = "Hello Bruce Springsteen!";
2724    /// // Oops! No match found, but there should be one!
2725    /// assert_eq!(None, re.find(hay));
2726    ///
2727    /// # Ok::<(), Box<dyn std::error::Error>>(())
2728    /// ```
2729    pub fn prefilter(self, pre: Option<Prefilter>) -> Config {
2730        Config { pre: Some(pre), ..self }
2731    }
2732
2733    /// Configures what kinds of groups are compiled as "capturing" in the
2734    /// underlying regex engine.
2735    ///
2736    /// This is set to [`WhichCaptures::All`] by default. Callers may wish to
2737    /// use [`WhichCaptures::Implicit`] in cases where one wants avoid the
2738    /// overhead of capture states for explicit groups.
2739    ///
2740    /// Note that another approach to avoiding the overhead of capture groups
2741    /// is by using non-capturing groups in the regex pattern. That is,
2742    /// `(?:a)` instead of `(a)`. This option is useful when you can't control
2743    /// the concrete syntax but know that you don't need the underlying capture
2744    /// states. For example, using `WhichCaptures::Implicit` will behave as if
2745    /// all explicit capturing groups in the pattern were non-capturing.
2746    ///
2747    /// Setting this to `WhichCaptures::None` is usually not the right thing to
2748    /// do. When no capture states are compiled, some regex engines (such as
2749    /// the `PikeVM`) won't be able to report match offsets. This will manifest
2750    /// as no match being found. Indeed, in order to enforce consistent
2751    /// behavior, the meta regex engine will always report `None` for routines
2752    /// that return match offsets even if one of its regex engines could
2753    /// service the request. This avoids "match or not" behavior from being
2754    /// influenced by user input (since user input can influence the selection
2755    /// of the regex engine).
2756    ///
2757    /// # Example
2758    ///
2759    /// This example demonstrates how the results of capture groups can change
2760    /// based on this option. First we show the default (all capture groups in
2761    /// the pattern are capturing):
2762    ///
2763    /// ```
2764    /// use regex_automata::{meta::Regex, Match, Span};
2765    ///
2766    /// let re = Regex::new(r"foo([0-9]+)bar")?;
2767    /// let hay = "foo123bar";
2768    ///
2769    /// let mut caps = re.create_captures();
2770    /// re.captures(hay, &mut caps);
2771    /// assert_eq!(Some(Span::from(0..9)), caps.get_group(0));
2772    /// assert_eq!(Some(Span::from(3..6)), caps.get_group(1));
2773    ///
2774    /// Ok::<(), Box<dyn std::error::Error>>(())
2775    /// ```
2776    ///
2777    /// And now we show the behavior when we only include implicit capture
2778    /// groups. In this case, we can only find the overall match span, but the
2779    /// spans of any other explicit group don't exist because they are treated
2780    /// as non-capturing. (In effect, when `WhichCaptures::Implicit` is used,
2781    /// there is no real point in using [`Regex::captures`] since it will never
2782    /// be able to report more information than [`Regex::find`].)
2783    ///
2784    /// ```
2785    /// use regex_automata::{
2786    ///     meta::Regex,
2787    ///     nfa::thompson::WhichCaptures,
2788    ///     Match,
2789    ///     Span,
2790    /// };
2791    ///
2792    /// let re = Regex::builder()
2793    ///     .configure(Regex::config().which_captures(WhichCaptures::Implicit))
2794    ///     .build(r"foo([0-9]+)bar")?;
2795    /// let hay = "foo123bar";
2796    ///
2797    /// let mut caps = re.create_captures();
2798    /// re.captures(hay, &mut caps);
2799    /// assert_eq!(Some(Span::from(0..9)), caps.get_group(0));
2800    /// assert_eq!(None, caps.get_group(1));
2801    ///
2802    /// Ok::<(), Box<dyn std::error::Error>>(())
2803    /// ```
2804    ///
2805    /// # Example: strange `Regex::find` behavior
2806    ///
2807    /// As noted above, when using [`WhichCaptures::None`], this means that
2808    /// `Regex::is_match` could return `true` while `Regex::find` returns
2809    /// `None`:
2810    ///
2811    /// ```
2812    /// use regex_automata::{
2813    ///     meta::Regex,
2814    ///     nfa::thompson::WhichCaptures,
2815    ///     Input,
2816    ///     Match,
2817    ///     Span,
2818    /// };
2819    ///
2820    /// let re = Regex::builder()
2821    ///     .configure(Regex::config().which_captures(WhichCaptures::None))
2822    ///     .build(r"foo([0-9]+)bar")?;
2823    /// let hay = "foo123bar";
2824    ///
2825    /// assert!(re.is_match(hay));
2826    /// assert_eq!(re.find(hay), None);
2827    /// assert_eq!(re.search_half(&Input::new(hay)), None);
2828    ///
2829    /// Ok::<(), Box<dyn std::error::Error>>(())
2830    /// ```
2831    pub fn which_captures(mut self, which_captures: WhichCaptures) -> Config {
2832        self.which_captures = Some(which_captures);
2833        self
2834    }
2835
2836    /// Sets the size limit, in bytes, to enforce on the construction of every
2837    /// NFA build by the meta regex engine.
2838    ///
2839    /// Setting it to `None` disables the limit. This is not recommended if
2840    /// you're compiling untrusted patterns.
2841    ///
2842    /// Note that this limit is applied to _each_ NFA built, and if any of
2843    /// them exceed the limit, then construction will fail. This limit does
2844    /// _not_ correspond to the total memory used by all NFAs in the meta regex
2845    /// engine.
2846    ///
2847    /// This defaults to some reasonable number that permits most reasonable
2848    /// patterns.
2849    ///
2850    /// # Example
2851    ///
2852    /// ```
2853    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
2854    /// use regex_automata::meta::Regex;
2855    ///
2856    /// let result = Regex::builder()
2857    ///     .configure(Regex::config().nfa_size_limit(Some(20 * (1<<10))))
2858    ///     // Not even 20KB is enough to build a single large Unicode class!
2859    ///     .build(r"\pL");
2860    /// assert!(result.is_err());
2861    ///
2862    /// // But notice that building such a regex with the exact same limit
2863    /// // can succeed depending on other aspects of the configuration. For
2864    /// // example, a single *forward* NFA will (at time of writing) fit into
2865    /// // the 20KB limit, but a *reverse* NFA of the same pattern will not.
2866    /// // So if one configures a meta regex such that a reverse NFA is never
2867    /// // needed and thus never built, then the 20KB limit will be enough for
2868    /// // a pattern like \pL!
2869    /// let result = Regex::builder()
2870    ///     .configure(Regex::config()
2871    ///         .nfa_size_limit(Some(20 * (1<<10)))
2872    ///         // The DFAs are the only thing that (currently) need a reverse
2873    ///         // NFA. So if both are disabled, the meta regex engine will
2874    ///         // skip building the reverse NFA. Note that this isn't an API
2875    ///         // guarantee. A future semver compatible version may introduce
2876    ///         // new use cases for a reverse NFA.
2877    ///         .hybrid(false)
2878    ///         .dfa(false)
2879    ///     )
2880    ///     // Not even 20KB is enough to build a single large Unicode class!
2881    ///     .build(r"\pL");
2882    /// assert!(result.is_ok());
2883    ///
2884    /// # Ok::<(), Box<dyn std::error::Error>>(())
2885    /// ```
2886    pub fn nfa_size_limit(self, limit: Option<usize>) -> Config {
2887        Config { nfa_size_limit: Some(limit), ..self }
2888    }
2889
2890    /// Sets the size limit, in bytes, for the one-pass DFA.
2891    ///
2892    /// Setting it to `None` disables the limit. Disabling the limit is
2893    /// strongly discouraged when compiling untrusted patterns. Even if the
2894    /// patterns are trusted, it still may not be a good idea, since a one-pass
2895    /// DFA can use a lot of memory. With that said, as the size of a regex
2896    /// increases, the likelihood of it being one-pass likely decreases.
2897    ///
2898    /// This defaults to some reasonable number that permits most reasonable
2899    /// one-pass patterns.
2900    ///
2901    /// # Example
2902    ///
2903    /// This shows how to set the one-pass DFA size limit. Note that since
2904    /// a one-pass DFA is an optional component of the meta regex engine,
2905    /// this size limit only impacts what is built internally and will never
2906    /// determine whether a `Regex` itself fails to build.
2907    ///
2908    /// ```
2909    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
2910    /// use regex_automata::meta::Regex;
2911    ///
2912    /// let result = Regex::builder()
2913    ///     .configure(Regex::config().onepass_size_limit(Some(2 * (1<<20))))
2914    ///     .build(r"\pL{5}");
2915    /// assert!(result.is_ok());
2916    /// # Ok::<(), Box<dyn std::error::Error>>(())
2917    /// ```
2918    pub fn onepass_size_limit(self, limit: Option<usize>) -> Config {
2919        Config { onepass_size_limit: Some(limit), ..self }
2920    }
2921
2922    /// Set the cache capacity, in bytes, for the lazy DFA.
2923    ///
2924    /// The cache capacity of the lazy DFA determines approximately how much
2925    /// heap memory it is allowed to use to store its state transitions. The
2926    /// state transitions are computed at search time, and if the cache fills
2927    /// up it, it is cleared. At this point, any previously generated state
2928    /// transitions are lost and are re-generated if they're needed again.
2929    ///
2930    /// This sort of cache filling and clearing works quite well _so long as
2931    /// cache clearing happens infrequently_. If it happens too often, then the
2932    /// meta regex engine will stop using the lazy DFA and switch over to a
2933    /// different regex engine.
2934    ///
2935    /// In cases where the cache is cleared too often, it may be possible to
2936    /// give the cache more space and reduce (or eliminate) how often it is
2937    /// cleared. Similarly, sometimes a regex is so big that the lazy DFA isn't
2938    /// used at all if its cache capacity isn't big enough.
2939    ///
2940    /// The capacity set here is a _limit_ on how much memory is used. The
2941    /// actual memory used is only allocated as it's needed.
2942    ///
2943    /// Determining the right value for this is a little tricky and will likely
2944    /// required some profiling. Enabling the `logging` feature and setting the
2945    /// log level to `trace` will also tell you how often the cache is being
2946    /// cleared.
2947    ///
2948    /// # Example
2949    ///
2950    /// ```
2951    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
2952    /// use regex_automata::meta::Regex;
2953    ///
2954    /// let result = Regex::builder()
2955    ///     .configure(Regex::config().hybrid_cache_capacity(20 * (1<<20)))
2956    ///     .build(r"\pL{5}");
2957    /// assert!(result.is_ok());
2958    /// # Ok::<(), Box<dyn std::error::Error>>(())
2959    /// ```
2960    pub fn hybrid_cache_capacity(self, limit: usize) -> Config {
2961        Config { hybrid_cache_capacity: Some(limit), ..self }
2962    }
2963
2964    /// Sets the size limit, in bytes, for heap memory used for a fully
2965    /// compiled DFA.
2966    ///
2967    /// **NOTE:** If you increase this, you'll likely also need to increase
2968    /// [`Config::dfa_state_limit`].
2969    ///
2970    /// In contrast to the lazy DFA, building a full DFA requires computing
2971    /// all of its state transitions up front. This can be a very expensive
2972    /// process, and runs in worst case `2^n` time and space (where `n` is
2973    /// proportional to the size of the regex). However, a full DFA unlocks
2974    /// some additional optimization opportunities.
2975    ///
2976    /// Because full DFAs can be so expensive, the default limits for them are
2977    /// incredibly small. Generally speaking, if your regex is moderately big
2978    /// or if you're using Unicode features (`\w` is Unicode-aware by default
2979    /// for example), then you can expect that the meta regex engine won't even
2980    /// attempt to build a DFA for it.
2981    ///
2982    /// If this and [`Config::dfa_state_limit`] are set to `None`, then the
2983    /// meta regex will not use any sort of limits when deciding whether to
2984    /// build a DFA. This in turn makes construction of a `Regex` take
2985    /// worst case exponential time and space. Even short patterns can result
2986    /// in huge space blow ups. So it is strongly recommended to keep some kind
2987    /// of limit set!
2988    ///
2989    /// The default is set to a small number that permits some simple regexes
2990    /// to get compiled into DFAs in reasonable time.
2991    ///
2992    /// # Example
2993    ///
2994    /// ```
2995    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
2996    /// use regex_automata::meta::Regex;
2997    ///
2998    /// let result = Regex::builder()
2999    ///     // 100MB is much bigger than the default.
3000    ///     .configure(Regex::config()
3001    ///         .dfa_size_limit(Some(100 * (1<<20)))
3002    ///         // We don't care about size too much here, so just
3003    ///         // remove the NFA state limit altogether.
3004    ///         .dfa_state_limit(None))
3005    ///     .build(r"\pL{5}");
3006    /// assert!(result.is_ok());
3007    /// # Ok::<(), Box<dyn std::error::Error>>(())
3008    /// ```
3009    pub fn dfa_size_limit(self, limit: Option<usize>) -> Config {
3010        Config { dfa_size_limit: Some(limit), ..self }
3011    }
3012
3013    /// Sets a limit on the total number of NFA states, beyond which, a full
3014    /// DFA is not attempted to be compiled.
3015    ///
3016    /// This limit works in concert with [`Config::dfa_size_limit`]. Namely,
3017    /// where as `Config::dfa_size_limit` is applied by attempting to construct
3018    /// a DFA, this limit is used to avoid the attempt in the first place. This
3019    /// is useful to avoid hefty initialization costs associated with building
3020    /// a DFA for cases where it is obvious the DFA will ultimately be too big.
3021    ///
3022    /// By default, this is set to a very small number.
3023    ///
3024    /// # Example
3025    ///
3026    /// ```
3027    /// # if cfg!(miri) { return Ok(()); } // miri takes too long
3028    /// use regex_automata::meta::Regex;
3029    ///
3030    /// let result = Regex::builder()
3031    ///     .configure(Regex::config()
3032    ///         // Sometimes the default state limit rejects DFAs even
3033    ///         // if they would fit in the size limit. Here, we disable
3034    ///         // the check on the number of NFA states and just rely on
3035    ///         // the size limit.
3036    ///         .dfa_state_limit(None))
3037    ///     .build(r"(?-u)\w{30}");
3038    /// assert!(result.is_ok());
3039    /// # Ok::<(), Box<dyn std::error::Error>>(())
3040    /// ```
3041    pub fn dfa_state_limit(self, limit: Option<usize>) -> Config {
3042        Config { dfa_state_limit: Some(limit), ..self }
3043    }
3044
3045    /// Whether to attempt to shrink the size of the alphabet for the regex
3046    /// pattern or not. When enabled, the alphabet is shrunk into a set of
3047    /// equivalence classes, where every byte in the same equivalence class
3048    /// cannot discriminate between a match or non-match.
3049    ///
3050    /// **WARNING:** This is only useful for debugging DFAs. Disabling this
3051    /// does not yield any speed advantages. Indeed, disabling it can result
3052    /// in much higher memory usage. Disabling byte classes is useful for
3053    /// debugging the actual generated transitions because it lets one see the
3054    /// transitions defined on actual bytes instead of the equivalence classes.
3055    ///
3056    /// This option is enabled by default and should never be disabled unless
3057    /// one is debugging the meta regex engine's internals.
3058    ///
3059    /// # Example
3060    ///
3061    /// ```
3062    /// use regex_automata::{meta::Regex, Match};
3063    ///
3064    /// let re = Regex::builder()
3065    ///     .configure(Regex::config().byte_classes(false))
3066    ///     .build(r"[a-z]+")?;
3067    /// let hay = "!!quux!!";
3068    /// assert_eq!(Some(Match::must(0, 2..6)), re.find(hay));
3069    ///
3070    /// # Ok::<(), Box<dyn std::error::Error>>(())
3071    /// ```
3072    pub fn byte_classes(self, yes: bool) -> Config {
3073        Config { byte_classes: Some(yes), ..self }
3074    }
3075
3076    /// Set the line terminator to be used by the `^` and `$` anchors in
3077    /// multi-line mode.
3078    ///
3079    /// This option has no effect when CRLF mode is enabled. That is,
3080    /// regardless of this setting, `(?Rm:^)` and `(?Rm:$)` will always treat
3081    /// `\r` and `\n` as line terminators (and will never match between a `\r`
3082    /// and a `\n`).
3083    ///
3084    /// By default, `\n` is the line terminator.
3085    ///
3086    /// **Warning**: This does not change the behavior of `.`. To do that,
3087    /// you'll need to configure the syntax option
3088    /// [`syntax::Config::line_terminator`](crate::util::syntax::Config::line_terminator)
3089    /// in addition to this. Otherwise, `.` will continue to match any
3090    /// character other than `\n`.
3091    ///
3092    /// # Example
3093    ///
3094    /// ```
3095    /// use regex_automata::{meta::Regex, util::syntax, Match};
3096    ///
3097    /// let re = Regex::builder()
3098    ///     .syntax(syntax::Config::new().multi_line(true))
3099    ///     .configure(Regex::config().line_terminator(b'\x00'))
3100    ///     .build(r"^foo$")?;
3101    /// let hay = "\x00foo\x00";
3102    /// assert_eq!(Some(Match::must(0, 1..4)), re.find(hay));
3103    ///
3104    /// # Ok::<(), Box<dyn std::error::Error>>(())
3105    /// ```
3106    pub fn line_terminator(self, byte: u8) -> Config {
3107        Config { line_terminator: Some(byte), ..self }
3108    }
3109
3110    /// Sets the capacity used to manage a pool of [`Cache`] values in the
3111    /// higher level convenience APIs.
3112    ///
3113    /// When not configured explicitly, a reasonable default is selected. It
3114    /// is rarely expected that a number large than the number of logical CPUs
3115    /// makes sense as a value. A smaller number could result in slowdowns if
3116    /// many regex queries are run under contention.
3117    pub fn pool_capacity(self, capacity: usize) -> Config {
3118        Config { pool_capacity: Some(capacity), ..self }
3119    }
3120
3121    /// Toggle whether the hybrid NFA/DFA (also known as the "lazy DFA") should
3122    /// be available for use by the meta regex engine.
3123    ///
3124    /// Enabling this does not necessarily mean that the lazy DFA will
3125    /// definitely be used. It just means that it will be _available_ for use
3126    /// if the meta regex engine thinks it will be useful.
3127    ///
3128    /// When the `hybrid` crate feature is enabled, then this is enabled by
3129    /// default. Otherwise, if the crate feature is disabled, then this is
3130    /// always disabled, regardless of its setting by the caller.
3131    pub fn hybrid(self, yes: bool) -> Config {
3132        Config { hybrid: Some(yes), ..self }
3133    }
3134
3135    /// Toggle whether a fully compiled DFA should be available for use by the
3136    /// meta regex engine.
3137    ///
3138    /// Enabling this does not necessarily mean that a DFA will definitely be
3139    /// used. It just means that it will be _available_ for use if the meta
3140    /// regex engine thinks it will be useful.
3141    ///
3142    /// When the `dfa-build` crate feature is enabled, then this is enabled by
3143    /// default. Otherwise, if the crate feature is disabled, then this is
3144    /// always disabled, regardless of its setting by the caller.
3145    pub fn dfa(self, yes: bool) -> Config {
3146        Config { dfa: Some(yes), ..self }
3147    }
3148
3149    /// Toggle whether a one-pass DFA should be available for use by the meta
3150    /// regex engine.
3151    ///
3152    /// Enabling this does not necessarily mean that a one-pass DFA will
3153    /// definitely be used. It just means that it will be _available_ for
3154    /// use if the meta regex engine thinks it will be useful. (Indeed, a
3155    /// one-pass DFA can only be used when the regex is one-pass. See the
3156    /// [`dfa::onepass`](crate::dfa::onepass) module for more details.)
3157    ///
3158    /// When the `dfa-onepass` crate feature is enabled, then this is enabled
3159    /// by default. Otherwise, if the crate feature is disabled, then this is
3160    /// always disabled, regardless of its setting by the caller.
3161    pub fn onepass(self, yes: bool) -> Config {
3162        Config { onepass: Some(yes), ..self }
3163    }
3164
3165    /// Toggle whether a bounded backtracking regex engine should be available
3166    /// for use by the meta regex engine.
3167    ///
3168    /// Enabling this does not necessarily mean that a bounded backtracker will
3169    /// definitely be used. It just means that it will be _available_ for use
3170    /// if the meta regex engine thinks it will be useful.
3171    ///
3172    /// When the `nfa-backtrack` crate feature is enabled, then this is enabled
3173    /// by default. Otherwise, if the crate feature is disabled, then this is
3174    /// always disabled, regardless of its setting by the caller.
3175    pub fn backtrack(self, yes: bool) -> Config {
3176        Config { backtrack: Some(yes), ..self }
3177    }
3178
3179    /// Returns the match kind on this configuration, as set by
3180    /// [`Config::match_kind`].
3181    ///
3182    /// If it was not explicitly set, then a default value is returned.
3183    pub fn get_match_kind(&self) -> MatchKind {
3184        self.match_kind.unwrap_or(MatchKind::LeftmostFirst)
3185    }
3186
3187    /// Returns whether empty matches must fall on valid UTF-8 boundaries, as
3188    /// set by [`Config::utf8_empty`].
3189    ///
3190    /// If it was not explicitly set, then a default value is returned.
3191    pub fn get_utf8_empty(&self) -> bool {
3192        self.utf8_empty.unwrap_or(true)
3193    }
3194
3195    /// Returns whether automatic prefilters are enabled, as set by
3196    /// [`Config::auto_prefilter`].
3197    ///
3198    /// If it was not explicitly set, then a default value is returned.
3199    pub fn get_auto_prefilter(&self) -> bool {
3200        self.autopre.unwrap_or(true)
3201    }
3202
3203    /// Returns a manually set prefilter, if one was set by
3204    /// [`Config::prefilter`].
3205    ///
3206    /// If it was not explicitly set, then a default value is returned.
3207    pub fn get_prefilter(&self) -> Option<&Prefilter> {
3208        self.pre.as_ref().unwrap_or(&None).as_ref()
3209    }
3210
3211    /// Returns the capture configuration, as set by
3212    /// [`Config::which_captures`].
3213    ///
3214    /// If it was not explicitly set, then a default value is returned.
3215    pub fn get_which_captures(&self) -> WhichCaptures {
3216        self.which_captures.unwrap_or(WhichCaptures::All)
3217    }
3218
3219    /// Returns NFA size limit, as set by [`Config::nfa_size_limit`].
3220    ///
3221    /// If it was not explicitly set, then a default value is returned.
3222    pub fn get_nfa_size_limit(&self) -> Option<usize> {
3223        self.nfa_size_limit.unwrap_or(Some(10 * (1 << 20)))
3224    }
3225
3226    /// Returns one-pass DFA size limit, as set by
3227    /// [`Config::onepass_size_limit`].
3228    ///
3229    /// If it was not explicitly set, then a default value is returned.
3230    pub fn get_onepass_size_limit(&self) -> Option<usize> {
3231        self.onepass_size_limit.unwrap_or(Some(1 * (1 << 20)))
3232    }
3233
3234    /// Returns hybrid NFA/DFA cache capacity, as set by
3235    /// [`Config::hybrid_cache_capacity`].
3236    ///
3237    /// If it was not explicitly set, then a default value is returned.
3238    pub fn get_hybrid_cache_capacity(&self) -> usize {
3239        self.hybrid_cache_capacity.unwrap_or(2 * (1 << 20))
3240    }
3241
3242    /// Returns DFA size limit, as set by [`Config::dfa_size_limit`].
3243    ///
3244    /// If it was not explicitly set, then a default value is returned.
3245    pub fn get_dfa_size_limit(&self) -> Option<usize> {
3246        // The default for this is VERY small because building a full DFA is
3247        // ridiculously costly. But for regexes that are very small, it can be
3248        // beneficial to use a full DFA. In particular, a full DFA can enable
3249        // additional optimizations via something called "accelerated" states.
3250        // Namely, when there's a state with only a few outgoing transitions,
3251        // we can temporary suspend walking the transition table and use memchr
3252        // for just those outgoing transitions to skip ahead very quickly.
3253        //
3254        // Generally speaking, if Unicode is enabled in your regex and you're
3255        // using some kind of Unicode feature, then it's going to blow this
3256        // size limit. Moreover, Unicode tends to defeat the "accelerated"
3257        // state optimization too, so it's a double whammy.
3258        //
3259        // We also use a limit on the number of NFA states to avoid even
3260        // starting the DFA construction process. Namely, DFA construction
3261        // itself could make lots of initial allocs proportional to the size
3262        // of the NFA, and if the NFA is large, it doesn't make sense to pay
3263        // that cost if we know it's likely to be blown by a large margin.
3264        self.dfa_size_limit.unwrap_or(Some(40 * (1 << 10)))
3265    }
3266
3267    /// Returns DFA size limit in terms of the number of states in the NFA, as
3268    /// set by [`Config::dfa_state_limit`].
3269    ///
3270    /// If it was not explicitly set, then a default value is returned.
3271    pub fn get_dfa_state_limit(&self) -> Option<usize> {
3272        // Again, as with the size limit, we keep this very small.
3273        self.dfa_state_limit.unwrap_or(Some(30))
3274    }
3275
3276    /// Returns whether byte classes are enabled, as set by
3277    /// [`Config::byte_classes`].
3278    ///
3279    /// If it was not explicitly set, then a default value is returned.
3280    pub fn get_byte_classes(&self) -> bool {
3281        self.byte_classes.unwrap_or(true)
3282    }
3283
3284    /// Returns the line terminator for this configuration, as set by
3285    /// [`Config::line_terminator`].
3286    ///
3287    /// If it was not explicitly set, then a default value is returned.
3288    pub fn get_line_terminator(&self) -> u8 {
3289        self.line_terminator.unwrap_or(b'\n')
3290    }
3291
3292    /// Returns the configured pool capacity, as set by
3293    /// [`Config::pool_capacity`].
3294    ///
3295    /// If it was not explicitly set, then a default value is returned.
3296    pub fn get_pool_capacity(&self) -> usize {
3297        // The default is an empirically chosen value that balances memory
3298        // usage with runtime performance. In practice, with `std` enabled,
3299        // we choose a value that matches the total number of CPUs.
3300        const DEFAULT_POOL_CAPACITY: usize = 8;
3301        self.pool_capacity.unwrap_or(DEFAULT_POOL_CAPACITY)
3302    }
3303
3304    /// Returns whether the hybrid NFA/DFA regex engine may be used, as set by
3305    /// [`Config::hybrid`].
3306    ///
3307    /// If it was not explicitly set, then a default value is returned.
3308    pub fn get_hybrid(&self) -> bool {
3309        #[cfg(feature = "hybrid")]
3310        {
3311            self.hybrid.unwrap_or(true)
3312        }
3313        #[cfg(not(feature = "hybrid"))]
3314        {
3315            false
3316        }
3317    }
3318
3319    /// Returns whether the DFA regex engine may be used, as set by
3320    /// [`Config::dfa`].
3321    ///
3322    /// If it was not explicitly set, then a default value is returned.
3323    pub fn get_dfa(&self) -> bool {
3324        #[cfg(feature = "dfa-build")]
3325        {
3326            self.dfa.unwrap_or(true)
3327        }
3328        #[cfg(not(feature = "dfa-build"))]
3329        {
3330            false
3331        }
3332    }
3333
3334    /// Returns whether the one-pass DFA regex engine may be used, as set by
3335    /// [`Config::onepass`].
3336    ///
3337    /// If it was not explicitly set, then a default value is returned.
3338    pub fn get_onepass(&self) -> bool {
3339        #[cfg(feature = "dfa-onepass")]
3340        {
3341            self.onepass.unwrap_or(true)
3342        }
3343        #[cfg(not(feature = "dfa-onepass"))]
3344        {
3345            false
3346        }
3347    }
3348
3349    /// Returns whether the bounded backtracking regex engine may be used, as
3350    /// set by [`Config::backtrack`].
3351    ///
3352    /// If it was not explicitly set, then a default value is returned.
3353    pub fn get_backtrack(&self) -> bool {
3354        #[cfg(feature = "nfa-backtrack")]
3355        {
3356            self.backtrack.unwrap_or(true)
3357        }
3358        #[cfg(not(feature = "nfa-backtrack"))]
3359        {
3360            false
3361        }
3362    }
3363
3364    /// Returns a "baseline" Thompson configuration for constructing NFAs based
3365    /// on this configuration.
3366    ///
3367    /// This is just a convenience routine to avoid repeating configuration
3368    /// construction.
3369    ///
3370    /// Callers may still need to set other things, like whether the NFA should
3371    /// be compiled in reverse. Callers may also override settings, like
3372    /// forcing no capture states to be included.
3373    pub(crate) fn to_thompson_config(&self) -> thompson::Config {
3374        let mut lookm = LookMatcher::new();
3375        lookm.set_line_terminator(self.get_line_terminator());
3376        thompson::Config::new()
3377            .utf8(self.get_utf8_empty())
3378            .reverse(false)
3379            .nfa_size_limit(self.get_nfa_size_limit())
3380            .shrink(false)
3381            .which_captures(self.get_which_captures())
3382            .look_matcher(lookm)
3383    }
3384
3385    /// Overwrite the default configuration such that the options in `o` are
3386    /// always used. If an option in `o` is not set, then the corresponding
3387    /// option in `self` is used. If it's not set in `self` either, then it
3388    /// remains not set.
3389    pub(crate) fn overwrite(&self, o: Config) -> Config {
3390        Config {
3391            match_kind: o.match_kind.or(self.match_kind),
3392            utf8_empty: o.utf8_empty.or(self.utf8_empty),
3393            autopre: o.autopre.or(self.autopre),
3394            pre: o.pre.or_else(|| self.pre.clone()),
3395            which_captures: o.which_captures.or(self.which_captures),
3396            nfa_size_limit: o.nfa_size_limit.or(self.nfa_size_limit),
3397            onepass_size_limit: o
3398                .onepass_size_limit
3399                .or(self.onepass_size_limit),
3400            hybrid_cache_capacity: o
3401                .hybrid_cache_capacity
3402                .or(self.hybrid_cache_capacity),
3403            hybrid: o.hybrid.or(self.hybrid),
3404            dfa: o.dfa.or(self.dfa),
3405            dfa_size_limit: o.dfa_size_limit.or(self.dfa_size_limit),
3406            dfa_state_limit: o.dfa_state_limit.or(self.dfa_state_limit),
3407            onepass: o.onepass.or(self.onepass),
3408            backtrack: o.backtrack.or(self.backtrack),
3409            byte_classes: o.byte_classes.or(self.byte_classes),
3410            line_terminator: o.line_terminator.or(self.line_terminator),
3411            pool_capacity: o.pool_capacity.or(self.pool_capacity),
3412        }
3413    }
3414}
3415
3416/// A builder for configuring and constructing a `Regex`.
3417///
3418/// The builder permits configuring two different aspects of a `Regex`:
3419///
3420/// * [`Builder::configure`] will set high-level configuration options as
3421/// described by a [`Config`].
3422/// * [`Builder::syntax`] will set the syntax level configuration options
3423/// as described by a [`util::syntax::Config`](crate::util::syntax::Config).
3424/// This only applies when building a `Regex` from pattern strings.
3425///
3426/// Once configured, the builder can then be used to construct a `Regex` from
3427/// one of 4 different inputs:
3428///
3429/// * [`Builder::build`] creates a regex from a single pattern string.
3430/// * [`Builder::build_many`] creates a regex from many pattern strings.
3431/// * [`Builder::build_from_hir`] creates a regex from a
3432/// [`regex-syntax::Hir`](Hir) expression.
3433/// * [`Builder::build_many_from_hir`] creates a regex from many
3434/// [`regex-syntax::Hir`](Hir) expressions.
3435///
3436/// The latter two methods in particular provide a way to construct a fully
3437/// feature regular expression matcher directly from an `Hir` expression
3438/// without having to first convert it to a string. (This is in contrast to the
3439/// top-level `regex` crate which intentionally provides no such API in order
3440/// to avoid making `regex-syntax` a public dependency.)
3441///
3442/// As a convenience, this builder may be created via [`Regex::builder`], which
3443/// may help avoid an extra import.
3444///
3445/// # Example: change the line terminator
3446///
3447/// This example shows how to enable multi-line mode by default and change the
3448/// line terminator to the NUL byte:
3449///
3450/// ```
3451/// use regex_automata::{meta::Regex, util::syntax, Match};
3452///
3453/// let re = Regex::builder()
3454///     .syntax(syntax::Config::new().multi_line(true))
3455///     .configure(Regex::config().line_terminator(b'\x00'))
3456///     .build(r"^foo$")?;
3457/// let hay = "\x00foo\x00";
3458/// assert_eq!(Some(Match::must(0, 1..4)), re.find(hay));
3459///
3460/// # Ok::<(), Box<dyn std::error::Error>>(())
3461/// ```
3462///
3463/// # Example: disable UTF-8 requirement
3464///
3465/// By default, regex patterns are required to match UTF-8. This includes
3466/// regex patterns that can produce matches of length zero. In the case of an
3467/// empty match, by default, matches will not appear between the code units of
3468/// a UTF-8 encoded codepoint.
3469///
3470/// However, it can be useful to disable this requirement, particularly if
3471/// you're searching things like `&[u8]` that are not known to be valid UTF-8.
3472///
3473/// ```
3474/// use regex_automata::{meta::Regex, util::syntax, Match};
3475///
3476/// let mut builder = Regex::builder();
3477/// // Disables the requirement that non-empty matches match UTF-8.
3478/// builder.syntax(syntax::Config::new().utf8(false));
3479/// // Disables the requirement that empty matches match UTF-8 boundaries.
3480/// builder.configure(Regex::config().utf8_empty(false));
3481///
3482/// // We can match raw bytes via \xZZ syntax, but we need to disable
3483/// // Unicode mode to do that. We could disable it everywhere, or just
3484/// // selectively, as shown here.
3485/// let re = builder.build(r"(?-u:\xFF)foo(?-u:\xFF)")?;
3486/// let hay = b"\xFFfoo\xFF";
3487/// assert_eq!(Some(Match::must(0, 0..5)), re.find(hay));
3488///
3489/// // We can also match between code units.
3490/// let re = builder.build(r"")?;
3491/// let hay = "☃";
3492/// assert_eq!(re.find_iter(hay).collect::<Vec<Match>>(), vec![
3493///     Match::must(0, 0..0),
3494///     Match::must(0, 1..1),
3495///     Match::must(0, 2..2),
3496///     Match::must(0, 3..3),
3497/// ]);
3498///
3499/// # Ok::<(), Box<dyn std::error::Error>>(())
3500/// ```
3501#[derive(Clone, Debug)]
3502pub struct Builder {
3503    config: Config,
3504    ast: ast::parse::ParserBuilder,
3505    hir: hir::translate::TranslatorBuilder,
3506}
3507
3508impl Builder {
3509    /// Creates a new builder for configuring and constructing a [`Regex`].
3510    pub fn new() -> Builder {
3511        Builder {
3512            config: Config::default(),
3513            ast: ast::parse::ParserBuilder::new(),
3514            hir: hir::translate::TranslatorBuilder::new(),
3515        }
3516    }
3517
3518    /// Builds a `Regex` from a single pattern string.
3519    ///
3520    /// If there was a problem parsing the pattern or a problem turning it into
3521    /// a regex matcher, then an error is returned.
3522    ///
3523    /// # Example
3524    ///
3525    /// This example shows how to configure syntax options.
3526    ///
3527    /// ```
3528    /// use regex_automata::{meta::Regex, util::syntax, Match};
3529    ///
3530    /// let re = Regex::builder()
3531    ///     .syntax(syntax::Config::new().crlf(true).multi_line(true))
3532    ///     .build(r"^foo$")?;
3533    /// let hay = "\r\nfoo\r\n";
3534    /// assert_eq!(Some(Match::must(0, 2..5)), re.find(hay));
3535    ///
3536    /// # Ok::<(), Box<dyn std::error::Error>>(())
3537    /// ```
3538    pub fn build(&self, pattern: &str) -> Result<Regex, BuildError> {
3539        self.build_many(&[pattern])
3540    }
3541
3542    /// Builds a `Regex` from many pattern strings.
3543    ///
3544    /// If there was a problem parsing any of the patterns or a problem turning
3545    /// them into a regex matcher, then an error is returned.
3546    ///
3547    /// # Example: finding the pattern that caused an error
3548    ///
3549    /// When a syntax error occurs, it is possible to ask which pattern
3550    /// caused the syntax error.
3551    ///
3552    /// ```
3553    /// use regex_automata::{meta::Regex, PatternID};
3554    ///
3555    /// let err = Regex::builder()
3556    ///     .build_many(&["a", "b", r"\p{Foo}", "c"])
3557    ///     .unwrap_err();
3558    /// assert_eq!(Some(PatternID::must(2)), err.pattern());
3559    /// ```
3560    ///
3561    /// # Example: zero patterns is valid
3562    ///
3563    /// Building a regex with zero patterns results in a regex that never
3564    /// matches anything. Because this routine is generic, passing an empty
3565    /// slice usually requires a turbo-fish (or something else to help type
3566    /// inference).
3567    ///
3568    /// ```
3569    /// use regex_automata::{meta::Regex, util::syntax, Match};
3570    ///
3571    /// let re = Regex::builder()
3572    ///     .build_many::<&str>(&[])?;
3573    /// assert_eq!(None, re.find(""));
3574    ///
3575    /// # Ok::<(), Box<dyn std::error::Error>>(())
3576    /// ```
3577    pub fn build_many<P: AsRef<str>>(
3578        &self,
3579        patterns: &[P],
3580    ) -> Result<Regex, BuildError> {
3581        use crate::util::primitives::IteratorIndexExt;
3582        log! {
3583            debug!("building meta regex with {} patterns:", patterns.len());
3584            for (pid, p) in patterns.iter().with_pattern_ids() {
3585                let p = p.as_ref();
3586                // We might split a grapheme with this truncation logic, but
3587                // that's fine. We at least avoid splitting a codepoint.
3588                let maxoff = p
3589                    .char_indices()
3590                    .map(|(i, ch)| i + ch.len_utf8())
3591                    .take(1000)
3592                    .last()
3593                    .unwrap_or(0);
3594                if maxoff < p.len() {
3595                    debug!("{pid:?}: {}[... snip ...]", &p[..maxoff]);
3596                } else {
3597                    debug!("{pid:?}: {p}");
3598                }
3599            }
3600        }
3601        let (mut asts, mut hirs) = (vec![], vec![]);
3602        for (pid, p) in patterns.iter().with_pattern_ids() {
3603            let ast = self
3604                .ast
3605                .build()
3606                .parse(p.as_ref())
3607                .map_err(|err| BuildError::ast(pid, err))?;
3608            asts.push(ast);
3609        }
3610        for ((pid, p), ast) in
3611            patterns.iter().with_pattern_ids().zip(asts.iter())
3612        {
3613            let hir = self
3614                .hir
3615                .build()
3616                .translate(p.as_ref(), ast)
3617                .map_err(|err| BuildError::hir(pid, err))?;
3618            hirs.push(hir);
3619        }
3620        self.build_many_from_hir(&hirs)
3621    }
3622
3623    /// Builds a `Regex` directly from an `Hir` expression.
3624    ///
3625    /// This is useful if you needed to parse a pattern string into an `Hir`
3626    /// for other reasons (such as analysis or transformations). This routine
3627    /// permits building a `Regex` directly from the `Hir` expression instead
3628    /// of first converting the `Hir` back to a pattern string.
3629    ///
3630    /// When using this method, any options set via [`Builder::syntax`] are
3631    /// ignored. Namely, the syntax options only apply when parsing a pattern
3632    /// string, which isn't relevant here.
3633    ///
3634    /// If there was a problem building the underlying regex matcher for the
3635    /// given `Hir`, then an error is returned.
3636    ///
3637    /// # Example
3638    ///
3639    /// This example shows how one can hand-construct an `Hir` expression and
3640    /// build a regex from it without doing any parsing at all.
3641    ///
3642    /// ```
3643    /// use {
3644    ///     regex_automata::{meta::Regex, Match},
3645    ///     regex_syntax::hir::{Hir, Look},
3646    /// };
3647    ///
3648    /// // (?Rm)^foo$
3649    /// let hir = Hir::concat(vec![
3650    ///     Hir::look(Look::StartCRLF),
3651    ///     Hir::literal("foo".as_bytes()),
3652    ///     Hir::look(Look::EndCRLF),
3653    /// ]);
3654    /// let re = Regex::builder()
3655    ///     .build_from_hir(&hir)?;
3656    /// let hay = "\r\nfoo\r\n";
3657    /// assert_eq!(Some(Match::must(0, 2..5)), re.find(hay));
3658    ///
3659    /// Ok::<(), Box<dyn std::error::Error>>(())
3660    /// ```
3661    pub fn build_from_hir(&self, hir: &Hir) -> Result<Regex, BuildError> {
3662        self.build_many_from_hir(&[hir])
3663    }
3664
3665    /// Builds a `Regex` directly from many `Hir` expressions.
3666    ///
3667    /// This is useful if you needed to parse pattern strings into `Hir`
3668    /// expressions for other reasons (such as analysis or transformations).
3669    /// This routine permits building a `Regex` directly from the `Hir`
3670    /// expressions instead of first converting the `Hir` expressions back to
3671    /// pattern strings.
3672    ///
3673    /// When using this method, any options set via [`Builder::syntax`] are
3674    /// ignored. Namely, the syntax options only apply when parsing a pattern
3675    /// string, which isn't relevant here.
3676    ///
3677    /// If there was a problem building the underlying regex matcher for the
3678    /// given `Hir` expressions, then an error is returned.
3679    ///
3680    /// Note that unlike [`Builder::build_many`], this can only fail as a
3681    /// result of building the underlying matcher. In that case, there is
3682    /// no single `Hir` expression that can be isolated as a reason for the
3683    /// failure. So if this routine fails, it's not possible to determine which
3684    /// `Hir` expression caused the failure.
3685    ///
3686    /// # Example
3687    ///
3688    /// This example shows how one can hand-construct multiple `Hir`
3689    /// expressions and build a single regex from them without doing any
3690    /// parsing at all.
3691    ///
3692    /// ```
3693    /// use {
3694    ///     regex_automata::{meta::Regex, Match},
3695    ///     regex_syntax::hir::{Hir, Look},
3696    /// };
3697    ///
3698    /// // (?Rm)^foo$
3699    /// let hir1 = Hir::concat(vec![
3700    ///     Hir::look(Look::StartCRLF),
3701    ///     Hir::literal("foo".as_bytes()),
3702    ///     Hir::look(Look::EndCRLF),
3703    /// ]);
3704    /// // (?Rm)^bar$
3705    /// let hir2 = Hir::concat(vec![
3706    ///     Hir::look(Look::StartCRLF),
3707    ///     Hir::literal("bar".as_bytes()),
3708    ///     Hir::look(Look::EndCRLF),
3709    /// ]);
3710    /// let re = Regex::builder()
3711    ///     .build_many_from_hir(&[&hir1, &hir2])?;
3712    /// let hay = "\r\nfoo\r\nbar";
3713    /// let got: Vec<Match> = re.find_iter(hay).collect();
3714    /// let expected = vec![
3715    ///     Match::must(0, 2..5),
3716    ///     Match::must(1, 7..10),
3717    /// ];
3718    /// assert_eq!(expected, got);
3719    ///
3720    /// Ok::<(), Box<dyn std::error::Error>>(())
3721    /// ```
3722    pub fn build_many_from_hir<H: Borrow<Hir>>(
3723        &self,
3724        hirs: &[H],
3725    ) -> Result<Regex, BuildError> {
3726        let config = self.config.clone();
3727        // We collect the HIRs into a vec so we can write internal routines
3728        // with '&[&Hir]'. i.e., Don't use generics everywhere to keep code
3729        // bloat down..
3730        let hirs: Vec<&Hir> = hirs.iter().map(|hir| hir.borrow()).collect();
3731        let info = RegexInfo::new(config, &hirs);
3732        let strat = strategy::new(&info, &hirs)?;
3733        let pool = {
3734            let strat = Arc::clone(&strat);
3735            let create: CachePoolFn = Box::new(move || strat.create_cache());
3736            Pool::with_capacity(self.config.get_pool_capacity(), create)
3737        };
3738        Ok(Regex { imp: Arc::new(RegexI { strat, info }), pool })
3739    }
3740
3741    /// Configure the behavior of a `Regex`.
3742    ///
3743    /// This configuration controls non-syntax options related to the behavior
3744    /// of a `Regex`. This includes things like whether empty matches can split
3745    /// a codepoint, prefilters, line terminators and a long list of options
3746    /// for configuring which regex engines the meta regex engine will be able
3747    /// to use internally.
3748    ///
3749    /// # Example
3750    ///
3751    /// This example shows how to disable UTF-8 empty mode. This will permit
3752    /// empty matches to occur between the UTF-8 encoding of a codepoint.
3753    ///
3754    /// ```
3755    /// use regex_automata::{meta::Regex, Match};
3756    ///
3757    /// let re = Regex::new("")?;
3758    /// let got: Vec<Match> = re.find_iter("☃").collect();
3759    /// // Matches only occur at the beginning and end of the snowman.
3760    /// assert_eq!(got, vec![
3761    ///     Match::must(0, 0..0),
3762    ///     Match::must(0, 3..3),
3763    /// ]);
3764    ///
3765    /// let re = Regex::builder()
3766    ///     .configure(Regex::config().utf8_empty(false))
3767    ///     .build("")?;
3768    /// let got: Vec<Match> = re.find_iter("☃").collect();
3769    /// // Matches now occur at every position!
3770    /// assert_eq!(got, vec![
3771    ///     Match::must(0, 0..0),
3772    ///     Match::must(0, 1..1),
3773    ///     Match::must(0, 2..2),
3774    ///     Match::must(0, 3..3),
3775    /// ]);
3776    ///
3777    /// Ok::<(), Box<dyn std::error::Error>>(())
3778    /// ```
3779    pub fn configure(&mut self, config: Config) -> &mut Builder {
3780        self.config = self.config.overwrite(config);
3781        self
3782    }
3783
3784    /// Configure the syntax options when parsing a pattern string while
3785    /// building a `Regex`.
3786    ///
3787    /// These options _only_ apply when [`Builder::build`] or [`Builder::build_many`]
3788    /// are used. The other build methods accept `Hir` values, which have
3789    /// already been parsed.
3790    ///
3791    /// # Example
3792    ///
3793    /// This example shows how to enable case insensitive mode.
3794    ///
3795    /// ```
3796    /// use regex_automata::{meta::Regex, util::syntax, Match};
3797    ///
3798    /// let re = Regex::builder()
3799    ///     .syntax(syntax::Config::new().case_insensitive(true))
3800    ///     .build(r"δ")?;
3801    /// assert_eq!(Some(Match::must(0, 0..2)), re.find(r"Δ"));
3802    ///
3803    /// Ok::<(), Box<dyn std::error::Error>>(())
3804    /// ```
3805    pub fn syntax(
3806        &mut self,
3807        config: crate::util::syntax::Config,
3808    ) -> &mut Builder {
3809        config.apply_ast(&mut self.ast);
3810        config.apply_hir(&mut self.hir);
3811        self
3812    }
3813}
3814
3815#[cfg(test)]
3816mod tests {
3817    use super::*;
3818
3819    // I found this in the course of building out the benchmark suite for
3820    // rebar.
3821    #[test]
3822    fn regression_suffix_literal_count() {
3823        let _ = env_logger::try_init();
3824
3825        let re = Regex::new(r"[a-zA-Z]+ing").unwrap();
3826        assert_eq!(1, re.find_iter("tingling").count());
3827    }
3828}