Patchwork D7863: rust-utils: add util to find a slice in another slice

login
register
mail settings
Submitter phabricator
Date Jan. 14, 2020, 10:34 p.m.
Message ID <d999b3c8cf7b3021941d956dde3fbe37@localhost.localdomain>
Download mbox | patch
Permalink /patch/44347/
State Not Applicable
Headers show

Comments

phabricator - Jan. 14, 2020, 10:34 p.m.
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

Patch

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<T>(slice: &[T], needle: &[T]) -> Option<usize>
+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