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