Skip to content

Subslice search #54961

Open
Open
@leonardo-m

Description

@leonardo-m

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: 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.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions