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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
//! HTTP header name types and the [`HeaderName`] trait.
//!
//! Provides type-safe header enums ([`RequestHeader`], [`ResponseHeader`])
//! and the generic [`HeaderName`] trait that unifies enum and `&str` lookups.

use std::fmt;

/// Trait for types that can be used as an HTTP header name.
///
/// Implemented for [`RequestHeader`], [`ResponseHeader`], and `&str`,
/// enabling both type-safe and dynamic header lookups with zero overhead.
///
/// The lifetime parameter ensures that enum variants (which return
/// `&'static str`) and string slices both work correctly when the
/// name needs to be stored.
///
/// This trait is **sealed** — it cannot be implemented outside this crate.
pub trait HeaderName<'name>: Copy + private::Sealed {
    /// Return the header name as bytes.
    fn as_header_bytes(self) -> &'name [u8];

    /// Return the header name as a string slice.
    fn as_header_str(self) -> &'name str;

    /// If this name is a known header enum variant, return its index
    /// into a fixed-size slot table for O(1) lookup. Returns `None`
    /// for dynamic `&str` names.
    #[inline]
    fn known_index(self) -> Option<usize> {
        None
    }
}

mod private {
    pub trait Sealed {}
    impl Sealed for &str {}
    impl Sealed for super::RequestHeader {}
    impl Sealed for super::ResponseHeader {}
}

impl<'name> HeaderName<'name> for &'name str {
    #[inline]
    fn as_header_bytes(self) -> &'name [u8] {
        self.as_bytes()
    }

    #[inline]
    fn as_header_str(self) -> &'name str {
        self
    }
}

impl<'name> HeaderName<'name> for RequestHeader {
    #[inline]
    fn as_header_bytes(self) -> &'name [u8] {
        self.as_bytes()
    }

    #[inline]
    fn as_header_str(self) -> &'name str {
        self.as_str()
    }

    #[inline]
    fn known_index(self) -> Option<usize> {
        Some(self as usize)
    }
}

impl<'name> HeaderName<'name> for ResponseHeader {
    #[inline]
    fn as_header_bytes(self) -> &'name [u8] {
        self.as_bytes()
    }

    #[inline]
    fn as_header_str(self) -> &'name str {
        self.as_str()
    }

    #[inline]
    fn known_index(self) -> Option<usize> {
        Some(self as usize)
    }
}

// ---------------------------------------------------------------------------
// Header (name-value pair)
// ---------------------------------------------------------------------------

/// A single HTTP header: a name-value pair of byte slices.
///
/// This is the zero-copy representation used by both [`crate::request::Request`]
/// and [`crate::response::Response`]. Both fields borrow from the
/// underlying buffer.
#[derive(Clone, Copy, Debug)]
pub struct Header<'a> {
    name: &'a [u8],
    value: &'a [u8],
}

impl<'a> Header<'a> {
    /// Sentinel value used to fill unused header slots in fixed-size arrays.
    pub(crate) const EMPTY: Self = Self {
        name: b"",
        value: b"",
    };

    /// Create a new header from raw byte slices.
    #[inline]
    pub(crate) const fn new(name: &'a [u8], value: &'a [u8]) -> Self {
        Self { name, value }
    }

    /// The header name as raw bytes.
    #[inline]
    #[must_use]
    pub const fn name(&self) -> &'a [u8] {
        self.name
    }

    /// The header value as raw bytes.
    #[inline]
    #[must_use]
    pub const fn value(&self) -> &'a [u8] {
        self.value
    }

    /// The header name as a UTF-8 string.
    ///
    /// # Errors
    ///
    /// Returns `Utf8Error` if the name is not valid UTF-8.
    #[inline]
    pub const fn name_str(&self) -> Result<&'a str, std::str::Utf8Error> {
        std::str::from_utf8(self.name)
    }

    /// The header value as a UTF-8 string.
    ///
    /// # Errors
    ///
    /// Returns `Utf8Error` if the value is not valid UTF-8.
    #[inline]
    pub const fn value_str(&self) -> Result<&'a str, std::str::Utf8Error> {
        std::str::from_utf8(self.value)
    }
}

// ---------------------------------------------------------------------------
// Method
// ---------------------------------------------------------------------------

/// HTTP request method.
///
/// The enum exists so that the type system enforces method validation at
/// parse time — a `Method` value is proof that the raw bytes were a
/// recognised method.
///
/// CONNECT and TRACE are intentionally **not** included:
///
/// - **TRACE** enables cross-site tracing (XST) attacks — an attacker
///   can steal `Authorization` / `Cookie` values reflected in the
///   response body. Most production servers disable it.
/// - **CONNECT** requests proxy tunneling, which changes the connection
///   semantics entirely (the server becomes a TCP relay) and is out of
///   scope for a request parser.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Method {
    Get,
    Head,
    Post,
    Put,
    Delete,
    Patch,
    Options,
}

impl Method {
    /// The method as its canonical HTTP string.
    #[inline]
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Get => "GET",
            Self::Head => "HEAD",
            Self::Post => "POST",
            Self::Put => "PUT",
            Self::Delete => "DELETE",
            Self::Patch => "PATCH",
            Self::Options => "OPTIONS",
        }
    }

    /// Returns `true` if the method can carry a request body.
    ///
    /// Only GET and HEAD are truly bodyless — the remaining methods
    /// (POST, PUT, PATCH, DELETE, OPTIONS) may carry a body per RFC 7231.
    #[inline]
    #[must_use]
    pub const fn can_have_body(self) -> bool {
        !matches!(self, Self::Get | Self::Head)
    }

    /// Try to parse a method from raw bytes.
    #[inline]
    pub(crate) const fn from_bytes(bytes: &[u8]) -> Option<Self> {
        match bytes {
            b"GET" => Some(Self::Get),
            b"HEAD" => Some(Self::Head),
            b"POST" => Some(Self::Post),
            b"PUT" => Some(Self::Put),
            b"DELETE" => Some(Self::Delete),
            b"PATCH" => Some(Self::Patch),
            b"OPTIONS" => Some(Self::Options),
            _ => None,
        }
    }
}

impl fmt::Display for Method {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

// ---------------------------------------------------------------------------
// HttpVersion
// ---------------------------------------------------------------------------

/// HTTP protocol version.
///
/// A parsed `HttpVersion` is proof that the request line contained a
/// recognised version string. Only HTTP/1.0 and HTTP/1.1 are accepted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HttpVersion {
    Http10,
    Http11,
}

impl HttpVersion {
    /// The version as its canonical HTTP string (e.g. `"HTTP/1.1"`).
    #[inline]
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Http10 => "HTTP/1.0",
            Self::Http11 => "HTTP/1.1",
        }
    }

    /// Try to parse a version from raw bytes.
    #[inline]
    pub(crate) const fn from_bytes(bytes: &[u8]) -> Option<Self> {
        match bytes {
            b"HTTP/1.0" => Some(Self::Http10),
            b"HTTP/1.1" => Some(Self::Http11),
            _ => None,
        }
    }
}

impl fmt::Display for HttpVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

// ---------------------------------------------------------------------------
// Request headers
// ---------------------------------------------------------------------------

/// Standard HTTP request header names.
///
/// Use with [`crate::request::Request::header`] for type-safe, zero-cost lookups.
/// Each variant maps to its canonical HTTP header string via [`as_str`](Self::as_str).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RequestHeader {
    Host,
    Accept,
    AcceptEncoding,
    AcceptLanguage,
    Authorization,
    CacheControl,
    Connection,
    ContentType,
    ContentLength,
    Cookie,
    IfNoneMatch,
    IfModifiedSince,
    Origin,
    Referer,
    UserAgent,
    TransferEncoding,
    Upgrade,
    UpgradeInsecureRequests,
}

impl RequestHeader {
    /// Total number of variants — used to size the O(1) lookup table.
    pub(crate) const COUNT: usize = 18;

    // Compile-time check: if you add a variant, update COUNT.
    const _ASSERT_COUNT: () = assert!(Self::UpgradeInsecureRequests as usize + 1 == Self::COUNT);

    /// Case-fold a `u32` (4 ASCII bytes) by OR-ing with 0x20 on each lane.
    #[inline]
    const fn fold32(v: u32) -> u32 {
        v | 0x2020_2020
    }

    /// Case-fold a `u64` (8 ASCII bytes) by OR-ing with 0x20 on each lane.
    #[inline]
    const fn fold64(v: u64) -> u64 {
        v | 0x2020_2020_2020_2020
    }

    /// Load 4 bytes at `offset` as a native-endian `u32`.
    #[inline]
    const fn load32(bytes: &[u8], off: usize) -> u32 {
        (bytes[off] as u32)
            | (bytes[off + 1] as u32) << 8
            | (bytes[off + 2] as u32) << 16
            | (bytes[off + 3] as u32) << 24
    }

    /// Load 8 bytes at `offset` as a native-endian `u64`.
    #[inline]
    const fn load64(bytes: &[u8], off: usize) -> u64 {
        (bytes[off] as u64)
            | (bytes[off + 1] as u64) << 8
            | (bytes[off + 2] as u64) << 16
            | (bytes[off + 3] as u64) << 24
            | (bytes[off + 4] as u64) << 32
            | (bytes[off + 5] as u64) << 40
            | (bytes[off + 6] as u64) << 48
            | (bytes[off + 7] as u64) << 56
    }

    /// Compile-time LE `u32` from 4 ASCII bytes (must be lowercase).
    #[inline]
    const fn const32(b: &[u8]) -> u32 {
        (b[0] as u32) | (b[1] as u32) << 8 | (b[2] as u32) << 16 | (b[3] as u32) << 24
    }

    /// Compile-time LE `u64` from 8 ASCII bytes (must be lowercase).
    #[inline]
    const fn const64(b: &[u8]) -> u64 {
        (b[0] as u64)
            | (b[1] as u64) << 8
            | (b[2] as u64) << 16
            | (b[3] as u64) << 24
            | (b[4] as u64) << 32
            | (b[5] as u64) << 40
            | (b[6] as u64) << 48
            | (b[7] as u64) << 56
    }

    /// Case-insensitive 4-byte match.
    #[inline]
    const fn eq4(input: &[u8], off: usize, expected: &[u8]) -> bool {
        Self::fold32(Self::load32(input, off)) == Self::const32(expected)
    }

    /// Case-insensitive 6-byte match (u32 + u16 tail).
    #[inline]
    const fn eq6(input: &[u8], expected: &[u8]) -> bool {
        Self::eq4(
            input,
            0,
            &[expected[0], expected[1], expected[2], expected[3]],
        ) && (input[4] | 0x20) == expected[4]
            && (input[5] | 0x20) == expected[5]
    }

    /// Case-insensitive 7-byte match (u32 + 3 tail bytes).
    #[inline]
    const fn eq7(input: &[u8], expected: &[u8]) -> bool {
        Self::eq4(
            input,
            0,
            &[expected[0], expected[1], expected[2], expected[3]],
        ) && (input[4] | 0x20) == expected[4]
            && (input[5] | 0x20) == expected[5]
            && (input[6] | 0x20) == expected[6]
    }

    /// Case-insensitive 8-byte match.
    #[inline]
    const fn eq8(input: &[u8], off: usize, expected: &[u8]) -> bool {
        Self::fold64(Self::load64(input, off)) == Self::const64(expected)
    }

    /// Case-insensitive 10-byte match (u64 + u16 tail).
    #[inline]
    const fn eq10(input: &[u8], expected: &[u8]) -> bool {
        Self::eq8(
            input,
            0,
            &[
                expected[0],
                expected[1],
                expected[2],
                expected[3],
                expected[4],
                expected[5],
                expected[6],
                expected[7],
            ],
        ) && (input[8] | 0x20) == expected[8]
            && (input[9] | 0x20) == expected[9]
    }

    /// Case-insensitive 12-byte match (u64 + u32).
    #[inline]
    const fn eq12(input: &[u8], expected: &[u8]) -> bool {
        Self::eq8(
            input,
            0,
            &[
                expected[0],
                expected[1],
                expected[2],
                expected[3],
                expected[4],
                expected[5],
                expected[6],
                expected[7],
            ],
        ) && Self::eq4(
            input,
            8,
            &[expected[8], expected[9], expected[10], expected[11]],
        )
    }

    /// Case-insensitive 13-byte match (u64 + u32 + 1 tail).
    #[inline]
    const fn eq13(input: &[u8], expected: &[u8]) -> bool {
        Self::eq12(input, expected) && (input[12] | 0x20) == expected[12]
    }

    /// Case-insensitive 14-byte match (u64 + u32 + 2 tail).
    #[inline]
    const fn eq14(input: &[u8], expected: &[u8]) -> bool {
        Self::eq12(input, expected)
            && (input[12] | 0x20) == expected[12]
            && (input[13] | 0x20) == expected[13]
    }

    /// Case-insensitive 15-byte match (u64 + u64 overlapping at byte 7).
    #[inline]
    const fn eq15(input: &[u8], expected: &[u8]) -> bool {
        Self::eq8(
            input,
            0,
            &[
                expected[0],
                expected[1],
                expected[2],
                expected[3],
                expected[4],
                expected[5],
                expected[6],
                expected[7],
            ],
        ) && Self::eq8(
            input,
            7,
            &[
                expected[7],
                expected[8],
                expected[9],
                expected[10],
                expected[11],
                expected[12],
                expected[13],
                expected[14],
            ],
        )
    }

    /// Case-insensitive 17-byte match (u64 + u64 + 1 tail).
    #[inline]
    const fn eq17(input: &[u8], expected: &[u8]) -> bool {
        Self::eq8(
            input,
            0,
            &[
                expected[0],
                expected[1],
                expected[2],
                expected[3],
                expected[4],
                expected[5],
                expected[6],
                expected[7],
            ],
        ) && Self::eq8(
            input,
            8,
            &[
                expected[8],
                expected[9],
                expected[10],
                expected[11],
                expected[12],
                expected[13],
                expected[14],
                expected[15],
            ],
        ) && (input[16] | 0x20) == expected[16]
    }

    /// Case-insensitive 25-byte match (u64 + u64 + u64 + 1 tail).
    #[inline]
    const fn eq25(input: &[u8], expected: &[u8]) -> bool {
        Self::eq8(
            input,
            0,
            &[
                expected[0],
                expected[1],
                expected[2],
                expected[3],
                expected[4],
                expected[5],
                expected[6],
                expected[7],
            ],
        ) && Self::eq8(
            input,
            8,
            &[
                expected[8],
                expected[9],
                expected[10],
                expected[11],
                expected[12],
                expected[13],
                expected[14],
                expected[15],
            ],
        ) && Self::eq8(
            input,
            16,
            &[
                expected[16],
                expected[17],
                expected[18],
                expected[19],
                expected[20],
                expected[21],
                expected[22],
                expected[23],
            ],
        ) && (input[24] | 0x20) == expected[24]
    }

    /// Try to match raw header-name bytes (case-insensitive) to a known
    /// variant. Used during parsing to populate the O(1) lookup table.
    ///
    /// Uses length + first-byte dispatch to avoid full comparisons for
    /// non-matching headers, and word-sized OR-0x20 for the final check.
    #[inline]
    pub(crate) const fn from_bytes_ignore_case(bytes: &[u8]) -> Option<Self> {
        match bytes.len() {
            4 => {
                if Self::eq4(bytes, 0, b"host") {
                    return Some(Self::Host);
                }
                None
            }
            6 => match bytes[0] | 0x20 {
                b'a' if Self::eq6(bytes, b"accept") => Some(Self::Accept),
                b'c' if Self::eq6(bytes, b"cookie") => Some(Self::Cookie),
                b'o' if Self::eq6(bytes, b"origin") => Some(Self::Origin),
                _ => None,
            },
            7 => match bytes[0] | 0x20 {
                b'r' if Self::eq7(bytes, b"referer") => Some(Self::Referer),
                b'u' if Self::eq7(bytes, b"upgrade") => Some(Self::Upgrade),
                _ => None,
            },
            10 => match bytes[0] | 0x20 {
                b'c' if Self::eq10(bytes, b"connection") => Some(Self::Connection),
                b'u' if Self::eq10(bytes, b"user-agent") => Some(Self::UserAgent),
                _ => None,
            },
            12 => {
                if Self::eq12(bytes, b"content-type") {
                    return Some(Self::ContentType);
                }
                None
            }
            13 => match bytes[0] | 0x20 {
                b'a' if Self::eq13(bytes, b"authorization") => Some(Self::Authorization),
                b'c' if Self::eq13(bytes, b"cache-control") => Some(Self::CacheControl),
                b'i' if Self::eq13(bytes, b"if-none-match") => Some(Self::IfNoneMatch),
                _ => None,
            },
            14 => {
                if Self::eq14(bytes, b"content-length") {
                    return Some(Self::ContentLength);
                }
                None
            }
            15 => {
                // Accept-Encoding and Accept-Language share first byte;
                // discriminate on byte 7 ('e' vs 'l').
                if bytes[0] | 0x20 != b'a' {
                    return None;
                }
                match bytes[7] | 0x20 {
                    b'e' if Self::eq15(bytes, b"accept-encoding") => Some(Self::AcceptEncoding),
                    b'l' if Self::eq15(bytes, b"accept-language") => Some(Self::AcceptLanguage),
                    _ => None,
                }
            }
            17 => match bytes[0] | 0x20 {
                b'i' if Self::eq17(bytes, b"if-modified-since") => Some(Self::IfModifiedSince),
                b't' if Self::eq17(bytes, b"transfer-encoding") => Some(Self::TransferEncoding),
                _ => None,
            },
            25 => {
                if Self::eq25(bytes, b"upgrade-insecure-requests") {
                    return Some(Self::UpgradeInsecureRequests);
                }
                None
            }
            _ => None,
        }
    }

    #[inline]
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Host => "Host",
            Self::Accept => "Accept",
            Self::AcceptEncoding => "Accept-Encoding",
            Self::AcceptLanguage => "Accept-Language",
            Self::Authorization => "Authorization",
            Self::CacheControl => "Cache-Control",
            Self::Connection => "Connection",
            Self::ContentType => "Content-Type",
            Self::ContentLength => "Content-Length",
            Self::Cookie => "Cookie",
            Self::IfNoneMatch => "If-None-Match",
            Self::IfModifiedSince => "If-Modified-Since",
            Self::Origin => "Origin",
            Self::Referer => "Referer",
            Self::UserAgent => "User-Agent",
            Self::TransferEncoding => "Transfer-Encoding",
            Self::Upgrade => "Upgrade",
            Self::UpgradeInsecureRequests => "Upgrade-Insecure-Requests",
        }
    }

    #[inline]
    #[must_use]
    pub const fn as_bytes(&self) -> &'static [u8] {
        match self {
            Self::Host => b"Host",
            Self::Accept => b"Accept",
            Self::AcceptEncoding => b"Accept-Encoding",
            Self::AcceptLanguage => b"Accept-Language",
            Self::Authorization => b"Authorization",
            Self::CacheControl => b"Cache-Control",
            Self::Connection => b"Connection",
            Self::ContentType => b"Content-Type",
            Self::ContentLength => b"Content-Length",
            Self::Cookie => b"Cookie",
            Self::IfNoneMatch => b"If-None-Match",
            Self::IfModifiedSince => b"If-Modified-Since",
            Self::Origin => b"Origin",
            Self::Referer => b"Referer",
            Self::UserAgent => b"User-Agent",
            Self::TransferEncoding => b"Transfer-Encoding",
            Self::Upgrade => b"Upgrade",
            Self::UpgradeInsecureRequests => b"Upgrade-Insecure-Requests",
        }
    }
}

// ---------------------------------------------------------------------------
// Response headers
// ---------------------------------------------------------------------------

/// Standard HTTP response header names.
///
/// Use with [`crate::response::Response::header`] via [`as_str`](Self::as_str),
/// or pass raw `&str` for non-standard headers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseHeader {
    ContentType,
    ContentLength,
    CacheControl,
    Connection,
    Date,
    Location,
    SetCookie,
    Vary,
    ETag,
    LastModified,
    Allow,
    Server,
    AccessControlAllowOrigin,
}

impl ResponseHeader {
    /// Total number of variants — used to size O(1) lookup tables.
    #[allow(dead_code)]
    pub(crate) const COUNT: usize = 13;

    // Compile-time check: if you add a variant, update COUNT.
    #[allow(dead_code)]
    const _ASSERT_COUNT: () = assert!(Self::AccessControlAllowOrigin as usize + 1 == Self::COUNT);

    #[inline]
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ContentType => "Content-Type",
            Self::ContentLength => "Content-Length",
            Self::CacheControl => "Cache-Control",
            Self::Connection => "Connection",
            Self::Date => "Date",
            Self::Location => "Location",
            Self::SetCookie => "Set-Cookie",
            Self::Vary => "Vary",
            Self::ETag => "ETag",
            Self::LastModified => "Last-Modified",
            Self::Allow => "Allow",
            Self::Server => "Server",
            Self::AccessControlAllowOrigin => "Access-Control-Allow-Origin",
        }
    }

    #[inline]
    #[must_use]
    pub const fn as_bytes(&self) -> &'static [u8] {
        match self {
            Self::ContentType => b"Content-Type",
            Self::ContentLength => b"Content-Length",
            Self::CacheControl => b"Cache-Control",
            Self::Connection => b"Connection",
            Self::Date => b"Date",
            Self::Location => b"Location",
            Self::SetCookie => b"Set-Cookie",
            Self::Vary => b"Vary",
            Self::ETag => b"ETag",
            Self::LastModified => b"Last-Modified",
            Self::Allow => b"Allow",
            Self::Server => b"Server",
            Self::AccessControlAllowOrigin => b"Access-Control-Allow-Origin",
        }
    }
}

// ---------------------------------------------------------------------------
// Status codes
// ---------------------------------------------------------------------------

/// HTTP response status codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum StatusCode {
    // 1xx Informational
    Continue,
    SwitchingProtocols,

    // 2xx Success
    Ok,
    Created,
    Accepted,
    NoContent,

    // 3xx Redirection
    MovedPermanently,
    Found,
    SeeOther,
    NotModified,
    TemporaryRedirect,
    PermanentRedirect,

    // 4xx Client Error
    BadRequest,
    Unauthorized,
    Forbidden,
    NotFound,
    MethodNotAllowed,
    Conflict,
    Gone,
    LengthRequired,
    PayloadTooLarge,
    UriTooLong,
    UnsupportedMediaType,
    UnprocessableEntity,
    TooManyRequests,

    // 5xx Server Error
    InternalServerError,
    NotImplemented,
    BadGateway,
    ServiceUnavailable,
    GatewayTimeout,
}

impl StatusCode {
    #[must_use]
    pub const fn code(self) -> u16 {
        match self {
            Self::Continue => 100,
            Self::SwitchingProtocols => 101,
            Self::Ok => 200,
            Self::Created => 201,
            Self::Accepted => 202,
            Self::NoContent => 204,
            Self::MovedPermanently => 301,
            Self::Found => 302,
            Self::SeeOther => 303,
            Self::NotModified => 304,
            Self::TemporaryRedirect => 307,
            Self::PermanentRedirect => 308,
            Self::BadRequest => 400,
            Self::Unauthorized => 401,
            Self::Forbidden => 403,
            Self::NotFound => 404,
            Self::MethodNotAllowed => 405,
            Self::Conflict => 409,
            Self::Gone => 410,
            Self::LengthRequired => 411,
            Self::PayloadTooLarge => 413,
            Self::UriTooLong => 414,
            Self::UnsupportedMediaType => 415,
            Self::UnprocessableEntity => 422,
            Self::TooManyRequests => 429,
            Self::InternalServerError => 500,
            Self::NotImplemented => 501,
            Self::BadGateway => 502,
            Self::ServiceUnavailable => 503,
            Self::GatewayTimeout => 504,
        }
    }

    #[must_use]
    pub const fn reason(self) -> &'static str {
        match self {
            Self::Continue => "Continue",
            Self::SwitchingProtocols => "Switching Protocols",
            Self::Ok => "OK",
            Self::Created => "Created",
            Self::Accepted => "Accepted",
            Self::NoContent => "No Content",
            Self::MovedPermanently => "Moved Permanently",
            Self::Found => "Found",
            Self::SeeOther => "See Other",
            Self::NotModified => "Not Modified",
            Self::TemporaryRedirect => "Temporary Redirect",
            Self::PermanentRedirect => "Permanent Redirect",
            Self::BadRequest => "Bad Request",
            Self::Unauthorized => "Unauthorized",
            Self::Forbidden => "Forbidden",
            Self::NotFound => "Not Found",
            Self::MethodNotAllowed => "Method Not Allowed",
            Self::Conflict => "Conflict",
            Self::Gone => "Gone",
            Self::LengthRequired => "Length Required",
            Self::PayloadTooLarge => "Payload Too Large",
            Self::UriTooLong => "URI Too Long",
            Self::UnsupportedMediaType => "Unsupported Media Type",
            Self::UnprocessableEntity => "Unprocessable Entity",
            Self::TooManyRequests => "Too Many Requests",
            Self::InternalServerError => "Internal Server Error",
            Self::NotImplemented => "Not Implemented",
            Self::BadGateway => "Bad Gateway",
            Self::ServiceUnavailable => "Service Unavailable",
            Self::GatewayTimeout => "Gateway Timeout",
        }
    }

    /// The full HTTP/1.1 status line including trailing `\r\n`, as a single
    /// byte slice. Allows writing the status line in one `write_all` call.
    #[must_use]
    pub const fn status_line(self) -> &'static [u8] {
        match self {
            Self::Continue => b"HTTP/1.1 100 Continue\r\n",
            Self::SwitchingProtocols => b"HTTP/1.1 101 Switching Protocols\r\n",
            Self::Ok => b"HTTP/1.1 200 OK\r\n",
            Self::Created => b"HTTP/1.1 201 Created\r\n",
            Self::Accepted => b"HTTP/1.1 202 Accepted\r\n",
            Self::NoContent => b"HTTP/1.1 204 No Content\r\n",
            Self::MovedPermanently => b"HTTP/1.1 301 Moved Permanently\r\n",
            Self::Found => b"HTTP/1.1 302 Found\r\n",
            Self::SeeOther => b"HTTP/1.1 303 See Other\r\n",
            Self::NotModified => b"HTTP/1.1 304 Not Modified\r\n",
            Self::TemporaryRedirect => b"HTTP/1.1 307 Temporary Redirect\r\n",
            Self::PermanentRedirect => b"HTTP/1.1 308 Permanent Redirect\r\n",
            Self::BadRequest => b"HTTP/1.1 400 Bad Request\r\n",
            Self::Unauthorized => b"HTTP/1.1 401 Unauthorized\r\n",
            Self::Forbidden => b"HTTP/1.1 403 Forbidden\r\n",
            Self::NotFound => b"HTTP/1.1 404 Not Found\r\n",
            Self::MethodNotAllowed => b"HTTP/1.1 405 Method Not Allowed\r\n",
            Self::Conflict => b"HTTP/1.1 409 Conflict\r\n",
            Self::Gone => b"HTTP/1.1 410 Gone\r\n",
            Self::LengthRequired => b"HTTP/1.1 411 Length Required\r\n",
            Self::PayloadTooLarge => b"HTTP/1.1 413 Payload Too Large\r\n",
            Self::UriTooLong => b"HTTP/1.1 414 URI Too Long\r\n",
            Self::UnsupportedMediaType => b"HTTP/1.1 415 Unsupported Media Type\r\n",
            Self::UnprocessableEntity => b"HTTP/1.1 422 Unprocessable Entity\r\n",
            Self::TooManyRequests => b"HTTP/1.1 429 Too Many Requests\r\n",
            Self::InternalServerError => b"HTTP/1.1 500 Internal Server Error\r\n",
            Self::NotImplemented => b"HTTP/1.1 501 Not Implemented\r\n",
            Self::BadGateway => b"HTTP/1.1 502 Bad Gateway\r\n",
            Self::ServiceUnavailable => b"HTTP/1.1 503 Service Unavailable\r\n",
            Self::GatewayTimeout => b"HTTP/1.1 504 Gateway Timeout\r\n",
        }
    }
}

impl fmt::Display for StatusCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.code(), self.reason())
    }
}

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

    #[test]
    fn method_display() {
        assert_eq!(Method::Get.to_string(), "GET");
        assert_eq!(Method::Post.to_string(), "POST");
        assert_eq!(Method::Options.to_string(), "OPTIONS");
    }

    #[test]
    fn http_version_display() {
        assert_eq!(HttpVersion::Http10.to_string(), "HTTP/1.0");
        assert_eq!(HttpVersion::Http11.to_string(), "HTTP/1.1");
    }

    #[test]
    fn status_code_display() {
        assert_eq!(StatusCode::Ok.to_string(), "200 OK");
        assert_eq!(StatusCode::NotFound.to_string(), "404 Not Found");
        assert_eq!(
            StatusCode::InternalServerError.to_string(),
            "500 Internal Server Error"
        );
    }
}