2 // Original implementation taken from rust-memchr
3 // Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
5 /// A safe interface to `memchr`.
7 /// Returns the index corresponding to the first occurrence of `needle` in
8 /// `haystack`, or `None` if one is not found.
10 /// memchr reduces to super-optimized machine code at around an order of
11 /// magnitude faster than `haystack.iter().position(|&b| b == needle)`.
16 /// This shows how to find the first position of a byte in a byte string.
18 /// ```ignore (cannot-doctest-private-modules)
19 /// use memchr::memchr;
21 /// let haystack = b"the quick brown fox";
22 /// assert_eq!(memchr(b'k', haystack), Some(8));
25 pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
26 ::sys::memchr::memchr(needle, haystack)
29 /// A safe interface to `memrchr`.
31 /// Returns the index corresponding to the last occurrence of `needle` in
32 /// `haystack`, or `None` if one is not found.
36 /// This shows how to find the last position of a byte in a byte string.
38 /// ```ignore (cannot-doctest-private-modules)
39 /// use memchr::memrchr;
41 /// let haystack = b"the quick brown fox";
42 /// assert_eq!(memrchr(b'o', haystack), Some(17));
45 pub fn memrchr(needle: u8, haystack: &[u8]) -> Option<usize> {
46 ::sys::memchr::memrchr(needle, haystack)
51 // test the implementations for the current platform
52 use super::{memchr, memrchr};
56 assert_eq!(Some(0), memchr(b'a', b"a"));
61 assert_eq!(Some(0), memchr(b'a', b"aaaa"));
66 assert_eq!(Some(4), memchr(b'z', b"aaaaz"));
71 assert_eq!(Some(4), memchr(b'\x00', b"aaaa\x00"));
75 fn matches_past_nul() {
76 assert_eq!(Some(5), memchr(b'z', b"aaaa\x00z"));
81 assert_eq!(None, memchr(b'a', b""));
86 assert_eq!(None, memchr(b'a', b"xyz"));
90 fn matches_one_reversed() {
91 assert_eq!(Some(0), memrchr(b'a', b"a"));
95 fn matches_begin_reversed() {
96 assert_eq!(Some(3), memrchr(b'a', b"aaaa"));
100 fn matches_end_reversed() {
101 assert_eq!(Some(0), memrchr(b'z', b"zaaaa"));
105 fn matches_nul_reversed() {
106 assert_eq!(Some(4), memrchr(b'\x00', b"aaaa\x00"));
110 fn matches_past_nul_reversed() {
111 assert_eq!(Some(0), memrchr(b'z', b"z\x00aaaa"));
115 fn no_match_empty_reversed() {
116 assert_eq!(None, memrchr(b'a', b""));
120 fn no_match_reversed() {
121 assert_eq!(None, memrchr(b'a', b"xyz"));
125 fn each_alignment() {
126 let mut data = [1u8; 64];
131 assert_eq!(Some(pos - start), memchr(needle, &data[start..]));