rust-utils: add util to find a slice in another slice
authorRaphaël Gomès <rgomes@octobus.net>
Tue, 14 Jan 2020 18:00:05 +0100
changeset 44079 191a461d6be6
parent 44078 f2c350e7371e
child 44080 4e05272dd681
rust-utils: add util to find a slice in another slice Differential Revision: https://phab.mercurial-scm.org/D7863
rust/hg-core/src/utils.rs
--- 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