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
use std::io::{self, Read, Write};

use crate::ascii::HttpChar;
use crate::error::{Error, ResponseErrorKind};
use crate::headers::{Header, HeaderName, StatusCode};
use crate::validate::HttpValidate;

/// Digit-pair lookup table: "00", "01", ..., "99" — halves the number
/// of divisions compared to one-digit-at-a-time.
#[allow(clippy::cast_possible_truncation)] // i < 100, digits always fit in u8
const DIGITS_LUT: [u8; 200] = {
    let mut t = [0u8; 200];
    let mut i = 0u16;
    while i < 100 {
        t[i as usize * 2] = HttpChar::Zero as u8 + (i / 10) as u8;
        t[i as usize * 2 + 1] = HttpChar::Zero as u8 + (i % 10) as u8;
        i += 1;
    }
    t
};

/// Format a `usize` as decimal digits on the stack (no heap allocation).
/// Uses a two-digits-at-a-time lookup table to halve the division count.
/// Returns a `(buffer, start)` pair; the formatted bytes are `buffer[start..]`.
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn format_usize(n: usize) -> FormattedUsize {
    let mut buf = [0u8; 20]; // usize::MAX is at most 20 digits
    let mut pos = buf.len();
    let mut rem = n;
    while rem >= 100 {
        let pair = (rem % 100) * 2;
        rem /= 100;
        pos -= 2;
        buf[pos] = DIGITS_LUT[pair];
        buf[pos + 1] = DIGITS_LUT[pair + 1];
    }
    // `rem` is now in 0..=99. Single-digit values (including the n==0
    // case) emit one byte; two-digit values emit two.
    if rem >= 10 {
        let pair = rem * 2;
        pos -= 2;
        buf[pos] = DIGITS_LUT[pair];
        buf[pos + 1] = DIGITS_LUT[pair + 1];
    } else {
        pos -= 1;
        buf[pos] = HttpChar::Zero + rem as u8;
    }
    FormattedUsize { buf, start: pos }
}

struct FormattedUsize {
    buf: [u8; 20],
    start: usize,
}

impl FormattedUsize {
    #[inline]
    fn as_bytes(&self) -> &[u8] {
        &self.buf[self.start..]
    }
}

/// Default maximum number of response headers.
pub const DEFAULT_MAX_RESPONSE_HEADERS: usize = 16;

/// An HTTP response builder (status + headers only, no body).
///
/// The body is passed directly to the write method that needs it,
/// keeping the struct free of body lifetime concerns.
///
/// The const generic `MAX_HDRS` controls header capacity
/// (default [`DEFAULT_MAX_RESPONSE_HEADERS`]).
///
/// # Writing modes
///
/// - [`write`](Self::write) — headers + in-memory body (`&[u8]`)
/// - [`write_streaming`](Self::write_streaming) — headers + body from a reader
/// - [`write_headers_to`](Self::write_headers_to) — headers only, caller writes body
///
/// # Examples
///
/// In-memory body:
///
/// ```
/// use xocomil::headers::{StatusCode, ResponseHeader};
/// use xocomil::response::Response;
///
/// let mut output = Vec::new();
/// Response::<16>::new(StatusCode::Ok)
///     .header(ResponseHeader::ContentType, b"text/html").unwrap()
///     .write(&mut output, b"<h1>Hello</h1>")
///     .unwrap();
/// ```
///
/// Streaming from a reader:
///
/// ```
/// use xocomil::headers::{StatusCode, ResponseHeader};
/// use xocomil::response::Response;
///
/// let body_data = b"file contents here";
/// let mut reader = &body_data[..];
/// let mut output = Vec::new();
///
/// Response::<16>::new(StatusCode::Ok)
///     .header(ResponseHeader::ContentType, b"application/octet-stream").unwrap()
///     .header(ResponseHeader::ContentLength, b"18").unwrap()
///     .write_streaming(&mut output, &mut reader)
///     .unwrap();
/// ```
///
/// Headers only (manual body writing):
///
/// ```
/// use std::io::Write;
/// use xocomil::headers::{StatusCode, ResponseHeader};
/// use xocomil::response::Response;
///
/// let mut output = Vec::new();
/// Response::<16>::new(StatusCode::Ok)
///     .header(ResponseHeader::ContentType, b"text/plain").unwrap()
///     .write_headers_to(&mut output)
///     .unwrap();
///
/// // Write body manually
/// output.write_all(b"streamed content").unwrap();
/// ```
#[must_use]
pub struct Response<'resp, const MAX_HDRS: usize = DEFAULT_MAX_RESPONSE_HEADERS> {
    status: StatusCode,
    headers: [Header<'resp>; MAX_HDRS],
    header_count: usize,
    /// Index of the Content-Length header in `headers`, or `None` if absent.
    content_length_idx: Option<usize>,
}

impl<'resp, const MAX_HDRS: usize> Response<'resp, MAX_HDRS> {
    /// Create a new response with the given status code.
    pub const fn new(status: StatusCode) -> Self {
        Self {
            status,
            headers: [Header::EMPTY; MAX_HDRS],
            header_count: 0,
            content_length_idx: None,
        }
    }

    /// Add a header to the response.
    ///
    /// Accepts any [`HeaderName`] — pass `ResponseHeader::ContentType`
    /// for type-safe names, or a raw `&str`.
    ///
    /// Header names must consist of valid HTTP token characters (RFC 7230
    /// §3.2.6) and values must not contain NUL, CR, or LF bytes.
    ///
    /// Returns `&mut Self` so headers can be chained or added in a loop
    /// with error recovery (the builder is not consumed on failure).
    ///
    /// # Errors
    ///
    /// Returns [`Error`] if the number of headers exceeds `MAX_HDRS`,
    /// or if the header name or value contains forbidden bytes.
    pub fn header(
        &mut self,
        name: impl HeaderName<'resp>,
        value: &'resp [u8],
    ) -> Result<&mut Self, Error> {
        if self.header_count >= MAX_HDRS {
            return Err(ResponseErrorKind::HeaderCapacityExceeded.into());
        }
        let name_bytes = name.as_header_bytes();
        if !name_bytes.is_valid_token() {
            return Err(ResponseErrorKind::InvalidHeaderName.into());
        }
        if !value.is_valid_header_value() {
            return Err(ResponseErrorKind::InvalidHeaderValue.into());
        }
        // Reject duplicate Content-Length headers — ambiguous framing that
        // downstream parsers may resolve inconsistently. O(1) via index.
        let is_content_length = name.known_index().map_or_else(
            || name_bytes.eq_ignore_ascii_case(b"Content-Length"),
            |idx| idx == crate::headers::ResponseHeader::ContentLength as usize,
        );
        if is_content_length {
            if self.content_length_idx.is_some() {
                return Err(ResponseErrorKind::DuplicateContentLength.into());
            }
            self.content_length_idx = Some(self.header_count);
        }
        self.headers[self.header_count] = Header::new(name_bytes, value);
        self.header_count += 1;
        Ok(self)
    }

    /// Write the status line and all user-supplied headers (without the
    /// terminal blank line). Used by both `write_headers_to` and `write`.
    fn write_status_and_headers(&self, writer: &mut impl Write) -> io::Result<()> {
        writer.write_all(self.status.status_line())?;
        for i in 0..self.header_count {
            let hdr = &self.headers[i];
            writer.write_all(hdr.name())?;
            writer.write_all(b": ")?;
            writer.write_all(hdr.value())?;
            writer.write_all(b"\r\n")?;
        }
        Ok(())
    }

    /// Write only the status line and headers to the writer.
    ///
    /// After calling this, the caller is responsible for writing the body
    /// and flushing. This enables streaming bodies from files, iterators,
    /// or any other source without buffering the entire response in memory.
    ///
    /// For best performance with unbuffered writers (e.g. raw `TcpStream`),
    /// wrap them in a `BufWriter` before calling this.
    ///
    /// # Errors
    ///
    /// Returns `io::Error` if writing fails.
    pub fn write_headers_to(&self, writer: &mut impl Write) -> io::Result<()> {
        self.write_status_and_headers(writer)?;
        writer.write_all(b"\r\n")
    }

    /// Write the full response (headers + in-memory body).
    ///
    /// Automatically appends a `Content-Length` header matching `body.len()`
    /// unless the caller already set one. If a manual `Content-Length` was
    /// set, it **must** match `body.len()` or an error is returned (a
    /// mismatch would produce malformed HTTP framing).
    ///
    /// Does **not** flush the writer — the caller controls flushing.
    ///
    /// # Errors
    ///
    /// Returns `io::Error` if writing to the writer fails, or if a
    /// manually-set `Content-Length` does not match the body length.
    pub fn write(&self, writer: &mut impl Write, body: &[u8]) -> io::Result<()> {
        // Validate Content-Length mismatch before writing anything. O(1) via stored index.
        if let Some(cl_idx) = self.content_length_idx {
            let expected = format_usize(body.len());
            if self.headers[cl_idx].value() != expected.as_bytes() {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "Content-Length header does not match body length",
                ));
            }
        }

        // Status line + user-supplied headers
        self.write_status_and_headers(writer)?;

        // Auto Content-Length when not manually set
        if self.content_length_idx.is_none() {
            writer.write_all(b"Content-Length: ")?;
            writer.write_all(format_usize(body.len()).as_bytes())?;
            writer.write_all(b"\r\n")?;
        }

        // End of headers + body
        writer.write_all(b"\r\n")?;
        if !body.is_empty() {
            writer.write_all(body)?;
        }
        Ok(())
    }

    /// Write headers, then stream the body from a reader.
    ///
    /// The caller **must** set `Content-Length` before calling this — the
    /// response needs a declared body length to frame the message correctly.
    /// The reader is limited to exactly `Content-Length` bytes to prevent
    /// writing more data than declared (response desync).
    ///
    /// To stream a chunked response, use [`write_headers_to`](Self::write_headers_to)
    /// and encode the chunks manually.
    ///
    /// Does **not** flush — the caller controls flushing.
    ///
    /// # Reader handling
    ///
    /// If `body` yields **more** than `Content-Length` bytes, the surplus
    /// is left **unread in the reader**. This is intentional response
    /// framing — emitting the surplus would desync the connection — but
    /// it means the caller must not assume `body` was drained. If `body`
    /// is a connection that will be reused, the leftover bytes will be
    /// the next thing read from it.
    ///
    /// If `body` yields **fewer** bytes than `Content-Length`, this
    /// returns [`io::ErrorKind::UnexpectedEof`].
    ///
    /// # Errors
    ///
    /// Returns `io::Error` if writing or reading fails, or if
    /// `Content-Length` is absent or invalid.
    pub fn write_streaming(&self, writer: &mut impl Write, body: &mut impl Read) -> io::Result<()> {
        // O(1) Content-Length lookup via stored index.
        let content_length = self.content_length_idx.ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "streaming response requires Content-Length header; \
                 use write_headers_to and encode chunks manually for chunked responses",
            )
        })?;

        let limit = crate::ascii::parse_content_length(self.headers[content_length].value())
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "Content-Length is not a valid integer",
                )
            })?;

        self.write_headers_to(writer)?;

        let copied = io::copy(&mut body.take(limit), writer)?;
        if copied < limit {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "body reader produced fewer bytes than Content-Length",
            ));
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ResponseErrorKind;
    use crate::headers::ResponseHeader;

    /// Helper: write response with body to a Vec and return as String.
    fn render(response: &Response, body: &[u8]) -> String {
        let mut out = Vec::new();
        response.write(&mut out, body).unwrap();
        String::from_utf8(out).unwrap()
    }

    /// Helper: write response with no body.
    fn render_empty(response: &Response) -> String {
        render(response, b"")
    }

    // -----------------------------------------------------------------------
    // write (headers + in-memory body)
    // -----------------------------------------------------------------------

    #[test]
    fn basic_200_response() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Type", b"text/plain").unwrap();
        let rendered = render(&resp, b"hello");
        assert!(rendered.starts_with("HTTP/1.1 200 OK\r\n"));
        assert!(rendered.contains("Content-Type: text/plain\r\n"));
        assert!(rendered.contains("\r\n\r\nhello"));
    }

    #[test]
    fn basic_404_response() {
        let resp = render(&Response::new(StatusCode::NotFound), b"not found");
        assert!(resp.starts_with("HTTP/1.1 404 Not Found\r\n"));
        assert!(resp.ends_with("not found"));
    }

    #[test]
    fn response_with_no_body() {
        let resp = render_empty(&Response::new(StatusCode::Ok));
        assert!(resp.ends_with("\r\n\r\n"));
    }

    #[test]
    fn response_with_binary_body() {
        let body = &[0u8, 1, 2, 255, 254, 253];
        let mut out = Vec::new();
        Response::<16>::new(StatusCode::Ok)
            .write(&mut out, body)
            .unwrap();
        assert!(out.ends_with(body));
    }

    #[test]
    fn multiple_headers() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Type", b"text/html").unwrap();
        resp.header("Cache-Control", b"no-cache").unwrap();
        resp.header("X-Custom", b"value").unwrap();
        let rendered = render(&resp, b"");
        assert!(rendered.contains("Content-Type: text/html\r\n"));
        assert!(rendered.contains("Cache-Control: no-cache\r\n"));
        assert!(rendered.contains("X-Custom: value\r\n"));
    }

    #[test]
    fn typed_response_headers() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header(ResponseHeader::ContentType, b"text/html")
            .unwrap();
        resp.header(ResponseHeader::CacheControl, b"no-store")
            .unwrap();
        resp.header(ResponseHeader::Connection, b"close").unwrap();
        let rendered = render(&resp, b"");
        assert!(rendered.contains("Content-Type: text/html\r\n"));
        assert!(rendered.contains("Cache-Control: no-store\r\n"));
        assert!(rendered.contains("Connection: close\r\n"));
    }

    #[test]
    fn all_status_codes() {
        for (status, expected) in [
            (StatusCode::Continue, "100 Continue"),
            (StatusCode::SwitchingProtocols, "101 Switching Protocols"),
            (StatusCode::Ok, "200 OK"),
            (StatusCode::Created, "201 Created"),
            (StatusCode::Accepted, "202 Accepted"),
            (StatusCode::NoContent, "204 No Content"),
            (StatusCode::MovedPermanently, "301 Moved Permanently"),
            (StatusCode::Found, "302 Found"),
            (StatusCode::SeeOther, "303 See Other"),
            (StatusCode::NotModified, "304 Not Modified"),
            (StatusCode::TemporaryRedirect, "307 Temporary Redirect"),
            (StatusCode::PermanentRedirect, "308 Permanent Redirect"),
            (StatusCode::BadRequest, "400 Bad Request"),
            (StatusCode::Unauthorized, "401 Unauthorized"),
            (StatusCode::Forbidden, "403 Forbidden"),
            (StatusCode::NotFound, "404 Not Found"),
            (StatusCode::MethodNotAllowed, "405 Method Not Allowed"),
            (StatusCode::Conflict, "409 Conflict"),
            (StatusCode::Gone, "410 Gone"),
            (StatusCode::LengthRequired, "411 Length Required"),
            (StatusCode::PayloadTooLarge, "413 Payload Too Large"),
            (StatusCode::UriTooLong, "414 URI Too Long"),
            (
                StatusCode::UnsupportedMediaType,
                "415 Unsupported Media Type",
            ),
            (StatusCode::UnprocessableEntity, "422 Unprocessable Entity"),
            (StatusCode::TooManyRequests, "429 Too Many Requests"),
            (StatusCode::InternalServerError, "500 Internal Server Error"),
            (StatusCode::NotImplemented, "501 Not Implemented"),
            (StatusCode::BadGateway, "502 Bad Gateway"),
            (StatusCode::ServiceUnavailable, "503 Service Unavailable"),
            (StatusCode::GatewayTimeout, "504 Gateway Timeout"),
        ] {
            let resp = render_empty(&Response::new(status));
            assert!(
                resp.starts_with(&format!("HTTP/1.1 {expected}\r\n")),
                "expected {expected}, got: {resp}"
            );
        }
    }

    // -----------------------------------------------------------------------
    // write_headers_to (headers only)
    // -----------------------------------------------------------------------

    #[test]
    fn write_headers_only() {
        let mut out = Vec::new();
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Type", b"text/plain").unwrap();
        resp.write_headers_to(&mut out).unwrap();
        let headers = String::from_utf8(out).unwrap();
        assert!(headers.starts_with("HTTP/1.1 200 OK\r\n"));
        assert!(headers.contains("Content-Type: text/plain\r\n"));
        assert!(headers.ends_with("\r\n\r\n"));
    }

    #[test]
    fn write_headers_then_manual_body() {
        let mut out = Vec::new();
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Type", b"text/plain").unwrap();
        resp.write_headers_to(&mut out).unwrap();
        out.extend_from_slice(b"manual body");

        let resp = String::from_utf8(out).unwrap();
        assert!(resp.ends_with("manual body"));
    }

    // -----------------------------------------------------------------------
    // write_streaming (headers + reader body)
    // -----------------------------------------------------------------------

    #[test]
    fn write_streaming_from_reader() {
        let body = b"streamed content";
        let mut reader = &body[..];
        let mut out = Vec::new();

        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Type", b"application/octet-stream")
            .unwrap();
        resp.header("Content-Length", b"16").unwrap();
        resp.write_streaming(&mut out, &mut reader).unwrap();

        let rendered = String::from_utf8(out).unwrap();
        assert!(rendered.starts_with("HTTP/1.1 200 OK\r\n"));
        assert!(rendered.ends_with("streamed content"));
    }

    #[test]
    fn write_streaming_empty_reader() {
        let mut reader = std::io::empty();
        let mut out = Vec::new();

        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"0").unwrap();
        resp.write_streaming(&mut out, &mut reader).unwrap();

        let rendered = String::from_utf8(out).unwrap();
        assert!(rendered.ends_with("\r\n\r\n"));
    }

    // -----------------------------------------------------------------------
    // Const generic MAX_HDRS
    // -----------------------------------------------------------------------

    #[test]
    fn custom_small_response_capacity() {
        let mut out = Vec::new();
        let mut resp = Response::<2>::new(StatusCode::Ok);
        resp.header("A", b"1").unwrap();
        resp.header("B", b"2").unwrap();
        resp.write(&mut out, b"").unwrap();
        let s = String::from_utf8(out).unwrap();
        assert!(s.contains("A: 1\r\n"));
        assert!(s.contains("B: 2\r\n"));
    }

    #[test]
    fn exceeding_header_capacity_returns_error() {
        let mut resp = Response::<2>::new(StatusCode::Ok);
        resp.header("A", b"1").unwrap();
        resp.header("B", b"2").unwrap();
        let err = resp.header("C", b"3").err().expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::HeaderCapacityExceeded)
        ));
    }

    // -----------------------------------------------------------------------
    // Header validation (response splitting prevention)
    // -----------------------------------------------------------------------

    #[test]
    fn rejects_value_with_crlf_injection() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        let err = resp
            .header("Content-Type", b"text/html\r\nX-Injected: evil")
            .err()
            .expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::InvalidHeaderValue)
        ));
    }

    #[test]
    fn rejects_value_with_nul() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        let err = resp
            .header("X-Bad", b"val\x00ue")
            .err()
            .expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::InvalidHeaderValue)
        ));
    }

    #[test]
    fn rejects_value_with_bare_cr() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        let err = resp
            .header("X-Bad", b"val\rue")
            .err()
            .expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::InvalidHeaderValue)
        ));
    }

    #[test]
    fn rejects_value_with_bare_lf() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        let err = resp
            .header("X-Bad", b"val\nue")
            .err()
            .expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::InvalidHeaderValue)
        ));
    }

    #[test]
    fn rejects_invalid_header_name() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        let err = resp
            .header("Bad Name", b"value")
            .err()
            .expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::InvalidHeaderName)
        ));
    }

    #[test]
    fn rejects_header_name_with_crlf() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        let err = resp
            .header("Bad\r\nName", b"value")
            .err()
            .expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::InvalidHeaderName)
        ));
    }

    #[test]
    fn rejects_empty_header_name() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        let err = resp.header("", b"value").err().expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::InvalidHeaderName)
        ));
    }

    #[test]
    fn allows_valid_header_value_with_high_bytes() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        assert!(resp.header("X-Custom", &[0x80, 0xFF, 0xFE]).is_ok());
    }

    #[test]
    fn builder_recovers_from_error() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        // Invalid header fails but doesn't consume the builder
        let err = resp
            .header("Bad Name", b"value")
            .err()
            .expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::InvalidHeaderName)
        ));
        // Builder is still usable
        resp.header("Good-Name", b"value").unwrap();
        let rendered = render(&resp, b"");
        assert!(rendered.contains("Good-Name: value\r\n"));
    }

    // -----------------------------------------------------------------------
    // Auto Content-Length
    // -----------------------------------------------------------------------

    #[test]
    fn auto_content_length_added() {
        let resp = render(&Response::new(StatusCode::Ok), b"hello");
        assert!(resp.contains("Content-Length: 5\r\n"));
    }

    #[test]
    fn auto_content_length_zero() {
        let resp = render_empty(&Response::new(StatusCode::Ok));
        assert!(resp.contains("Content-Length: 0\r\n"));
    }

    #[test]
    fn manual_content_length_not_duplicated() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"5").unwrap();
        let rendered = render(&resp, b"hello");
        assert_eq!(rendered.matches("Content-Length").count(), 1);
    }

    // -----------------------------------------------------------------------
    // Content-Length mismatch prevention
    // -----------------------------------------------------------------------

    #[test]
    fn rejects_content_length_mismatch() {
        let mut out = Vec::new();
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"999").unwrap();
        let err = resp.write(&mut out, b"hello").unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn accepts_correct_manual_content_length() {
        let mut out = Vec::new();
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"5").unwrap();
        resp.write(&mut out, b"hello").unwrap();
        let rendered = String::from_utf8(out).unwrap();
        assert!(rendered.contains("Content-Length: 5\r\n"));
        assert!(rendered.ends_with("hello"));
    }

    // -----------------------------------------------------------------------
    // Streaming framing requirement
    // -----------------------------------------------------------------------

    #[test]
    fn streaming_rejects_missing_framing() {
        let mut reader = &b"body"[..];
        let mut out = Vec::new();
        let err = Response::<16>::new(StatusCode::Ok)
            .write_streaming(&mut out, &mut reader)
            .unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn streaming_accepts_content_length() {
        let mut reader = &b"body"[..];
        let mut out = Vec::new();
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"4").unwrap();
        resp.write_streaming(&mut out, &mut reader).unwrap();
        let rendered = String::from_utf8(out).unwrap();
        assert!(rendered.ends_with("body"));
    }

    #[test]
    fn streaming_rejects_transfer_encoding_without_content_length() {
        let mut reader = &b"4\r\nbody\r\n0\r\n\r\n"[..];
        let mut out = Vec::new();
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Transfer-Encoding", b"chunked").unwrap();
        let err = resp.write_streaming(&mut out, &mut reader).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn streaming_limits_body_to_content_length() {
        // Reader has 10 bytes but Content-Length says 4
        let mut reader = &b"bodySECRET"[..];
        let mut out = Vec::new();
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"4").unwrap();
        resp.write_streaming(&mut out, &mut reader).unwrap();
        let rendered = String::from_utf8(out).unwrap();
        assert!(rendered.ends_with("body"));
        assert!(!rendered.contains("SECRET"));
    }

    #[test]
    fn streaming_rejects_short_body() {
        // Reader has 2 bytes but Content-Length says 10
        let mut reader = &b"hi"[..];
        let mut out = Vec::new();
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"10").unwrap();
        let err = resp.write_streaming(&mut out, &mut reader).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
    }

    #[test]
    fn streaming_rejects_invalid_content_length() {
        let mut reader = &b"body"[..];
        let mut out = Vec::new();
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"not-a-number").unwrap();
        let err = resp.write_streaming(&mut out, &mut reader).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    // -----------------------------------------------------------------------
    // Duplicate Content-Length prevention
    // -----------------------------------------------------------------------

    #[test]
    fn rejects_duplicate_content_length_header() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"5").unwrap();
        let err = resp
            .header("Content-Length", b"10")
            .err()
            .expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::DuplicateContentLength)
        ));
    }

    #[test]
    fn rejects_duplicate_content_length_case_insensitive() {
        let mut resp = Response::<16>::new(StatusCode::Ok);
        resp.header("Content-Length", b"5").unwrap();
        let err = resp
            .header("content-length", b"5")
            .err()
            .expect("expected error");
        assert!(matches!(
            err,
            Error::Response(ResponseErrorKind::DuplicateContentLength)
        ));
    }
}