comparison rust/hg-core/src/utils.rs @ 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 3fe40dd6355d
children c18dd48cea4a
comparison
equal deleted inserted replaced
44078:f2c350e7371e 44079:191a461d6be6
7 7
8 //! Contains useful functions, traits, structs, etc. for use in core. 8 //! Contains useful functions, traits, structs, etc. for use in core.
9 9
10 pub mod files; 10 pub mod files;
11 pub mod hg_path; 11 pub mod hg_path;
12
13 /// Useful until rust/issues/56345 is stable
14 ///
15 /// # Examples
16 ///
17 /// ```
18 /// use crate::hg::utils::find_slice_in_slice;
19 ///
20 /// let haystack = b"This is the haystack".to_vec();
21 /// assert_eq!(find_slice_in_slice(&haystack, b"the"), Some(8));
22 /// assert_eq!(find_slice_in_slice(&haystack, b"not here"), None);
23 /// ```
24 pub fn find_slice_in_slice<T>(slice: &[T], needle: &[T]) -> Option<usize>
25 where
26 for<'a> &'a [T]: PartialEq,
27 {
28 slice
29 .windows(needle.len())
30 .position(|window| window == needle)
31 }
12 32
13 /// Replaces the `from` slice with the `to` slice inside the `buf` slice. 33 /// Replaces the `from` slice with the `to` slice inside the `buf` slice.
14 /// 34 ///
15 /// # Examples 35 /// # Examples
16 /// 36 ///