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

login
register
mail settings
Submitter phabricator
Date Jan. 15, 2020, 9:55 p.m.
Message ID <dadb669fef27a92a631a4aabf9ed5a95@localhost.localdomain>
Download mbox | patch
Permalink /patch/44387/
State Not Applicable
Headers show

Comments

phabricator - Jan. 15, 2020, 9:55 p.m.
Alphare updated this revision to Diff 19315.

REPOSITORY
  rHG Mercurial

CHANGES SINCE LAST UPDATE
  https://phab.mercurial-scm.org/D7863?vs=19274&id=19315

BRANCH
  default

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