changeset 44079:191a461d6be6

rust-utils: add util to find a slice in another slice Differential Revision: https://phab.mercurial-scm.org/D7863
author Raphaël Gomès <rgomes@octobus.net>
date Tue, 14 Jan 2020 18:00:05 +0100
parents f2c350e7371e
children 4e05272dd681
files rust/hg-core/src/utils.rs
diffstat 1 files changed, 20 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/rust/hg-core/src/utils.rs	Tue Jan 14 16:00:57 2020 +0100
+++ b/rust/hg-core/src/utils.rs	Tue Jan 14 18:00:05 2020 +0100
@@ -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