Skip to main content

sark_http/field/scan/
mod.rs

1//! Allocation-free scans over immutable wire bytes.
2
3use core::{mem, num::NonZero};
4
5const LANE: usize = 16;
6
7mod raw;
8
9/// One actual forward-search match retained on its exact immutable source.
10#[derive(Clone, Copy)]
11pub struct Match<'a> {
12    bytes: &'a [u8],
13    end: NonZero<usize>,
14}
15
16impl<'a> Match<'a> {
17    pub fn find(byte: u8, bytes: &'a [u8]) -> Option<Self> {
18        let index = memchr::memchr(byte, bytes)?;
19        // SAFETY: memchr returned this byte's position inside the exact retained source.
20        Some(unsafe { raw::found(bytes, index) })
21    }
22
23    pub fn find2(first: u8, second: u8, bytes: &'a [u8]) -> Option<Self> {
24        let index = memchr::memchr2(first, second, bytes)?;
25        // SAFETY: memchr2 returned a matched position inside the exact retained source.
26        Some(unsafe { raw::found(bytes, index) })
27    }
28
29    pub const fn start(self) -> usize {
30        self.end.get() - 1
31    }
32
33    pub const fn end(self) -> NonZero<usize> {
34        self.end
35    }
36
37    pub fn byte(self) -> u8 {
38        raw::byte(self)
39    }
40
41    pub fn prefix(self) -> &'a [u8] {
42        raw::before::<false>(self)
43    }
44
45    pub fn through(self) -> &'a [u8] {
46        raw::before::<true>(self)
47    }
48
49    pub fn tail(self) -> &'a [u8] {
50        raw::after::<true>(self)
51    }
52
53    pub fn suffix(self) -> &'a [u8] {
54        raw::after::<false>(self)
55    }
56}
57
58pub(crate) fn split_token(bytes: &[u8]) -> (&[u8], &[u8]) {
59    let Some(index) = bytes
60        .iter()
61        .position(|&byte| !super::Error::is_name_byte(byte))
62    else {
63        return (bytes, &[]);
64    };
65    // SAFETY: position found the delimiter in these same immutable bytes.
66    let end = unsafe { raw::found(bytes, index) };
67    (end.prefix(), end.tail())
68}
69
70#[derive(PartialEq, Eq)]
71pub enum Outcome<T> {
72    Found(T),
73    Invalid { offset: usize, actual: u8 },
74    Partial,
75}
76
77/// A pointer-sized view over bytes scanned as HTTP/1 field syntax.
78#[repr(transparent)]
79pub struct Bytes<'a>(&'a [u8]);
80
81impl<'a> Bytes<'a> {
82    pub const fn new(bytes: &'a [u8]) -> Self {
83        Self(bytes)
84    }
85
86    pub fn name(&self, start: usize) -> Outcome<(usize, u8)> {
87        let Some(rest) = self.0.get(start..) else {
88            return Outcome::Partial;
89        };
90        let (prefix, rest) = rest.split_at(rest.len().min(LANE));
91        let outcome = name_tail(prefix, start);
92        if !matches!(outcome, Outcome::Partial) {
93            return outcome;
94        }
95        if rest.is_empty() {
96            return Outcome::Partial;
97        }
98        let index = start + prefix.len();
99        if rest.len() < LANE {
100            return name_tail(rest, index);
101        }
102        name_simd(rest, index)
103    }
104
105    pub fn value(&self, start: usize) -> Outcome<usize> {
106        let Some(rest) = self.0.get(start..) else {
107            return Outcome::Partial;
108        };
109        value_simd(rest, start)
110    }
111}
112
113fn name_simd(bytes: &[u8], mut index: usize) -> Outcome<(usize, u8)> {
114    let (lanes, tail) = bytes.as_chunks::<LANE>();
115    let (groups, lanes) = lanes.as_chunks::<4>();
116    for group in groups {
117        let [a, b, c, d] = group;
118        let masks = [
119            mask::<true>(*a),
120            mask::<true>(*b),
121            mask::<true>(*c),
122            mask::<true>(*d),
123        ];
124        let Some(found) = NonZero::new(packed(masks)) else {
125            index += 4 * LANE;
126            continue;
127        };
128        let (offset, byte) = first(group, found);
129        return name_at(index + offset, byte);
130    }
131    for lane in lanes {
132        let bits = mask::<true>(*lane);
133        if bits != 0 {
134            let (offset, byte) = in_lane(lane, bits);
135            return name_at(index + offset, byte);
136        }
137        index += LANE;
138    }
139    if tail.is_empty() {
140        Outcome::Partial
141    } else {
142        name_tail(tail, index)
143    }
144}
145
146fn value_simd(bytes: &[u8], mut index: usize) -> Outcome<usize> {
147    let Some((lane, rest)) = bytes.split_first_chunk::<LANE>() else {
148        return value_tail(bytes, index);
149    };
150    let bits = mask::<false>(*lane);
151    if bits != 0 {
152        let (offset, byte) = in_lane(lane, bits);
153        return value_at(bytes, offset, index + offset, byte);
154    }
155    index += LANE;
156    let (lanes, tail) = rest.as_chunks::<LANE>();
157    let (groups, lanes) = lanes.as_chunks::<4>();
158    let mut consumed = LANE;
159    for group in groups {
160        let [a, b, c, d] = group;
161        let masks = [
162            mask::<false>(*a),
163            mask::<false>(*b),
164            mask::<false>(*c),
165            mask::<false>(*d),
166        ];
167        let Some(found) = NonZero::new(packed(masks)) else {
168            index += 4 * LANE;
169            consumed += 4 * LANE;
170            continue;
171        };
172        let (offset, byte) = first(group, found);
173        return value_at(bytes, consumed + offset, index + offset, byte);
174    }
175    for lane in lanes {
176        let bits = mask::<false>(*lane);
177        if bits != 0 {
178            let (offset, byte) = in_lane(lane, bits);
179            return value_at(bytes, consumed + offset, index + offset, byte);
180        }
181        index += LANE;
182        consumed += LANE;
183    }
184    if tail.is_empty() {
185        Outcome::Partial
186    } else {
187        value_tail(tail, index)
188    }
189}
190
191fn name_tail(bytes: &[u8], index: usize) -> Outcome<(usize, u8)> {
192    for (offset, &byte) in bytes.iter().enumerate() {
193        let pos = index + offset;
194        if byte == b':' || byte == b'\r' {
195            return Outcome::Found((pos, byte));
196        }
197        if !crate::field::Error::is_name_byte(byte) {
198            return Outcome::Invalid {
199                offset: pos,
200                actual: byte,
201            };
202        }
203    }
204    Outcome::Partial
205}
206
207fn value_tail(bytes: &[u8], index: usize) -> Outcome<usize> {
208    for (offset, &byte) in bytes.iter().enumerate() {
209        if byte == b'\r' {
210            return value_at(bytes, offset, index + offset, byte);
211        }
212        if !crate::field::Error::is_text(byte) {
213            return Outcome::Invalid {
214                offset: index + offset,
215                actual: byte,
216            };
217        }
218    }
219    Outcome::Partial
220}
221
222/// Lowest byte one nonzero lane mask selects inside that lane.
223///
224/// A lane mask carries exactly `LANE` bits, so its lowest set bit already names
225/// an in-lane index: the byte needs no second range check and no panic path.
226fn in_lane(lane: &[u8; LANE], bits: u16) -> (usize, u8) {
227    let offset = bits.trailing_zeros() as usize & (LANE - 1);
228    (offset, lane[offset])
229}
230
231/// Byte-ordered bits of the four lane masks of one group.
232fn packed(masks: [u16; 4]) -> u64 {
233    let mut bits = 0;
234    for (lane, mask) in masks.into_iter().enumerate() {
235        bits |= u64::from(mask) << (lane * LANE);
236    }
237    bits
238}
239
240/// Lowest byte one nonzero group mask selects.
241///
242/// The mask carries one bit per byte, so its lowest set bit names the byte
243/// without a second search or a panic path.
244fn first(group: &[[u8; LANE]; 4], found: NonZero<u64>) -> (usize, u8) {
245    let ordinal = found.get().trailing_zeros() as usize;
246    (ordinal, group[ordinal / LANE][ordinal % LANE])
247}
248
249fn mask<const NAME: bool>(lane: [u8; LANE]) -> u16 {
250    let flags = lane.map(|byte| {
251        let invalid = if NAME {
252            !crate::field::Error::is_name_byte(byte)
253        } else {
254            !crate::field::Error::is_text(byte)
255        };
256        u8::from(invalid) << 7
257    });
258    let mut bits = 0;
259    // Each byte is 0 or 0x80; packing preserves byte order without cross-byte carries.
260    for (index, chunk) in flags.as_chunks::<8>().0.iter().enumerate() {
261        let word = u64::from_le_bytes(*chunk);
262        bits |= ((word.wrapping_mul(0x0002_0408_1020_4081) >> 56) as u16) << (index * 8);
263    }
264    bits
265}
266
267fn name_at(pos: usize, byte: u8) -> Outcome<(usize, u8)> {
268    if byte == b':' || byte == b'\r' {
269        Outcome::Found((pos, byte))
270    } else {
271        Outcome::Invalid {
272            offset: pos,
273            actual: byte,
274        }
275    }
276}
277
278fn value_at(bytes: &[u8], offset: usize, pos: usize, byte: u8) -> Outcome<usize> {
279    if byte != b'\r' {
280        return Outcome::Invalid {
281            offset: pos,
282            actual: byte,
283        };
284    }
285    let Some(next) = bytes.get(offset + 1) else {
286        return Outcome::Partial;
287    };
288    if *next == b'\n' {
289        Outcome::Found(pos)
290    } else {
291        Outcome::Invalid {
292            offset: pos + 1,
293            actual: *next,
294        }
295    }
296}
297
298const _: () = {
299    let word = mem::size_of::<usize>();
300    assert!(mem::size_of::<Bytes<'_>>() == 2 * word);
301    assert!(mem::size_of::<Outcome<usize>>() == 2 * word);
302    assert!(mem::size_of::<Outcome<(usize, u8)>>() == 3 * word);
303    assert!(mem::size_of::<Match<'_>>() == 3 * word);
304    assert!(mem::size_of::<Option<Match<'_>>>() == 3 * word);
305};