1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Original implementation taken from rust-memchr
12 // Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
14 /// A safe interface to `memchr`.
16 /// Returns the index corresponding to the first occurrence of `needle` in
17 /// `haystack`, or `None` if one is not found.
19 /// memchr reduces to super-optimized machine code at around an order of
20 /// magnitude faster than `haystack.iter().position(|&b| b == needle)`.
25 /// This shows how to find the first position of a byte in a byte string.
27 /// ```ignore (cannot-doctest-private-modules)
28 /// use memchr::memchr;
30 /// let haystack = b"the quick brown fox";
31 /// assert_eq!(memchr(b'k', haystack), Some(8));
34 pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
35 ::sys::memchr::memchr(needle, haystack)
38 /// A safe interface to `memrchr`.
40 /// Returns the index corresponding to the last occurrence of `needle` in
41 /// `haystack`, or `None` if one is not found.
45 /// This shows how to find the last position of a byte in a byte string.
47 /// ```ignore (cannot-doctest-private-modules)
48 /// use memchr::memrchr;
50 /// let haystack = b"the quick brown fox";
51 /// assert_eq!(memrchr(b'o', haystack), Some(17));
54 pub fn memrchr(needle: u8, haystack: &[u8]) -> Option<usize> {
55 ::sys::memchr::memrchr(needle, haystack)
60 // test the implementations for the current plattform
61 use super::{memchr, memrchr};
65 assert_eq!(Some(0), memchr(b'a', b"a"));
70 assert_eq!(Some(0), memchr(b'a', b"aaaa"));
75 assert_eq!(Some(4), memchr(b'z', b"aaaaz"));
80 assert_eq!(Some(4), memchr(b'\x00', b"aaaa\x00"));
84 fn matches_past_nul() {
85 assert_eq!(Some(5), memchr(b'z', b"aaaa\x00z"));
90 assert_eq!(None, memchr(b'a', b""));
95 assert_eq!(None, memchr(b'a', b"xyz"));
99 fn matches_one_reversed() {
100 assert_eq!(Some(0), memrchr(b'a', b"a"));
104 fn matches_begin_reversed() {
105 assert_eq!(Some(3), memrchr(b'a', b"aaaa"));
109 fn matches_end_reversed() {
110 assert_eq!(Some(0), memrchr(b'z', b"zaaaa"));
114 fn matches_nul_reversed() {
115 assert_eq!(Some(4), memrchr(b'\x00', b"aaaa\x00"));
119 fn matches_past_nul_reversed() {
120 assert_eq!(Some(0), memrchr(b'z', b"z\x00aaaa"));
124 fn no_match_empty_reversed() {
125 assert_eq!(None, memrchr(b'a', b""));
129 fn no_match_reversed() {
130 assert_eq!(None, memrchr(b'a', b"xyz"));
134 fn each_alignment() {
135 let mut data = [1u8; 64];
140 assert_eq!(Some(pos - start), memchr(needle, &data[start..]));