Struct PikeVM
struct PikeVM { ... }
A virtual machine for executing regex searches with capturing groups.
Infallible APIs
Unlike most other regex engines in this crate, a PikeVM never returns an
error at search time. It supports all Anchored configurations, never
quits and works on haystacks of arbitrary length.
There are two caveats to mention though:
- If an invalid pattern ID is given to a search via
Anchored::Pattern, then the PikeVM will report "no match." This is consistent with all other regex engines in this crate. - When using
PikeVM::which_overlapping_matcheswith aPatternSetthat has insufficient capacity to store all valid pattern IDs, then if a match occurs for aPatternIDthat cannot be inserted, it is silently dropped as if it did not match.
Advice
The PikeVM is generally the most "powerful" regex engine in this crate.
"Powerful" in this context means that it can handle any regular expression
that is parseable by regex-syntax and any size haystack. Regretably,
the PikeVM is also simultaneously often the slowest regex engine in
practice. This results in an annoying situation where one generally tries
to pick any other regex engine (or perhaps none at all) before being
forced to fall back to a PikeVM.
For example, a common strategy for dealing with capturing groups is to
actually look for the overall match of the regex using a faster regex
engine, like a lazy DFA. Once the overall
match is found, one can then run the PikeVM on just the match span to
find the spans of the capturing groups. In this way, the faster regex
engine does the majority of the work, while the PikeVM only lends its
power in a more limited role.
Unfortunately, this isn't always possible because the faster regex engines
don't support all of the regex features in regex-syntax. This notably
includes (and is currently limited to) Unicode word boundaries. So if
your pattern has Unicode word boundaries, you typically can't use a
DFA-based regex engine at all (unless you enable heuristic support for
it). (The one-pass
DFA can handle Unicode word boundaries for
anchored searches only, but in a cruel sort of joke, many Unicode features
tend to result in making the regex not one-pass.)
Example
This example shows that the PikeVM implements Unicode word boundaries
correctly by default.
# if cfg! // miri takes too long
use ;
let re = new?;
let mut cache = re.create_cache;
let mut it = re.find_iter;
assert_eq!;
assert_eq!;
assert_eq!;
# Ok::
Implementations
impl PikeVM
fn is_match<'h, I: Into<Input<'h>>>(self: &Self, cache: &mut Cache, input: I) -> boolReturns true if and only if this
PikeVMmatches the given haystack.This routine may short circuit if it knows that scanning future input will never lead to a different result. In particular, if the underlying NFA enters a match state, then this routine will return
trueimmediately without inspecting any future input. (Consider how this might make a difference given the regexa+on the haystackaaaaaaaaaaaaaaa. This routine can stop after it sees the firsta, but routines likefindneed to continue searching because+is greedy by default.)Example
This shows basic usage:
use PikeVM; let re = new?; let mut cache = re.create_cache; assert!; assert!; # Ok::Example: consistency with search APIs
is_matchis guaranteed to returntruewheneverfindreturns a match. This includes searches that are executed entirely within a codepoint:use ; let re = new?; let mut cache = re.create_cache; assert!; # Ok::Notice that when UTF-8 mode is disabled, then the above reports a match because the restriction against zero-width matches that split a codepoint has been lifted:
use ; let re = builder .thompson .build?; let mut cache = re.create_cache; assert!; # Ok::fn find<'h, I: Into<Input<'h>>>(self: &Self, cache: &mut Cache, input: I) -> Option<Match>Executes a leftmost forward search and returns a
Matchif one exists.This routine only includes the overall match span. To get access to the individual spans of each capturing group, use
PikeVM::captures.Example
Leftmost first match semantics corresponds to the match with the smallest starting offset, but where the end offset is determined by preferring earlier branches in the original regular expression. For example,
Sam|Samwisewill matchSaminSamwise, butSamwise|Samwill matchSamwiseinSamwise.Generally speaking, the "leftmost first" match is how most backtracking regular expressions tend to work. This is in contrast to POSIX-style regular expressions that yield "leftmost longest" matches. Namely, both
Sam|SamwiseandSamwise|SammatchSamwisewhen using leftmost longest semantics. (This crate does not currently support leftmost longest semantics.)use ; let re = new?; let mut cache = re.create_cache; let expected = must; assert_eq!; // Even though a match is found after reading the first byte (`a`), // the leftmost first match semantics demand that we find the earliest // match that prefers earlier parts of the pattern over later parts. let re = new?; let mut cache = re.create_cache; let expected = must; assert_eq!; # Ok::fn captures<'h, I: Into<Input<'h>>>(self: &Self, cache: &mut Cache, input: I, caps: &mut Captures)Executes a leftmost forward search and writes the spans of capturing groups that participated in a match into the provided
Capturesvalue. If no match was found, thenCaptures::is_matchis guaranteed to returnfalse.Example
use ; let re = new?; let = ; re.captures; assert!; assert_eq!; assert_eq!; assert_eq!; # Ok::fn find_iter<'r, 'c, 'h, I: Into<Input<'h>>>(self: &'r Self, cache: &'c mut Cache, input: I) -> FindMatches<'r, 'c, 'h>Returns an iterator over all non-overlapping leftmost matches in the given bytes. If no match exists, then the iterator yields no elements.
Example
use ; let re = new?; let mut cache = re.create_cache; let text = "foo1 foo12 foo123"; let matches: = re.find_iter.collect; assert_eq!; # Ok::fn captures_iter<'r, 'c, 'h, I: Into<Input<'h>>>(self: &'r Self, cache: &'c mut Cache, input: I) -> CapturesMatches<'r, 'c, 'h>Returns an iterator over all non-overlapping
Capturesvalues. If no match exists, then the iterator yields no elements.This yields the same matches as
PikeVM::find_iter, but it includes the spans of all capturing groups that participate in each match.Tip: See
util::iter::Searcherfor how to correctly iterate over all matches in a haystack while avoiding the creation of a newCapturesvalue for every match. (Which you are forced to do with anIterator.)Example
use ; let re = new?; let mut cache = re.create_cache; let text = "foo1 foo12 foo123"; let matches: = re .captures_iter // The unwrap is OK since 'numbers' matches if the pattern matches. .map .collect; assert_eq!; # Ok::
impl PikeVM
fn new(pattern: &str) -> Result<PikeVM, BuildError>Parse the given regular expression using the default configuration and return the corresponding
PikeVM.If you want a non-default configuration, then use the
Builderto set your own configuration.Example
use ; let re = new?; let mut cache = re.create_cache; assert_eq!; # Ok::fn new_many<P: AsRef<str>>(patterns: &[P]) -> Result<PikeVM, BuildError>Like
new, but parses multiple patterns into a single "multi regex." This similarly uses the default regex configuration.Example
use ; let re = new_many?; let mut cache = re.create_cache; let mut it = re.find_iter; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; # Ok::fn new_from_nfa(nfa: NFA) -> Result<PikeVM, BuildError>Like
new, but builds a PikeVM directly from an NFA. This is useful if you already have an NFA, or even if you hand-assembled the NFA.Example
This shows how to hand assemble a regular expression via its HIR, compile an NFA from it and build a PikeVM from the NFA.
use ; use ; let hir = class; let config = NFAconfig.nfa_size_limit; let nfa = NFAcompiler.configure.build_from_hir?; let re = new_from_nfa?; let = ; let expected = Some; re.captures; assert_eq!; # Ok::fn always_match() -> Result<PikeVM, BuildError>Create a new
PikeVMthat matches every input.Example
use ; let re = always_match?; let mut cache = re.create_cache; let expected = must; assert_eq!; assert_eq!; # Ok::fn never_match() -> Result<PikeVM, BuildError>Create a new
PikeVMthat never matches any input.Example
use PikeVM; let re = never_match?; let mut cache = re.create_cache; assert_eq!; assert_eq!; # Ok::fn config() -> ConfigReturn a default configuration for a
PikeVM.This is a convenience routine to avoid needing to import the
Configtype when customizing the construction of aPikeVM.Example
This example shows how to disable UTF-8 mode. When UTF-8 mode is disabled, zero-width matches that split a codepoint are allowed. Otherwise they are never reported.
In the code below, notice that
""is permitted to match positions that split the encoding of a codepoint.use ; let re = builder .thompson .build?; let mut cache = re.create_cache; let haystack = "a☃z"; let mut it = re.find_iter; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; # Ok::fn builder() -> BuilderReturn a builder for configuring the construction of a
PikeVM.This is a convenience routine to avoid needing to import the
Buildertype in common cases.Example
This example shows how to use the builder to disable UTF-8 mode everywhere.
use ; let re = builder .syntax .thompson .build?; let = ; let haystack = b"\xFEfoo\xFFarzz\xE2\x98\xFF\n"; let expected = Some; re.captures; assert_eq!; # Ok::fn create_captures(self: &Self) -> CapturesCreate a new empty set of capturing groups that is guaranteed to be valid for the search APIs on this
PikeVM.A
Capturesvalue created for a specificPikeVMcannot be used with any otherPikeVM.This is a convenience function for
Captures::all. See theCapturesdocumentation for an explanation of its alternative constructors that permit thePikeVMto do less work during a search, and thus might make it faster.fn create_cache(self: &Self) -> CacheCreate a new cache for this
PikeVM.The cache returned should only be used for searches for this
PikeVM. If you want to reuse the cache for anotherPikeVM, then you must callCache::resetwith thatPikeVM(or, equivalently,PikeVM::reset_cache).fn reset_cache(self: &Self, cache: &mut Cache)Reset the given cache such that it can be used for searching with the this
PikeVM(and only thisPikeVM).A cache reset permits reusing memory already allocated in this cache with a different
PikeVM.Example
This shows how to re-purpose a cache for use with a different
PikeVM.# if cfg! // miri takes too long use ; let re1 = new?; let re2 = new?; let mut cache = re1.create_cache; assert_eq!; // Using 'cache' with re2 is not allowed. It may result in panics or // incorrect results. In order to re-purpose the cache, we must reset // it with the PikeVM we'd like to use it with. // // Similarly, after this reset, using the cache with 're1' is also not // allowed. re2.reset_cache; assert_eq!; # Ok::fn pattern_len(self: &Self) -> usizeReturns the total number of patterns compiled into this
PikeVM.In the case of a
PikeVMthat contains no patterns, this returns0.Example
This example shows the pattern length for a
PikeVMthat never matches:use PikeVM; let re = never_match?; assert_eq!; # Ok::And another example for a
PikeVMthat matches at every position:use PikeVM; let re = always_match?; assert_eq!; # Ok::And finally, a
PikeVMthat was constructed from multiple patterns:use PikeVM; let re = new_many?; assert_eq!; # Ok::fn get_config(self: &Self) -> &ConfigReturn the config for this
PikeVM.fn get_nfa(self: &Self) -> &NFAReturns a reference to the underlying NFA.
impl PikeVM
fn search(self: &Self, cache: &mut Cache, input: &Input<'_>, caps: &mut Captures)Executes a leftmost forward search and writes the spans of capturing groups that participated in a match into the provided
Capturesvalue. If no match was found, thenCaptures::is_matchis guaranteed to returnfalse.This is like
PikeVM::captures, but it accepts a concrete&Inputinstead of anInto<Input>.Example: specific pattern search
This example shows how to build a multi-PikeVM that permits searching for specific patterns.
use ; let re = new_many?; let = ; let haystack = "foo123"; // Since we are using the default leftmost-first match and both // patterns match at the same starting position, only the first pattern // will be returned in this case when doing a search for any of the // patterns. let expected = Some; re.search; assert_eq!; // But if we want to check whether some other pattern matches, then we // can provide its pattern ID. let expected = Some; let input = new .anchored; re.search; assert_eq!; # Ok::Example: specifying the bounds of a search
This example shows how providing the bounds of a search can produce different results than simply sub-slicing the haystack.
# if cfg! // miri takes too long use ; let re = new?; let = ; let haystack = "foo123bar"; // Since we sub-slice the haystack, the search doesn't know about // the larger context and assumes that `123` is surrounded by word // boundaries. And of course, the match position is reported relative // to the sub-slice as well, which means we get `0..3` instead of // `3..6`. let expected = Some; re.search; assert_eq!; // But if we provide the bounds of the search within the context of the // entire haystack, then the search can take the surrounding context // into account. (And if we did find a match, it would be reported // as a valid offset into `haystack` instead of its sub-slice.) let expected = None; let input = new.range; re.search; assert_eq!; # Ok::fn search_slots(self: &Self, cache: &mut Cache, input: &Input<'_>, slots: &mut [Option<NonMaxUsize>]) -> Option<PatternID>Executes a leftmost forward search and writes the spans of capturing groups that participated in a match into the provided
slots, and returns the matching pattern ID. The contents of the slots for patterns other than the matching pattern are unspecified. If no match was found, thenNoneis returned and the contents ofslotsis unspecified.This is like
PikeVM::search, but it accepts a raw slots slice instead of aCapturesvalue. This is useful in contexts where you don't want or need to allocate aCaptures.It is legal to pass any number of slots to this routine. If the regex engine would otherwise write a slot offset that doesn't fit in the provided slice, then it is simply skipped. In general though, there are usually three slice lengths you might want to use:
- An empty slice, if you only care about which pattern matched.
- A slice with
pattern_len() * 2slots, if you only care about the overall match spans for each matching pattern. - A slice with
slot_len()slots, which permits recording match offsets for every capturing group in every pattern.
Example
This example shows how to find the overall match offsets in a multi-pattern search without allocating a
Capturesvalue. Indeed, we can put our slots right on the stack.# if cfg! // miri takes too long use ; let re = new_many?; let mut cache = re.create_cache; let input = new; // We only care about the overall match offsets here, so we just // allocate two slots for each pattern. Each slot records the start // and end of the match. let mut slots = ; let pid = re.search_slots; assert_eq!; // The overall match offsets are always at 'pid * 2' and 'pid * 2 + 1'. // See 'GroupInfo' for more details on the mapping between groups and // slot indices. let slot_start = pid.unwrap.as_usize * 2; let slot_end = slot_start + 1; assert_eq!; assert_eq!; # Ok::fn which_overlapping_matches(self: &Self, cache: &mut Cache, input: &Input<'_>, patset: &mut PatternSet)Writes the set of patterns that match anywhere in the given search configuration to
patset. If multiple patterns match at the same position and thisPikeVMwas configured withMatchKind::Allsemantics, then all matching patterns are written to the given set.Unless all of the patterns in this
PikeVMare anchored, then generally speaking, this will visit every byte in the haystack.This search routine does not clear the pattern set. This gives some flexibility to the caller (e.g., running multiple searches with the same pattern set), but does make the API bug-prone if you're reusing the same pattern set for multiple searches but intended them to be independent.
If a pattern ID matched but the given
PatternSetdoes not have sufficient capacity to store it, then it is not inserted and silently dropped.Example
This example shows how to find all matching patterns in a haystack, even when some patterns match at the same position as other patterns.
# if cfg! // miri takes too long use ; let patterns = &; let re = builder .configure .build_many?; let mut cache = re.create_cache; let input = new; let mut patset = new; re.which_overlapping_matches; let expected = vec!; let got: = patset.iter.map.collect; assert_eq!; # Ok::
impl Clone for PikeVM
fn clone(self: &Self) -> PikeVM
impl Debug for PikeVM
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Freeze for PikeVM
impl RefUnwindSafe for PikeVM
impl Send for PikeVM
impl Sync for PikeVM
impl Unpin for PikeVM
impl UnsafeUnpin for PikeVM
impl UnwindSafe for PikeVM
impl<T> Any for PikeVM
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for PikeVM
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for PikeVM
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for PikeVM
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for PikeVM
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for PikeVM
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for PikeVM
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for PikeVM
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for PikeVM
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>