]> git.lizzy.rs Git - rust.git/blob - library/std/src/memchr.rs
std: move "mod tests/benches" to separate files
[rust.git] / library / std / src / memchr.rs
1 // Original implementation taken from rust-memchr.
2 // Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
3
4 #[cfg(test)]
5 mod tests;
6
7 /// A safe interface to `memchr`.
8 ///
9 /// Returns the index corresponding to the first occurrence of `needle` in
10 /// `haystack`, or `None` if one is not found.
11 ///
12 /// memchr reduces to super-optimized machine code at around an order of
13 /// magnitude faster than `haystack.iter().position(|&b| b == needle)`.
14 /// (See benchmarks.)
15 ///
16 /// # Examples
17 ///
18 /// This shows how to find the first position of a byte in a byte string.
19 ///
20 /// ```ignore (cannot-doctest-private-modules)
21 /// use memchr::memchr;
22 ///
23 /// let haystack = b"the quick brown fox";
24 /// assert_eq!(memchr(b'k', haystack), Some(8));
25 /// ```
26 #[inline]
27 pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
28     crate::sys::memchr::memchr(needle, haystack)
29 }
30
31 /// A safe interface to `memrchr`.
32 ///
33 /// Returns the index corresponding to the last occurrence of `needle` in
34 /// `haystack`, or `None` if one is not found.
35 ///
36 /// # Examples
37 ///
38 /// This shows how to find the last position of a byte in a byte string.
39 ///
40 /// ```ignore (cannot-doctest-private-modules)
41 /// use memchr::memrchr;
42 ///
43 /// let haystack = b"the quick brown fox";
44 /// assert_eq!(memrchr(b'o', haystack), Some(17));
45 /// ```
46 #[inline]
47 pub fn memrchr(needle: u8, haystack: &[u8]) -> Option<usize> {
48     crate::sys::memchr::memrchr(needle, haystack)
49 }