Trait pattern_3::needle::ReverseConsumer
source · pub unsafe trait ReverseConsumer<A: Hay + ?Sized>: Consumer<A> {
fn rconsume(&mut self, hay: Span<&A>) -> Option<A::Index>;
fn trim_end(&mut self, hay: &A) -> A::Index { ... }
}
Expand description
A consumer which can be searched from the end.
This trait provides methods for matching a needle anchored at the end of a hay.
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 rconsume(&mut self, hay: Span<&A>) -> Option<A::Index>
fn rconsume(&mut self, hay: Span<&A>) -> Option<A::Index>
Checks if the needle can be found at the end of the span.
This method is used to implement the standard algorithm
ends_with()
as well as providing the default
implementation for .trim_end()
.
The hay and the restricted range for searching can be recovered by
calling span
.into_parts()
. If a needle can be
found ending at range.end
, this method should return the start index
of the needle relative to the hay.
If the needle cannot be found at the end of the span, this method
should return None
.
Examples
Consumes ASCII characters from the end.
extern crate pattern_3;
use pattern_3::{ReverseConsumer, Needle, Span};
let mut consumer = Needle::<&str>::into_consumer(|c: char| c.is_ascii());
let span = Span::from("Hi😋!!");
// consumes the last ASCII character
assert_eq!(consumer.rconsume(span.clone()), Some(7));
// slice the span to skip the first match.
let span = unsafe { span.slice_unchecked(0..7) };
// matched the second to last ASCII character
assert_eq!(consumer.rconsume(span.clone()), Some(6));
// should match nothing now.
let span = unsafe { span.slice_unchecked(0..6) };
assert_eq!(consumer.rconsume(span.clone()), None);
Provided Methods§
sourcefn trim_end(&mut self, hay: &A) -> A::Index
fn trim_end(&mut self, hay: &A) -> A::Index
Repeatedly removes suffixes of the hay which matches the needle.
This method is used to implement the standard algorithm
trim_end()
.
A fast generic implementation in terms of
.rconsume()
is provided by default.
Nevertheless, many needles allow a higher-performance specialization.
Examples
extern crate pattern_3;
use pattern_3::{ReverseConsumer, Needle, Span};
let mut consumer = Needle::<&str>::into_consumer('x');
assert_eq!(consumer.trim_end("yyxxx"), 2);
let mut consumer = Needle::<&str>::into_consumer('x');
assert_eq!(consumer.trim_end("xxxyy"), 5);