xocomil 0.3.0

A lightweight, zero-allocation HTTP/1.1 request parser and response writer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! HTTP validation as an extension trait on `[u8]`.
//!
//! Provides RFC 7230 conformance checks for header names, header values,
//! and request targets. The forbidden-byte checks use SIMD on x86-64
//! (SSE2), aarch64 (NEON), and wasm32 (simd128), with a scalar fallback.

use crate::ascii::HttpChar;

/// Extension trait providing HTTP validation on byte slices.
///
/// All methods are pure predicates — they return `bool` so callers can
/// map failures to their own error types (`RequestError`, `io::Error`,
/// etc.).
pub trait HttpValidate {
    /// Returns `true` if every byte is a valid HTTP token character
    /// (RFC 7230 §3.2.6 `tchar`) and the slice is non-empty.
    fn is_valid_token(&self) -> bool;

    /// Returns `true` if the slice contains no forbidden header-value
    /// bytes: NUL (0x00), CR (0x0D), LF (0x0A).
    ///
    /// Uses SSE2 on x86-64 to scan 16 bytes at a time.
    fn is_valid_header_value(&self) -> bool;

    /// Returns `true` if the slice contains no control characters
    /// (0x00–0x1F, 0x7F). Used for request-target validation.
    ///
    /// **Note:** Space (`0x20`) is allowed by this method. In the request
    /// parser, the path is extracted by splitting on spaces first, so
    /// spaces never appear in the path slice. If you call this method on
    /// unsplit input, be aware that spaces will pass validation.
    ///
    /// **Note:** High bytes (0x80–0xFF) are permitted per RFC 7230, which
    /// treats request-targets as opaque octets. Callers that interpret
    /// the path as UTF-8 or apply percent-decoding should perform their
    /// own validation to prevent encoding-confusion attacks (e.g. overlong
    /// UTF-8 sequences being decoded as path separators).
    fn is_valid_request_target(&self) -> bool;

    /// Trim leading and trailing optional whitespace (SP / HTAB)
    /// per RFC 7230 §3.2.6.
    fn trim_ows(&self) -> &[u8];
}

// ---------------------------------------------------------------------------
// Shared bitmask-based implementation (SSE2 + wasm SIMD)
// ---------------------------------------------------------------------------

/// Generates `is_valid_header_value` and `is_valid_request_target` using a
/// bitmask SIMD strategy. Each call site defines `simd_splat!`, `simd_load!`,
/// `simd_cmpeq!`, `simd_or!`, `simd_bitmask!`, `simd_max_epu8!`, and
/// `simd_andnot!` helper macros that abstract over the architecture-specific
/// intrinsics before invoking this macro.
macro_rules! impl_bitmask_validate {
    () => {
        /// Safety: all SIMD loads stay within `buf[i..i+16]`
        /// where `i + 16 <= buf.len()`.
        #[inline]
        pub(super) fn is_valid_header_value(buf: &[u8]) -> bool {
            let len = buf.len();
            unsafe {
                let nul = simd_splat!(HttpChar::Null.as_u8());
                let cr = simd_splat!(HttpChar::CarriageReturn.as_u8());
                let lf = simd_splat!(HttpChar::LineFeed.as_u8());
                let mut i = 0;

                while i + 16 <= len {
                    let chunk = simd_load!(buf.as_ptr().add(i));
                    let bad = simd_or!(
                        simd_cmpeq!(chunk, nul),
                        simd_or!(simd_cmpeq!(chunk, cr), simd_cmpeq!(chunk, lf))
                    );
                    if simd_bitmask!(bad) != 0 {
                        return false;
                    }
                    i += 16;
                }

                while i < len {
                    let b = *buf.get_unchecked(i);
                    if b == HttpChar::Null
                        || b == HttpChar::CarriageReturn
                        || b == HttpChar::LineFeed
                    {
                        return false;
                    }
                    i += 1;
                }

                true
            }
        }

        #[inline]
        pub(super) fn is_valid_request_target(buf: &[u8]) -> bool {
            let len = buf.len();
            unsafe {
                let min_valid = simd_splat!(HttpChar::Space.as_u8());
                let del = simd_splat!(HttpChar::Delete.as_u8());
                let mut i = 0;

                while i + 16 <= len {
                    let chunk = simd_load!(buf.as_ptr().add(i));
                    let not_ctrl = simd_cmpeq!(simd_max_epu8!(chunk, min_valid), chunk);
                    let is_del = simd_cmpeq!(chunk, del);
                    let good = simd_andnot!(is_del, not_ctrl);
                    if simd_bitmask!(good) != 0xFFFF {
                        return false;
                    }
                    i += 16;
                }

                while i < len {
                    let b = *buf.get_unchecked(i);
                    if b <= 0x1F || b == HttpChar::Delete {
                        return false;
                    }
                    i += 1;
                }

                true
            }
        }
    };
}

// ---------------------------------------------------------------------------
// Architecture-specific helpers
// ---------------------------------------------------------------------------

#[cfg(target_arch = "x86_64")]
#[allow(
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::cast_ptr_alignment
)]
mod sse2 {
    crate::simd::define_simd_primitives!();

    use crate::ascii::HttpChar;

    impl_bitmask_validate!();
}

#[cfg(target_arch = "aarch64")]
mod neon {
    use std::arch::aarch64::{
        vbicq_u8, vceqq_u8, vcgeq_u8, vdupq_n_u8, vld1q_u8, vmaxvq_u8, vminvq_u8, vorrq_u8,
    };

    use crate::ascii::HttpChar;

    /// Safety: NEON is guaranteed on all aarch64 processors.
    /// All loads stay within `buf[i..i+16]` where `i + 16 <= buf.len()`.
    #[inline]
    pub(super) fn is_valid_header_value(buf: &[u8]) -> bool {
        let len = buf.len();
        unsafe {
            let nul = vdupq_n_u8(HttpChar::Null.as_u8());
            let cr = vdupq_n_u8(HttpChar::CarriageReturn.as_u8());
            let lf = vdupq_n_u8(HttpChar::LineFeed.as_u8());
            let mut i = 0;

            while i + 16 <= len {
                let chunk = vld1q_u8(buf.as_ptr().add(i));
                let bad = vorrq_u8(
                    vceqq_u8(chunk, nul),
                    vorrq_u8(vceqq_u8(chunk, cr), vceqq_u8(chunk, lf)),
                );
                if vmaxvq_u8(bad) != 0 {
                    return false;
                }
                i += 16;
            }

            while i < len {
                let b = *buf.get_unchecked(i);
                if b == HttpChar::Null || b == HttpChar::CarriageReturn || b == HttpChar::LineFeed {
                    return false;
                }
                i += 1;
            }

            true
        }
    }

    #[inline]
    pub(super) fn is_valid_request_target(buf: &[u8]) -> bool {
        let len = buf.len();
        unsafe {
            let min_valid = vdupq_n_u8(HttpChar::Space.as_u8());
            let del = vdupq_n_u8(HttpChar::Delete.as_u8());
            let mut i = 0;

            while i + 16 <= len {
                let chunk = vld1q_u8(buf.as_ptr().add(i));
                let not_ctrl = vcgeq_u8(chunk, min_valid);
                let is_del = vceqq_u8(chunk, del);
                let good = vbicq_u8(not_ctrl, is_del);
                if vminvq_u8(good) == 0 {
                    return false;
                }
                i += 16;
            }

            while i < len {
                let b = *buf.get_unchecked(i);
                if b <= 0x1F || b == HttpChar::Delete {
                    return false;
                }
                i += 1;
            }

            true
        }
    }
}

#[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
#[allow(clippy::cast_sign_loss)]
mod wasm_simd {
    crate::simd::define_simd_primitives!();

    use crate::ascii::HttpChar;

    impl_bitmask_validate!();
}

#[cfg(not(any(
    target_arch = "x86_64",
    target_arch = "aarch64",
    all(target_arch = "wasm32", target_feature = "simd128")
)))]
mod scalar {
    use crate::ascii::HttpChar;

    #[inline]
    pub(super) fn is_valid_header_value(buf: &[u8]) -> bool {
        buf.iter().all(|&b| {
            b != HttpChar::Null && b != HttpChar::CarriageReturn && b != HttpChar::LineFeed
        })
    }

    #[inline]
    pub(super) fn is_valid_request_target(buf: &[u8]) -> bool {
        buf.iter().all(|&b| b > 0x1F && b != HttpChar::Delete)
    }
}

// ---------------------------------------------------------------------------
// Dispatch
// ---------------------------------------------------------------------------

/// Select the best implementation for the current target.
macro_rules! dispatch {
    ($fn_name:ident $(, $arg:expr)* $(,)?) => {{
        #[cfg(target_arch = "x86_64")]
        { sse2::$fn_name($($arg),*) }
        #[cfg(target_arch = "aarch64")]
        { neon::$fn_name($($arg),*) }
        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
        { wasm_simd::$fn_name($($arg),*) }
        #[cfg(not(any(
            target_arch = "x86_64",
            target_arch = "aarch64",
            all(target_arch = "wasm32", target_feature = "simd128")
        )))]
        { scalar::$fn_name($($arg),*) }
    }};
}

/// SSSE3 trampoline for `Ssse3::is_valid_token`. The
/// `#[target_feature(enable = "ssse3")]` lets the compiler inline
/// `pshufb` from `Ssse3::all16` into the per-chunk SIMD loop.
///
/// # Safety
///
/// Caller must ensure the host supports SSSE3.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "ssse3")]
#[inline]
unsafe fn is_valid_token_ssse3(buf: &[u8]) -> bool {
    use crate::tchar::{Ssse3, TcharCheck};
    <Ssse3 as TcharCheck>::is_valid_token(buf)
}

/// AVX2 token validator using 32-byte chunks. Falls back to the SSSE3
/// path for the tail (16-byte chunk + scalar bytes) so the average
/// header name doesn't pay 32-byte alignment cost.
///
/// # Safety
///
/// Caller must ensure the host supports AVX2.
/// Inline 16-byte TCHAR validator using SSE/SSSE3 intrinsics directly.
///
/// Lives inside the AVX2 token validator's compilation unit so the
/// `target_feature(enable = "avx2")` attribute on the caller carries
/// through to these instructions and they inline into the loop instead
/// of calling out to `Ssse3::all16` across a function boundary.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
#[inline]
unsafe fn tchar_all16_inline(ptr: *const u8) -> bool {
    use std::arch::x86_64::{
        _mm_and_si128, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_set1_epi8,
        _mm_setzero_si128, _mm_shuffle_epi8, _mm_srli_epi16,
    };

    // Safety: caller guarantees `ptr` is valid for 16 bytes.
    // AVX2 is enabled here, which strictly implies SSSE3 (and SSE2).
    unsafe {
        // Pull the nibble tables from the single source of truth in
        // `crate::tchar`. Kept as locals so the compiler still has the
        // option to fold them into rip-relative loads alongside the
        // surrounding AVX2 code (same codegen as the previous duplicated
        // literals, but without the divergence risk).
        let lo_tbl_arr: [u8; 16] = crate::tchar::LO_NIBBLES;
        let hi_tbl_arr: [u8; 16] = crate::tchar::HI_NIBBLES;

        let chunk = _mm_loadu_si128(ptr.cast());
        let lo_tbl = _mm_loadu_si128(lo_tbl_arr.as_ptr().cast());
        let hi_tbl = _mm_loadu_si128(hi_tbl_arr.as_ptr().cast());
        let nibble_mask = _mm_set1_epi8(0x0F);

        let lo_nib = _mm_and_si128(chunk, nibble_mask);
        let hi_nib = _mm_and_si128(_mm_srli_epi16(chunk, 4), nibble_mask);
        let lo_shuf = _mm_shuffle_epi8(lo_tbl, lo_nib);
        let hi_shuf = _mm_shuffle_epi8(hi_tbl, hi_nib);
        let valid = _mm_and_si128(lo_shuf, hi_shuf);

        let invalid = _mm_cmpeq_epi8(valid, _mm_setzero_si128());
        _mm_movemask_epi8(invalid) == 0
    }
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
#[inline]
unsafe fn is_valid_token_avx2(buf: &[u8]) -> bool {
    use crate::tchar::{Avx2, TABLE};

    let len = buf.len();
    if len == 0 {
        return false;
    }
    let ptr = buf.as_ptr();
    let mut i = 0;
    // 32-byte AVX2 chunks.
    while i + 32 <= len {
        // Safety: i + 32 <= len.
        if unsafe { Avx2::mask32(ptr.add(i)) } != 0xFFFF_FFFF {
            return false;
        }
        i += 32;
    }
    // 16-byte chunk for the tail — inlined SSE2/SSSE3 instructions
    // rather than a cross-function call to `Ssse3::all16`.
    if i + 16 <= len {
        // Safety: i + 16 <= len; AVX2 implies SSE2 + SSSE3.
        if unsafe { !tchar_all16_inline(ptr.add(i)) } {
            return false;
        }
        i += 16;
    }
    // Scalar bytes for the final remainder (< 16 bytes).
    while i < len {
        if !TABLE[buf[i] as usize] {
            return false;
        }
        i += 1;
    }
    true
}

impl HttpValidate for [u8] {
    #[inline]
    fn is_valid_token(&self) -> bool {
        #[cfg(target_arch = "x86_64")]
        {
            use crate::tchar::{Sse2Only, TcharCheck, has_avx2, has_ssse3};
            // Runtime AVX2 → SSSE3 → SSE2 dispatch — same ladder as
            // scan.rs. Each tier calls into a `#[target_feature]`-
            // attributed trampoline so the SIMD intrinsics inline into
            // the per-chunk loop.
            if has_avx2() {
                // Safety: AVX2 confirmed available.
                unsafe { is_valid_token_avx2(self) }
            } else if has_ssse3() {
                // Safety: SSSE3 confirmed available.
                unsafe { is_valid_token_ssse3(self) }
            } else {
                <Sse2Only as TcharCheck>::is_valid_token(self)
            }
        }
        #[cfg(not(target_arch = "x86_64"))]
        {
            use crate::tchar::{Arch, TcharCheck};
            Arch::is_valid_token(self)
        }
    }

    #[inline]
    fn is_valid_header_value(&self) -> bool {
        dispatch!(is_valid_header_value, self)
    }

    #[inline]
    fn is_valid_request_target(&self) -> bool {
        dispatch!(is_valid_request_target, self)
    }

    #[inline]
    fn trim_ows(&self) -> &[u8] {
        let len = self.len();
        if len == 0 {
            return self;
        }

        // Fast path: most header values start with a non-OWS byte
        // (the colon is immediately followed by the value).
        let first = self[0];
        let last = self[len - 1];
        let first_ok = first != HttpChar::Space && first != HttpChar::HorizontalTab;
        let last_ok = last != HttpChar::Space && last != HttpChar::HorizontalTab;
        if first_ok && last_ok {
            return self;
        }

        // Slow path: scan from the edges.
        let mut start = 0;
        while start < len {
            if self[start] != HttpChar::Space && self[start] != HttpChar::HorizontalTab {
                break;
            }
            start += 1;
        }
        let mut end = len;
        while end > start {
            if self[end - 1] != HttpChar::Space && self[end - 1] != HttpChar::HorizontalTab {
                break;
            }
            end -= 1;
        }
        &self[start..end]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // -----------------------------------------------------------------------
    // is_valid_token
    // -----------------------------------------------------------------------

    #[test]
    fn valid_token_alpha() {
        assert!(b"Host".is_valid_token());
        assert!(b"Content-Type".is_valid_token());
        assert!(b"X-My_Header.v2".is_valid_token());
    }

    #[test]
    fn valid_token_special_tchars() {
        assert!(b"!#$%&'*+-.^_`|~".is_valid_token());
    }

    #[test]
    fn invalid_token_empty() {
        assert!(!b"".is_valid_token());
    }

    #[test]
    fn invalid_token_space() {
        assert!(!b"Bad Name".is_valid_token());
    }

    #[test]
    fn invalid_token_control_char() {
        assert!(!b"Bad\x01Name".is_valid_token());
    }

    #[test]
    fn invalid_token_colon() {
        assert!(!b"Name:Value".is_valid_token());
    }

    #[test]
    fn invalid_token_crlf() {
        assert!(!b"Bad\r\nName".is_valid_token());
    }

    // -----------------------------------------------------------------------
    // is_valid_header_value
    // -----------------------------------------------------------------------

    #[test]
    fn valid_value_printable() {
        assert!(b"text/html; charset=utf-8".is_valid_header_value());
    }

    #[test]
    fn valid_value_empty() {
        assert!(b"".is_valid_header_value());
    }

    #[test]
    fn valid_value_high_bytes() {
        assert!([0x80u8, 0xFF, 0xFE].as_slice().is_valid_header_value());
    }

    #[test]
    fn invalid_value_nul() {
        assert!(!b"bad\x00value".is_valid_header_value());
    }

    #[test]
    fn invalid_value_cr() {
        assert!(!b"bad\rvalue".is_valid_header_value());
    }

    #[test]
    fn invalid_value_lf() {
        assert!(!b"bad\nvalue".is_valid_header_value());
    }

    #[test]
    fn invalid_value_crlf_injection() {
        assert!(!b"text/html\r\nX-Injected: evil".is_valid_header_value());
    }

    #[test]
    fn value_validation_simd_boundary() {
        // Exactly 16 bytes, forbidden byte at each position
        for pos in 0..16 {
            let mut buf = [b'a'; 16];
            buf[pos] = 0;
            assert!(!buf.as_slice().is_valid_header_value());
        }
        // 17 bytes — scalar tail handles the last byte
        let mut buf = [b'a'; 17];
        buf[16] = b'\r';
        assert!(!buf.as_slice().is_valid_header_value());
    }

    // -----------------------------------------------------------------------
    // is_valid_request_target
    // -----------------------------------------------------------------------

    #[test]
    fn valid_target_path() {
        assert!(b"/index.html".is_valid_request_target());
        assert!(b"/search?q=hello&lang=en".is_valid_request_target());
        assert!(b"/page#section".is_valid_request_target());
        assert!(b"/hello%20world".is_valid_request_target());
    }

    #[test]
    fn valid_target_high_bytes() {
        assert!([b'/', 0xFF, 0xFE].as_slice().is_valid_request_target());
    }

    #[test]
    fn invalid_target_nul() {
        assert!(!b"/file.txt\x00.jpg".is_valid_request_target());
    }

    #[test]
    fn invalid_target_control_chars() {
        for c in 0x00..=0x1F {
            let buf = [b'/', c];
            assert!(!buf.as_slice().is_valid_request_target(), "byte {c:#04x}");
        }
        assert!(!b"/path\x7F".is_valid_request_target());
    }

    // -----------------------------------------------------------------------
    // trim_ows
    // -----------------------------------------------------------------------

    #[test]
    fn trim_ows_leading() {
        assert_eq!(b"  value".trim_ows(), b"value");
    }

    #[test]
    fn trim_ows_trailing() {
        assert_eq!(b"value  ".trim_ows(), b"value");
    }

    #[test]
    fn trim_ows_both() {
        assert_eq!(b" \t value \t ".trim_ows(), b"value");
    }

    #[test]
    fn trim_ows_empty() {
        assert_eq!(b"".trim_ows(), b"");
    }

    #[test]
    fn trim_ows_only_whitespace() {
        assert_eq!(b"   ".trim_ows(), b"");
    }

    #[test]
    fn trim_ows_no_whitespace() {
        assert_eq!(b"value".trim_ows(), b"value");
    }

    #[test]
    fn trim_ows_tabs() {
        assert_eq!(b"\t\tvalue\t".trim_ows(), b"value");
    }
}