From patchwork Tue Jan 14 22:34:38 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: D7863: rust-utils: add util to find a slice in another slice From: phabricator X-Patchwork-Id: 44347 Message-Id: To: Phabricator Cc: mercurial-devel@mercurial-scm.org Date: Tue, 14 Jan 2020 22:34:38 +0000 Closed by commit rHGed57b3557443: rust-utils: add util to find a slice in another slice (authored by Alphare). This revision was automatically updated to reflect the committed changes. REPOSITORY rHG Mercurial CHANGES SINCE LAST UPDATE https://phab.mercurial-scm.org/D7863?vs=19255&id=19274 CHANGES SINCE LAST ACTION https://phab.mercurial-scm.org/D7863/new/ REVISION DETAIL https://phab.mercurial-scm.org/D7863 AFFECTED FILES rust/hg-core/src/utils.rs CHANGE DETAILS To: Alphare, #hg-reviewers, pulkit Cc: durin42, kevincox, mercurial-devel 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