pub unsafe trait Consumer<A: Hay + ?Sized> {
fn consume(&mut self, span: Span<&A>) -> Option<A::Index>;
fn trim_start(&mut self, hay: &A) -> A::Index { ... }
}
Expand description
A consumer, for searching a Needle
from a Hay
anchored at the
beginnning.
This trait provides methods for matching a needle anchored at the beginning of a hay.
See documentation of Searcher
for an example.
Safety
This trait is marked unsafe because the range returned by its methods are required to lie on valid codeword boundaries in the haystack. This enables users of this trait to slice the haystack without additional runtime checks.
Required Methods§
sourcefn consume(&mut self, span: Span<&A>) -> Option<A::Index>
fn consume(&mut self, span: Span<&A>) -> Option<A::Index>
Checks if the needle can be found at the beginning of the span.
This method is used to implement the standard algorithm
starts_with()
as well as providing the default
implementation for .trim_start()
.
The hay and the restricted range for searching can be recovered by
calling span
.into_parts()
. If a needle can be
found starting at range.start
, this method should return the end index
of the needle relative to the hay.
If the needle cannot be found at the beginning of the span, this method
should return None
.
Examples
Consumes ASCII characters from the beginning.
extern crate pattern_3;
use pattern_3::{Consumer, Needle, Span};
let mut consumer = Needle::<&str>::into_consumer(|c: char| c.is_ascii());
let span = Span::from("Hi😋!!");
// consumes the first ASCII character
assert_eq!(consumer.consume(span.clone()), Some(1));
// slice the span to skip the first match.
let span = unsafe { span.slice_unchecked(1..8) };
// matched the second ASCII character
assert_eq!(consumer.consume(span.clone()), Some(2));
// should match nothing now.
let span = unsafe { span.slice_unchecked(2..8) };
assert_eq!(consumer.consume(span.clone()), None);
Provided Methods§
sourcefn trim_start(&mut self, hay: &A) -> A::Index
fn trim_start(&mut self, hay: &A) -> A::Index
Repeatedly removes prefixes of the hay which matches the needle.
This method is used to implement the standard algorithm
trim_start()
.
Returns the start index of the slice after all prefixes are removed.
A fast generic implementation in terms of
.consume()
is provided by default. Nevertheless,
many needles allow a higher-performance specialization.
Examples
extern crate pattern_3;
use pattern_3::{Consumer, Needle, Span};
let mut consumer = Needle::<&str>::into_consumer('x');
assert_eq!(consumer.trim_start("xxxyy"), 3);
let mut consumer = Needle::<&str>::into_consumer('x');
assert_eq!(consumer.trim_start("yyxxx"), 0);