Subslice search · Issue #54961 · rust-lang/rust (original) (raw)
Navigation Menu
- Explore
- Pricing
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Description
As enhancement, I think stdlib should contain functions that search a subslice inside a given slice:
fn contains_subslice<T: PartialEq>(data: &[T], needle: &[T]) -> bool {
data
.windows(needle.len())
.any(|w| w == needle)
}
fn position_subslice<T: PartialEq>(data: &[T], needle: &[T]) -> Option<usize> {
data
.windows(needle.len())
.enumerate()
.find(|&(_, w)| w == needle)
.map(|(i, _)| i)
}
fn main() {
println!("{}", contains_subslice(b"hello", b"ll"));
println!("{:?}", position_subslice(b"hello", b"ll"));
}
For the common case of T:Copy items the true stdlib functions should specialize using a smarter algorithm, like:
https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
(Similar functions are useful for iterators too).