# HG changeset patch # User Raphaël Gomès # Date 2020-01-14 17:00:05 # Node ID ed57b355744396130ed2507e09d9607f0cf86664 # Parent 717f7eb39655c070b3dd6c1c8486c192ab52ff34 rust-utils: add util to find a slice in another slice Differential Revision: https://phab.mercurial-scm.org/D7863 diff --git a/rust/hg-core/src/utils.rs b/rust/hg-core/src/utils.rs --- a/rust/hg-core/src/utils.rs +++ b/rust/hg-core/src/utils.rs @@ -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