# HG changeset patch # User Raphaël Gomès # Date 1579021205 -3600 # Node ID 191a461d6be60867a8069cb2f0698f78409c1dc2 # Parent f2c350e7371e340814daa020daeb4dc9203bc9c1 rust-utils: add util to find a slice in another slice Differential Revision: https://phab.mercurial-scm.org/D7863 diff -r f2c350e7371e -r 191a461d6be6 rust/hg-core/src/utils.rs --- a/rust/hg-core/src/utils.rs Tue Jan 14 16:00:57 2020 +0100 +++ b/rust/hg-core/src/utils.rs Tue Jan 14 18:00:05 2020 +0100 @@ -10,6 +10,26 @@ pub mod files; pub mod hg_path; +/// Useful until rust/issues/56345 is stable +/// +/// # Examples +/// +/// ``` +/// use crate::hg::utils::find_slice_in_slice; +/// +/// let haystack = b"This is the haystack".to_vec(); +/// assert_eq!(find_slice_in_slice(&haystack, b"the"), Some(8)); +/// assert_eq!(find_slice_in_slice(&haystack, b"not here"), None); +/// ``` +pub fn find_slice_in_slice(slice: &[T], needle: &[T]) -> Option +where + for<'a> &'a [T]: PartialEq, +{ + slice + .windows(needle.len()) + .position(|window| window == needle) +} + /// Replaces the `from` slice with the `to` slice inside the `buf` slice. /// /// # Examples