-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Open
Labels
C-feature-requestCategory: A feature request, i.e: not implemented / a PR.Category: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.
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).
windelbouwman, cx88, scooter-dangle, Aidiakapi, leeduhem and 38 moremarcospb19, seandewar, DaniSancas, sammysheep, ByteNybbler and 2 more
Metadata
Metadata
Assignees
Labels
C-feature-requestCategory: A feature request, i.e: not implemented / a PR.Category: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.