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

Alphare (Raphaël Gomès) phabricator at mercurial-scm.org
Tue Jan 14 17:34:38 EST 2020


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

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



To: Alphare, #hg-reviewers, pulkit
Cc: durin42, kevincox, mercurial-devel


More information about the Mercurial-devel mailing list