Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subslice search #54961

Open
leonardo-m opened this Issue Oct 10, 2018 · 2 comments

Comments

Projects
None yet
3 participants
@leonardo-m
Copy link

leonardo-m commented Oct 10, 2018

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

@estebank estebank added the T-libs label Oct 10, 2018

@Shnatsel

This comment has been minimized.

Copy link

Shnatsel commented Jan 12, 2019

I am baffled that this is actually not in the standard library. Functions contains and find are apparently implemented for strings but not slices?

@Shnatsel

This comment has been minimized.

Copy link

Shnatsel commented Jan 12, 2019

At least there is a third-party crate based on stdlib implementation for strings: https://github.com/strake/subslice.rs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.