1

Javascript provides "abcde".indexOf("de") === 3.

I'd like to do the same thing for a &[T] where T implements PartialEq.

fn search_haystack<T: PartialEq>(needle: &[T], haystack: &[T]) -> Option<usize> {
    todo!()
}
fn main() {
    let haystack = [1,2,3,4,5];
    let needle = [3,4];
    assert_eq!(search_haystack(&needle, &haystack), Some(2))
}

I could write this function myself but it seems like something the stdlib would offer, and I have not been able to find it. How do I accomplish this efficiently using the stdlib (not nightly).

nlta
  • 1,716
  • 1
  • 7
  • 17

1 Answers1

1

You can use slice.windows(n) to get an iterator of all subslices of length n. You can combine that with iterator.position() to find the first subslice that is equal to needle:

fn search_haystack<T: PartialEq>(needle: &[T], haystack: &[T]) -> Option<usize> {
    if needle.is_empty() {
        // special case: `haystack.windows(0)` will panic, so this case
        // needs to be handled separately in whatever way you feel is
        // appropriate
        return Some(0);
    }

    haystack.windows(needle.len()).position(|subslice| subslice == needle)
}
Frxstrem
  • 38,761
  • 9
  • 79
  • 119
  • Yes this works I benchmarked it against a simple loop with starts_with and performance is identical. Thank you! – nlta Dec 10 '22 at 22:59