Skip to main content

core/slice/
memchr.rs

1// Original implementation taken from rust-memchr.
2// Copyright 2015 Andrew Gallant, bluss and Nicolas Koch
3
4use crate::intrinsics::const_eval_select;
5
6const LO_USIZE: usize = usize::repeat_u8(0x01);
7const HI_USIZE: usize = usize::repeat_u8(0x80);
8const USIZE_BYTES: usize = size_of::<usize>();
9
10/// Returns `true` if `x` contains any zero byte.
11///
12/// From *Matters Computational*, J. Arndt:
13///
14/// "The idea is to subtract one from each of the bytes and then look for
15/// bytes where the borrow propagated all the way to the most significant
16/// bit."
17#[inline]
18const fn contains_zero_byte(x: usize) -> bool {
19    x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0
20}
21
22/// Returns the first index matching the byte `x` in `text`.
23#[inline]
24#[must_use]
25pub const fn memchr(x: u8, text: &[u8]) -> Option<usize> {
26    // Fast path for small slices.
27    let result =
28        if text.len() < 2 * USIZE_BYTES { memchr_naive(x, text) } else { memchr_aligned(x, text) };
29    if let Some(index) = result {
30        // SAFETY: Both implementations only return an index from within `text`.
31        unsafe { crate::hint::assert_unchecked(index < text.len()) };
32    }
33    result
34}
35
36#[inline]
37const fn memchr_naive(x: u8, text: &[u8]) -> Option<usize> {
38    let mut i = 0;
39
40    // FIXME(const-hack): Replace with `text.iter().pos(|c| *c == x)`.
41    while i < text.len() {
42        if text[i] == x {
43            return Some(i);
44        }
45
46        i += 1;
47    }
48
49    None
50}
51
52#[rustc_allow_const_fn_unstable(const_eval_select)] // fallback impl has same behavior
53const fn memchr_aligned(x: u8, text: &[u8]) -> Option<usize> {
54    // The runtime version behaves the same as the compiletime version, it's
55    // just more optimized.
56    const_eval_select!(
57        @capture { x: u8, text: &[u8] } -> Option<usize>:
58        if const {
59            memchr_naive(x, text)
60        } else {
61            // Scan for a single byte value by reading two `usize` words at a time.
62            //
63            // Split `text` in three parts
64            // - unaligned initial part, before the first word aligned address in text
65            // - body, scan by 2 words at a time
66            // - the last remaining part, < 2 word size
67
68            // search up to an aligned boundary
69            let len = text.len();
70            let ptr = text.as_ptr();
71            let mut offset = ptr.align_offset(USIZE_BYTES);
72
73            if offset > 0 {
74                offset = offset.min(len);
75                let slice = &text[..offset];
76                if let Some(index) = memchr_naive(x, slice) {
77                    return Some(index);
78                }
79            }
80
81            // search the body of the text
82            let repeated_x = usize::repeat_u8(x);
83            while offset <= len - 2 * USIZE_BYTES {
84                // SAFETY: the while's predicate guarantees a distance of at least 2 * usize_bytes
85                // between the offset and the end of the slice.
86                unsafe {
87                    let u = *(ptr.add(offset) as *const usize);
88                    let v = *(ptr.add(offset + USIZE_BYTES) as *const usize);
89
90                    // break if there is a matching byte
91                    let zu = contains_zero_byte(u ^ repeated_x);
92                    let zv = contains_zero_byte(v ^ repeated_x);
93                    if zu || zv {
94                        break;
95                    }
96                }
97                offset += USIZE_BYTES * 2;
98            }
99
100            // Find the byte after the point the body loop stopped.
101            // FIXME(const-hack): Use `?` instead.
102            // FIXME(const-hack, fee1-dead): use range slicing
103            let slice =
104            // SAFETY: offset is within bounds
105                unsafe { super::from_raw_parts(text.as_ptr().add(offset), text.len() - offset) };
106            if let Some(i) = memchr_naive(x, slice) { Some(offset + i) } else { None }
107        }
108    )
109}
110
111/// Returns the last index matching the byte `x` in `text`.
112#[inline]
113#[must_use]
114pub fn memrchr(x: u8, text: &[u8]) -> Option<usize> {
115    let result = memrchr_aligned(x, text);
116    if let Some(index) = result {
117        // SAFETY: `memrchr_aligned` only returns the index of a matching byte in `text`.
118        unsafe { crate::hint::assert_unchecked(index < text.len()) };
119    }
120    result
121}
122
123fn memrchr_aligned(x: u8, text: &[u8]) -> Option<usize> {
124    // Scan for a single byte value by reading two `usize` words at a time.
125    //
126    // Split `text` in three parts:
127    // - unaligned tail, after the last word aligned address in text,
128    // - body, scanned by 2 words at a time,
129    // - the first remaining bytes, < 2 word size.
130    let len = text.len();
131    let ptr = text.as_ptr();
132    type Chunk = usize;
133
134    let (min_aligned_offset, max_aligned_offset) = {
135        // We call this just to obtain the length of the prefix and suffix.
136        // In the middle we always process two chunks at once.
137        // SAFETY: transmuting `[u8]` to `[usize]` is safe except for size differences
138        // which are handled by `align_to`.
139        let (prefix, _, suffix) = unsafe { text.align_to::<(Chunk, Chunk)>() };
140        (prefix.len(), len - suffix.len())
141    };
142
143    let mut offset = max_aligned_offset;
144    if let Some(index) = text[offset..].iter().rposition(|elt| *elt == x) {
145        return Some(offset + index);
146    }
147
148    // Search the body of the text, make sure we don't cross min_aligned_offset.
149    // offset is always aligned, so just testing `>` is sufficient and avoids possible
150    // overflow.
151    let repeated_x = usize::repeat_u8(x);
152    let chunk_bytes = size_of::<Chunk>();
153
154    while offset > min_aligned_offset {
155        // SAFETY: offset starts at len - suffix.len(), as long as it is greater than
156        // min_aligned_offset (prefix.len()) the remaining distance is at least 2 * chunk_bytes.
157        unsafe {
158            let u = *(ptr.add(offset - 2 * chunk_bytes) as *const Chunk);
159            let v = *(ptr.add(offset - chunk_bytes) as *const Chunk);
160
161            // Break if there is a matching byte.
162            let zu = contains_zero_byte(u ^ repeated_x);
163            let zv = contains_zero_byte(v ^ repeated_x);
164            if zu || zv {
165                break;
166            }
167        }
168        offset -= 2 * chunk_bytes;
169    }
170
171    // Find the byte before the point the body loop stopped.
172    text[..offset].iter().rposition(|elt| *elt == x)
173}