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