http-net 0.2.0

Sans-IO HTTP/1.1 server and client: strict RFC 9112 parsing, smuggling defences, bounded buffers, keep-alive, chunked bodies, upgrades, a blocking std adapter, no dependencies.
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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
//! Incremental scanning of message heads, their interpretation, and the
//! borrowed views handed to callers.
//!
//! The scanner finds one CRLF-terminated line at a time and remembers where
//! it stopped searching, so input that arrives one byte at a time is still
//! examined once: head parsing is linear in the head's length no matter how
//! it is split. Each line is fully validated when it completes; field
//! positions are stored as offsets from the message start so the head can be
//! read back without copying.

use alloc::vec::Vec;
use core::{fmt, slice};

use crate::{
    error::HttpError,
    limits::Limits,
    syntax::{
        check_field_value, find_byte, is_host_value, is_ows, is_reason, is_target_chars, is_tchar,
        is_token, list_elements, parse_decimal, trim_ows,
    },
};

/// An offset range into a message head.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Span {
    start: u32,
    end: u32,
}

impl Span {
    #[inline]
    fn new(start: usize, end: usize) -> Self {
        // Offsets are bounded by the buffer capacity, which `Limits` keeps
        // far below `u32::MAX`.
        Self {
            start: start as u32,
            end: end as u32,
        }
    }

    #[inline]
    pub(crate) fn get<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
        buf.get(self.start as usize..self.end as usize)
            .unwrap_or(&[])
    }
}

/// One field line: name and (OWS-trimmed) value.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Field {
    name: Span,
    value: Span,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum HeadKind {
    Request,
    Response,
    Trailer,
}

pub(crate) enum Progress {
    Partial,
    /// The head is complete; the value is its length including the blank line.
    Done(usize),
}

/// Finds the next CRLF-terminated line starting at `line_start`, resuming
/// the search at `*scan`. Returns the end of the line content (the index of
/// its CR). `budget` bounds the line length including CRLF.
pub(crate) fn find_line(
    msg: &[u8],
    line_start: usize,
    scan: &mut usize,
    budget: usize,
    too_long: HttpError,
) -> Result<Option<usize>, HttpError> {
    let from = (*scan).max(line_start);
    let hay = msg.get(from..).unwrap_or(&[]);
    match find_byte(b'\n', hay) {
        Some(i) => {
            let lf = from + i;
            if lf + 1 - line_start > budget {
                return Err(too_long);
            }
            if lf == line_start || msg.get(lf - 1) != Some(&b'\r') {
                return Err(HttpError::BareLf);
            }
            *scan = lf + 1;
            Ok(Some(lf - 1))
        }
        None => {
            *scan = msg.len();
            if msg.len().saturating_sub(line_start) >= budget {
                Err(too_long)
            } else {
                Ok(None)
            }
        }
    }
}

/// Resumable scanner over a head (start line plus field lines) or a trailer
/// section (field lines only).
pub(crate) struct HeadScanner {
    scan: usize,
    line_start: usize,
    start_line: Option<Span>,
    skipped: usize,
    field_bytes: usize,
    count: usize,
    pub(crate) fields: Vec<Field>,
}

impl HeadScanner {
    pub(crate) const fn new() -> Self {
        Self {
            scan: 0,
            line_start: 0,
            start_line: None,
            skipped: 0,
            field_bytes: 0,
            count: 0,
            fields: Vec::new(),
        }
    }

    /// Prepares for the next message; keeps the field vector's allocation.
    pub(crate) fn reset(&mut self) {
        self.scan = 0;
        self.line_start = 0;
        self.start_line = None;
        self.skipped = 0;
        self.field_bytes = 0;
        self.count = 0;
        self.fields.clear();
    }

    /// Resets only the line state, for a trailer section, keeping the head's
    /// stored fields readable.
    pub(crate) fn reset_lines(&mut self) {
        self.scan = 0;
        self.line_start = 0;
        self.skipped = 0;
        self.field_bytes = 0;
        self.count = 0;
    }

    pub(crate) fn start_line(&self) -> Span {
        self.start_line.unwrap_or_default()
    }

    /// Scans `msg` (the bytes from the message start to the end of input).
    pub(crate) fn advance(
        &mut self,
        msg: &[u8],
        limits: &Limits,
        kind: HeadKind,
        store: bool,
    ) -> Result<Progress, HttpError> {
        loop {
            let in_start = kind != HeadKind::Trailer && self.start_line.is_none();
            let (budget, too_long) = if in_start {
                (
                    limits.max_start_line().saturating_sub(self.skipped),
                    HttpError::StartLineTooLong,
                )
            } else {
                (
                    limits.max_header_bytes().saturating_sub(self.field_bytes),
                    HttpError::HeadersTooLarge,
                )
            };
            let Some(end) = find_line(msg, self.line_start, &mut self.scan, budget, too_long)?
            else {
                return Ok(Progress::Partial);
            };
            let start = self.line_start;
            let line = msg.get(start..end).unwrap_or(&[]);
            let line_len = self.scan - start;
            self.line_start = self.scan;

            if in_start {
                if line.is_empty() {
                    if kind == HeadKind::Request {
                        // RFC 9112 section 2.2: ignore empty lines before the
                        // request line. They count against its budget.
                        self.skipped += line_len;
                        continue;
                    }
                    return Err(HttpError::InvalidStartLine);
                }
                if find_byte(b'\r', line).is_some() {
                    return Err(HttpError::BareCr);
                }
                self.start_line = Some(Span::new(start, end));
                continue;
            }
            if line.is_empty() {
                return Ok(Progress::Done(self.scan));
            }
            self.field_bytes += line_len;
            // Every field line must leave room for the blank line that ends
            // the section, so the section as a whole fits the budget.
            if self.field_bytes + 2 > limits.max_header_bytes() {
                return Err(HttpError::HeadersTooLarge);
            }
            if self.count >= limits.max_headers() {
                return Err(HttpError::TooManyHeaders);
            }
            let field = parse_field(line, start)?;
            self.count += 1;
            if store {
                self.fields.push(field);
            }
        }
    }
}

/// Validates one field line (`line` starts at offset `base` in the head).
fn parse_field(line: &[u8], base: usize) -> Result<Field, HttpError> {
    if line.first().is_some_and(|&b| is_ows(b)) {
        return Err(HttpError::ObsFold);
    }
    let Some(colon) = find_byte(b':', line) else {
        return Err(if find_byte(b'\r', line).is_some() {
            HttpError::BareCr
        } else {
            HttpError::InvalidHeaderName
        });
    };
    let name = &line[..colon];
    if name.last().is_some_and(|&b| is_ows(b)) {
        return Err(HttpError::WhitespaceBeforeColon);
    }
    if !name.iter().all(|&b| is_tchar(b)) || name.is_empty() {
        return Err(if find_byte(b'\r', name).is_some() {
            HttpError::BareCr
        } else {
            HttpError::InvalidHeaderName
        });
    }
    let raw = &line[colon + 1..];
    let lead = raw.iter().take_while(|&&b| is_ows(b)).count();
    let value = trim_ows(raw);
    check_field_value(value)?;
    let value_start = base + colon + 1 + lead;
    Ok(Field {
        name: Span::new(base, base + colon),
        value: Span::new(value_start, value_start + value.len()),
    })
}

/// The request method.
///
/// Methods are case-sensitive (RFC 9110 section 9.1): `get` is a different,
/// unregistered method and parses as [`Method::Other`]. The exact text is
/// always available from [`RequestHead::method_str`].
///
/// # Examples
///
/// ```
/// use http_net::Method;
///
/// assert_eq!(Method::from_bytes(b"GET"), Method::Get);
/// assert_eq!(Method::from_bytes(b"get"), Method::Other);
/// assert_eq!(Method::Post.as_str(), Some("POST"));
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Method {
    /// `GET`
    Get,
    /// `HEAD`: the response carries headers but never a body.
    Head,
    /// `POST`
    Post,
    /// `PUT`
    Put,
    /// `DELETE`
    Delete,
    /// `CONNECT`: the target is in authority form; a 2xx response turns the
    /// connection into a tunnel.
    Connect,
    /// `OPTIONS`: the only method that may use the `*` target.
    Options,
    /// `TRACE`
    Trace,
    /// `PATCH`
    Patch,
    /// Any other token.
    Other,
}

impl Method {
    /// Classifies a method token (case-sensitive).
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(http_net::Method::from_bytes(b"PATCH"), http_net::Method::Patch);
    /// ```
    #[must_use]
    pub fn from_bytes(token: &[u8]) -> Self {
        match token {
            b"GET" => Self::Get,
            b"HEAD" => Self::Head,
            b"POST" => Self::Post,
            b"PUT" => Self::Put,
            b"DELETE" => Self::Delete,
            b"CONNECT" => Self::Connect,
            b"OPTIONS" => Self::Options,
            b"TRACE" => Self::Trace,
            b"PATCH" => Self::Patch,
            _ => Self::Other,
        }
    }

    /// The method's text, or `None` for [`Method::Other`].
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(http_net::Method::Other.as_str(), None);
    /// ```
    #[must_use]
    pub const fn as_str(&self) -> Option<&'static str> {
        Some(match self {
            Self::Get => "GET",
            Self::Head => "HEAD",
            Self::Post => "POST",
            Self::Put => "PUT",
            Self::Delete => "DELETE",
            Self::Connect => "CONNECT",
            Self::Options => "OPTIONS",
            Self::Trace => "TRACE",
            Self::Patch => "PATCH",
            Self::Other => return None,
        })
    }
}

/// The HTTP version of a message.
///
/// # Examples
///
/// ```
/// use http_net::Version;
///
/// assert_eq!(Version::Http11.as_str(), "HTTP/1.1");
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Version {
    /// HTTP/1.0: no chunked encoding, keep-alive only when asked for.
    Http10,
    /// HTTP/1.1 (also used for HTTP/1.2 through 1.9, which RFC 9110 section
    /// 2.5 says to process as the highest implemented minor version).
    Http11,
}

impl Version {
    /// The version's wire text.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(http_net::Version::Http10.as_str(), "HTTP/1.0");
    /// ```
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Http10 => "HTTP/1.0",
            Self::Http11 => "HTTP/1.1",
        }
    }
}

/// How a message's body is delimited.
///
/// # Examples
///
/// ```
/// use http_net::{BodyFraming, ServerConn, ServerEvent};
///
/// let mut conn = ServerConn::new();
/// let _ = conn.feed(b"POST /x HTTP/1.1\r\nHost: a\r\nContent-Length: 3\r\n\r\nabc");
/// match conn.poll().unwrap() {
///     ServerEvent::Request(req) => assert_eq!(req.framing(), BodyFraming::Length(3)),
///     other => panic!("{other:?}"),
/// }
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BodyFraming {
    /// No body.
    None,
    /// Exactly this many bytes (`Content-Length`).
    Length(u64),
    /// `Transfer-Encoding: chunked`.
    Chunked,
    /// The body runs until the peer closes the connection (responses only).
    UntilClose,
}

fn parse_version(v: &[u8]) -> Result<Version, HttpError> {
    match v {
        [b'H', b'T', b'T', b'P', b'/', major, b'.', minor]
            if major.is_ascii_digit() && minor.is_ascii_digit() =>
        {
            match (major, minor) {
                (b'1', b'0') => Ok(Version::Http10),
                (b'1', _) => Ok(Version::Http11),
                _ => Err(HttpError::UnsupportedVersion),
            }
        }
        _ => Err(HttpError::InvalidVersion),
    }
}

/// What the framing-relevant fields of a message say.
#[derive(Default)]
struct FieldFacts {
    content_length: Option<u64>,
    te_seen: bool,
    te_codings: usize,
    te_chunked: usize,
    te_last_chunked: bool,
    te_other: bool,
    close: bool,
    keep_alive: bool,
    upgrade_token: bool,
    upgrade_field: bool,
    expect_continue: bool,
    hosts: usize,
    host: Option<Span>,
}

fn scan_fields(head: &[u8], fields: &[Field]) -> Result<FieldFacts, HttpError> {
    let mut facts = FieldFacts::default();
    for field in fields {
        let name = field.name.get(head);
        let value = field.value.get(head);
        if name.eq_ignore_ascii_case(b"content-length") {
            if facts.content_length.is_some() {
                return Err(HttpError::DuplicateContentLength);
            }
            facts.content_length =
                Some(parse_decimal(value).ok_or(HttpError::InvalidContentLength)?);
        } else if name.eq_ignore_ascii_case(b"transfer-encoding") {
            facts.te_seen = true;
            for element in list_elements(value) {
                let (coding, params) = match find_byte(b';', element) {
                    Some(i) => (trim_ows(&element[..i]), true),
                    None => (element, false),
                };
                if !is_token(coding) {
                    return Err(HttpError::InvalidTransferEncoding);
                }
                facts.te_codings += 1;
                if coding.eq_ignore_ascii_case(b"chunked") {
                    if params {
                        return Err(HttpError::InvalidTransferEncoding);
                    }
                    facts.te_chunked += 1;
                    facts.te_last_chunked = true;
                } else {
                    facts.te_other = true;
                    facts.te_last_chunked = false;
                }
            }
        } else if name.eq_ignore_ascii_case(b"connection") {
            for token in list_elements(value) {
                if token.eq_ignore_ascii_case(b"close") {
                    facts.close = true;
                } else if token.eq_ignore_ascii_case(b"keep-alive") {
                    facts.keep_alive = true;
                } else if token.eq_ignore_ascii_case(b"upgrade") {
                    facts.upgrade_token = true;
                }
            }
        } else if name.eq_ignore_ascii_case(b"upgrade") {
            facts.upgrade_field |= !value.is_empty();
        } else if name.eq_ignore_ascii_case(b"host") {
            facts.hosts += 1;
            facts.host = Some(field.value);
        } else if name.eq_ignore_ascii_case(b"expect") {
            // RFC 9110 section 10.1.1: the expectation is case-insensitive.
            facts.expect_continue |=
                list_elements(value).any(|e| e.eq_ignore_ascii_case(b"100-continue"));
        }
    }
    Ok(facts)
}

/// Applies RFC 9112 section 6 to the transfer-coding facts.
fn transfer_framing(
    facts: &FieldFacts,
    version: Version,
) -> Result<Option<BodyFraming>, HttpError> {
    if !facts.te_seen {
        return Ok(None);
    }
    if version == Version::Http10 {
        return Err(HttpError::TransferEncodingInHttp10);
    }
    if facts.content_length.is_some() {
        return Err(HttpError::ConflictingFraming);
    }
    if facts.te_codings == 0 || facts.te_chunked > 1 || !facts.te_last_chunked {
        return Err(HttpError::InvalidTransferEncoding);
    }
    if facts.te_other {
        return Err(HttpError::UnsupportedTransferEncoding);
    }
    Ok(Some(BodyFraming::Chunked))
}

/// Everything learned from a request head.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RequestInfo {
    pub(crate) method: Method,
    method_span: Span,
    target: Span,
    pub(crate) version: Version,
    pub(crate) framing: BodyFraming,
    pub(crate) keep_alive: bool,
    pub(crate) upgrade: bool,
    pub(crate) expect_continue: bool,
    host: Option<Span>,
    /// The authority of an absolute-form target, which replaces `Host`.
    authority: Option<Span>,
    /// The path-and-query part of the target: the whole target except for
    /// the absolute form, where it is what follows the authority.
    origin: Span,
}

impl RequestInfo {
    pub(crate) const EMPTY: Self = Self {
        method: Method::Get,
        method_span: Span { start: 0, end: 0 },
        target: Span { start: 0, end: 0 },
        version: Version::Http11,
        framing: BodyFraming::None,
        keep_alive: false,
        upgrade: false,
        expect_continue: false,
        host: None,
        authority: None,
        origin: Span { start: 0, end: 0 },
    };
}

/// Validates a request target against the forms its method allows.
pub(crate) fn check_target(method: Method, target: &[u8]) -> Result<(), HttpError> {
    let ok = match target.first() {
        None => false,
        Some(b'/') => method != Method::Connect && is_target_chars(target),
        Some(b'*') if target.len() == 1 => method == Method::Options,
        Some(_) if method == Method::Connect => {
            // authority-form: host ":" port, with a non-empty host and port.
            is_authority(target)
                && target
                    .iter()
                    .rposition(|&b| b == b':')
                    .is_some_and(|c| c + 1 < target.len() && !target[c..].contains(&b']'))
        }
        Some(_) => split_absolute_form(target).is_some(),
    };
    if ok {
        Ok(())
    } else {
        Err(HttpError::InvalidTarget)
    }
}

/// `host [":" port]` with a non-empty host: RFC 9110 section 4.2.1 makes an
/// empty host in an `http` URI invalid.
fn is_authority(s: &[u8]) -> bool {
    !s.is_empty() && s[0] != b':' && is_host_value(s)
}

/// Splits an absolute-form target, `scheme "://" authority path-abempty
/// [ "?" query ]`, returning the authority's range within it.
///
/// Only the hierarchical form with an authority is accepted: it is the form
/// RFC 9112 section 3.2.2 describes (requests to proxies, and future
/// requests to origin servers), and it is the only one that names the host
/// the request is for. Userinfo is refused (RFC 9110 section 4.2.4 says to
/// treat it as an error), as is an empty host.
fn split_absolute_form(target: &[u8]) -> Option<(usize, usize)> {
    let colon = find_byte(b':', target)?;
    let scheme = &target[..colon];
    let scheme_ok = scheme.first().is_some_and(u8::is_ascii_alphabetic)
        && scheme
            .iter()
            .all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'));
    if !scheme_ok || !target[colon..].starts_with(b"://") {
        return None;
    }
    let auth_start = colon + 3;
    let after = &target[auth_start..];
    let auth_len = after
        .iter()
        .position(|&b| b == b'/' || b == b'?')
        .unwrap_or(after.len());
    let authority = &after[..auth_len];
    let rest = &after[auth_len..];
    (is_authority(authority) && is_target_chars(rest))
        .then_some((auth_start, auth_start + auth_len))
}

pub(crate) fn interpret_request(
    head: &[u8],
    start: Span,
    fields: &[Field],
    limits: &Limits,
) -> Result<RequestInfo, HttpError> {
    let line = start.get(head);
    let base = start.start as usize;
    let sp1 = find_byte(b' ', line).ok_or(HttpError::InvalidStartLine)?;
    let sp2 = line
        .iter()
        .rposition(|&b| b == b' ')
        .ok_or(HttpError::InvalidStartLine)?;
    if sp2 == sp1 {
        return Err(HttpError::InvalidStartLine);
    }
    let method_bytes = &line[..sp1];
    if !is_token(method_bytes) {
        return Err(HttpError::InvalidMethod);
    }
    let version = parse_version(&line[sp2 + 1..])?;
    let method = Method::from_bytes(method_bytes);
    let target = &line[sp1 + 1..sp2];
    check_target(method, target)?;
    let target_start = base + sp1 + 1;
    let target_span = Span::new(target_start, base + sp2);
    let (authority, origin) = match target.first() {
        Some(b'/' | b'*') => (None, target_span),
        _ if method == Method::Connect => (None, target_span),
        _ => match split_absolute_form(target) {
            Some((a, b)) => (
                Some(Span::new(target_start + a, target_start + b)),
                Span::new(target_start + b, base + sp2),
            ),
            None => return Err(HttpError::InvalidTarget),
        },
    };

    let facts = scan_fields(head, fields)?;
    let framing = match transfer_framing(&facts, version)? {
        Some(f) => f,
        None => match facts.content_length {
            Some(n) if n > limits.max_body() => return Err(HttpError::BodyTooLarge),
            Some(0) | None => BodyFraming::None,
            Some(n) => BodyFraming::Length(n),
        },
    };
    if facts.hosts > 1 {
        return Err(HttpError::InvalidHost);
    }
    if let Some(host) = facts.host {
        if !is_host_value(host.get(head)) {
            return Err(HttpError::InvalidHost);
        }
    } else if version == Version::Http11 {
        return Err(HttpError::MissingHost);
    }
    let keep_alive = match version {
        Version::Http11 => !facts.close,
        Version::Http10 => facts.keep_alive && !facts.close,
    };
    Ok(RequestInfo {
        method,
        method_span: Span::new(base, base + sp1),
        target: target_span,
        version,
        framing,
        keep_alive,
        // RFC 9110 section 7.8: Upgrade in an HTTP/1.0 request is ignored.
        upgrade: version == Version::Http11 && facts.upgrade_token && facts.upgrade_field,
        // RFC 9110 section 10.1.1: ignored in HTTP/1.0, and meaningless
        // without a body to wait for.
        expect_continue: version == Version::Http11
            && facts.expect_continue
            && framing != BodyFraming::None,
        host: facts.host,
        authority,
        origin,
    })
}

/// Everything learned from a response head.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ResponseInfo {
    pub(crate) status: u16,
    reason: Span,
    pub(crate) version: Version,
    pub(crate) framing: BodyFraming,
    pub(crate) keep_alive: bool,
    pub(crate) upgrade_field: bool,
}

impl ResponseInfo {
    pub(crate) const EMPTY: Self = Self {
        status: 0,
        reason: Span { start: 0, end: 0 },
        version: Version::Http11,
        framing: BodyFraming::None,
        keep_alive: false,
        upgrade_field: false,
    };
}

/// What the client asked for, which decides how the response is framed.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Asked {
    pub(crate) head: bool,
    pub(crate) connect: bool,
}

pub(crate) fn interpret_response(
    head: &[u8],
    start: Span,
    fields: &[Field],
    limits: &Limits,
    asked: Asked,
) -> Result<ResponseInfo, HttpError> {
    let line = start.get(head);
    let base = start.start as usize;
    // status-line = HTTP-version SP status-code SP [ reason-phrase ]
    if line.len() < 13 || line[8] != b' ' || line[12] != b' ' {
        return Err(HttpError::InvalidStartLine);
    }
    let version = parse_version(&line[..8])?;
    let code = &line[9..12];
    if !code.iter().all(u8::is_ascii_digit) {
        return Err(HttpError::InvalidStatus);
    }
    let status = code
        .iter()
        .fold(0u16, |acc, &d| acc * 10 + u16::from(d - b'0'));
    if !(100..=599).contains(&status) {
        return Err(HttpError::InvalidStatus);
    }
    let reason = &line[13..];
    if !is_reason(reason) {
        return Err(HttpError::InvalidStartLine);
    }

    let facts = scan_fields(head, fields)?;
    let bodiless = asked.head
        || (100..200).contains(&status)
        || status == 204
        || status == 304
        || (asked.connect && (200..300).contains(&status));
    let framing = if bodiless {
        BodyFraming::None
    } else {
        match transfer_framing(&facts, version)? {
            Some(f) => f,
            None => match facts.content_length {
                Some(n) if n > limits.max_body() => return Err(HttpError::BodyTooLarge),
                Some(0) => BodyFraming::None,
                Some(n) => BodyFraming::Length(n),
                None => BodyFraming::UntilClose,
            },
        }
    };
    let keep_alive = framing != BodyFraming::UntilClose
        && match version {
            Version::Http11 => !facts.close,
            Version::Http10 => facts.keep_alive && !facts.close,
        };
    Ok(ResponseInfo {
        status,
        reason: Span::new(base + 13, base + line.len()),
        version,
        framing,
        keep_alive,
        upgrade_field: facts.upgrade_field,
    })
}

/// Iterator over a head's fields as `(name, value)` pairs, in arrival order.
///
/// Names are returned as received (field names are case-insensitive; compare
/// with `eq_ignore_ascii_case`). Values have surrounding whitespace removed
/// and may contain any byte RFC 9110 allows, including `obs-text` above
/// 0x7F, so they are bytes rather than `str`.
///
/// # Examples
///
/// ```
/// use http_net::{ServerConn, ServerEvent};
///
/// let mut conn = ServerConn::new();
/// let _ = conn.feed(b"GET / HTTP/1.1\r\nHost: a\r\nX-One: 1\r\n\r\n");
/// if let ServerEvent::Request(req) = conn.poll().unwrap() {
///     let names: Vec<&str> = req.headers().map(|(n, _)| n).collect();
///     assert_eq!(names, ["Host", "X-One"]);
/// }
/// ```
#[derive(Clone)]
pub struct Headers<'a> {
    head: &'a [u8],
    fields: slice::Iter<'a, Field>,
}

impl<'a> Iterator for Headers<'a> {
    type Item = (&'a str, &'a [u8]);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let field = self.fields.next()?;
        Some((
            core::str::from_utf8(field.name.get(self.head)).unwrap_or(""),
            field.value.get(self.head),
        ))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.fields.size_hint()
    }
}

impl ExactSizeIterator for Headers<'_> {}

impl fmt::Debug for Headers<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(self.clone().map(|(n, v)| (n, Lossy(v))))
            .finish()
    }
}

struct Lossy<'a>(&'a [u8]);

impl fmt::Debug for Lossy<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match core::str::from_utf8(self.0) {
            Ok(s) => fmt::Debug::fmt(s, f),
            Err(_) => fmt::Debug::fmt(self.0, f),
        }
    }
}

fn find_header<'a>(head: &'a [u8], fields: &[Field], name: &str) -> Option<&'a [u8]> {
    fields
        .iter()
        .find(|f| f.name.get(head).eq_ignore_ascii_case(name.as_bytes()))
        .map(|f| f.value.get(head))
}

/// A parsed request head, borrowed from the connection's buffer.
///
/// Every accessor is a slice of the bytes that arrived; nothing is copied.
/// The view stays valid until the next call that mutates the connection.
/// Read it again later with [`ServerConn::request`](crate::ServerConn::request).
///
/// # Examples
///
/// ```
/// use http_net::{Method, ServerConn, ServerEvent, Version};
///
/// let mut conn = ServerConn::new();
/// let _ = conn.feed(b"GET /search?q=rust HTTP/1.1\r\nHost: example.com\r\n\r\n");
/// let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
/// assert_eq!(req.method(), Method::Get);
/// assert_eq!(req.path(), "/search");
/// assert_eq!(req.query(), Some("q=rust"));
/// assert_eq!(req.version(), Version::Http11);
/// assert_eq!(req.host(), Some("example.com"));
/// assert!(req.keep_alive());
/// ```
#[derive(Clone, Copy)]
pub struct RequestHead<'a> {
    head: &'a [u8],
    fields: &'a [Field],
    info: &'a RequestInfo,
}

impl<'a> RequestHead<'a> {
    pub(crate) const fn new(head: &'a [u8], fields: &'a [Field], info: &'a RequestInfo) -> Self {
        Self { head, fields, info }
    }

    /// The method, classified.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{Method, ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"DELETE /x HTTP/1.1\r\nHost: a\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.method(), Method::Delete);
    /// ```
    #[must_use]
    pub fn method(&self) -> Method {
        self.info.method
    }

    /// The method exactly as received.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{Method, ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"PROPFIND /x HTTP/1.1\r\nHost: a\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.method(), Method::Other);
    /// assert_eq!(req.method_str(), "PROPFIND");
    /// ```
    #[must_use]
    pub fn method_str(&self) -> &'a str {
        core::str::from_utf8(self.info.method_span.get(self.head)).unwrap_or("")
    }

    /// The request target exactly as received (origin form `/path?query`,
    /// absolute form, authority form for `CONNECT`, or `*`).
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /a%20b?x=1 HTTP/1.1\r\nHost: a\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.target(), "/a%20b?x=1");
    /// ```
    #[must_use]
    pub fn target(&self) -> &'a str {
        core::str::from_utf8(self.info.target.get(self.head)).unwrap_or("")
    }

    /// The path: the target up to (not including) the first `?`, with
    /// percent-encoding left as received.
    ///
    /// For an absolute-form target (`http://host/p?q`) this is the path
    /// after the authority (`/p`), and `/` when that path is empty, so a
    /// router sees the same path whichever form the client used. For `*`
    /// and for `CONNECT`'s authority form it is the whole target.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /files/a.txt?v=2 HTTP/1.1\r\nHost: a\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.path(), "/files/a.txt");
    ///
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET http://a/files/b.txt HTTP/1.1\r\nHost: a\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.path(), "/files/b.txt");
    /// ```
    #[must_use]
    pub fn path(&self) -> &'a str {
        let origin = self.origin();
        let path = origin.split_once('?').map_or(origin, |(p, _)| p);
        if path.is_empty() && self.info.authority.is_some() {
            // RFC 9110 section 4.2.3: an empty path in an http URI is "/".
            "/"
        } else {
            path
        }
    }

    /// The query after the first `?`, if there is one.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /x HTTP/1.1\r\nHost: a\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.query(), None);
    /// ```
    #[must_use]
    pub fn query(&self) -> Option<&'a str> {
        self.origin().split_once('?').map(|(_, q)| q)
    }

    /// The path-and-query part of the target.
    fn origin(&self) -> &'a str {
        core::str::from_utf8(self.info.origin.get(self.head)).unwrap_or("")
    }

    /// The protocol version.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent, Version};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /x HTTP/1.0\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.version(), Version::Http10);
    /// ```
    #[must_use]
    pub fn version(&self) -> Version {
        self.info.version
    }

    /// All fields in arrival order.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /x HTTP/1.1\r\nHost: a\r\nAccept: */*\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.headers().len(), 2);
    /// ```
    #[must_use]
    pub fn headers(&self) -> Headers<'a> {
        Headers {
            head: self.head,
            fields: self.fields.iter(),
        }
    }

    /// The value of the first field named `name` (ASCII case-insensitive).
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /x HTTP/1.1\r\nHost: a\r\nAccept:  text/html \r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.header("accept"), Some(&b"text/html"[..]));
    /// assert_eq!(req.header("cookie"), None);
    /// ```
    #[must_use]
    pub fn header(&self, name: &str) -> Option<&'a [u8]> {
        find_header(self.head, self.fields, name)
    }

    /// Like [`header`](Self::header), but only when the value is UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /x HTTP/1.1\r\nHost: a\r\nX: \xff\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.header_str("host"), Some("a"));
    /// assert_eq!(req.header_str("x"), None);
    /// ```
    #[must_use]
    pub fn header_str(&self, name: &str) -> Option<&'a str> {
        self.header(name).and_then(|v| core::str::from_utf8(v).ok())
    }

    /// The authority the request is for (`host [":" port]`), if known.
    ///
    /// This is the `Host` field, except for an absolute-form target
    /// (`GET http://example.com/ HTTP/1.1`), whose authority wins: RFC 9112
    /// section 3.2.2 requires a server to ignore `Host` then, so the two can
    /// never be read differently. The raw field stays available through
    /// `header("host")`. HTTP/1.1 requests always carry a valid `Host`;
    /// HTTP/1.0 requests may not, and an empty `Host` (a target with no
    /// authority) is reported as `Some("")`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /x HTTP/1.1\r\nHost: 127.0.0.1:8080\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.host(), Some("127.0.0.1:8080"));
    ///
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET http://a.test/x HTTP/1.1\r\nHost: b.test\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.host(), Some("a.test"));
    /// assert_eq!(req.header("host"), Some(&b"b.test"[..]));
    /// ```
    #[must_use]
    pub fn host(&self) -> Option<&'a str> {
        self.info
            .authority
            .or(self.info.host)
            .and_then(|s| core::str::from_utf8(s.get(self.head)).ok())
    }

    /// Whether the client sent `Expect: 100-continue` and is waiting for a
    /// `100 Continue` before sending the body. Only HTTP/1.1 requests that
    /// have a body report it (RFC 9110 section 10.1.1).
    ///
    /// Answer it before reading the body: either
    /// [`ServerConn::send_continue`](crate::ServerConn::send_continue), or a
    /// final response straight away (which closes the connection afterwards,
    /// since the body was not read). The blocking `Server` sends
    /// `100 Continue` itself.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"PUT /f HTTP/1.1\r\nHost: a\r\nExpect: 100-continue\r\nContent-Length: 9\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert!(req.expects_continue());
    /// ```
    #[must_use]
    pub fn expects_continue(&self) -> bool {
        self.info.expect_continue
    }

    /// How the request body is delimited.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{BodyFraming, ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"POST /x HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(req.framing(), BodyFraming::Chunked);
    /// ```
    #[must_use]
    pub fn framing(&self) -> BodyFraming {
        self.info.framing
    }

    /// Whether the client allows the connection to stay open after this
    /// exchange (HTTP/1.1 unless `Connection: close`; HTTP/1.0 only with
    /// `Connection: keep-alive`).
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /x HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert!(!req.keep_alive());
    /// ```
    #[must_use]
    pub fn keep_alive(&self) -> bool {
        self.info.keep_alive
    }

    /// Whether this is an HTTP/1.1 request to switch protocols: `Connection`
    /// lists `upgrade` and an `Upgrade` field names the protocol (read it
    /// with `header("upgrade")`). Answer with
    /// [`Response::switching_protocols`](crate::Response::switching_protocols)
    /// to hand the connection over.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ServerConn, ServerEvent};
    /// # let mut conn = ServerConn::new();
    /// # let _ = conn.feed(b"GET /ws HTTP/1.1\r\nHost: a\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n");
    /// # let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
    /// assert!(req.is_upgrade());
    /// assert_eq!(req.header("upgrade"), Some(&b"websocket"[..]));
    /// ```
    #[must_use]
    pub fn is_upgrade(&self) -> bool {
        self.info.upgrade
    }
}

impl fmt::Debug for RequestHead<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RequestHead")
            .field("method", &self.method_str())
            .field("target", &self.target())
            .field("version", &self.version())
            .field("headers", &self.headers())
            .field("framing", &self.framing())
            .finish()
    }
}

/// A parsed response head, borrowed from the client connection's buffer.
///
/// # Examples
///
/// ```
/// use http_net::{ClientConn, ClientEvent, Request};
///
/// let mut conn = ClientConn::new();
/// let mut out = Vec::new();
/// conn.send_request(&Request::get("/").header("host", "a"), &mut out).unwrap();
/// let _ = conn.feed(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
/// let ClientEvent::Response(resp) = conn.poll().unwrap() else { panic!() };
/// assert_eq!(resp.status(), 404);
/// assert_eq!(resp.reason(), "Not Found");
/// ```
#[derive(Clone, Copy)]
pub struct ResponseHead<'a> {
    head: &'a [u8],
    fields: &'a [Field],
    info: &'a ResponseInfo,
}

impl<'a> ResponseHead<'a> {
    pub(crate) const fn new(head: &'a [u8], fields: &'a [Field], info: &'a ResponseInfo) -> Self {
        Self { head, fields, info }
    }

    /// The status code (`100..=599`).
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ClientConn, ClientEvent, Request};
    /// # let mut conn = ClientConn::new();
    /// # conn.send_request(&Request::get("/").header("host", "a"), &mut Vec::new()).unwrap();
    /// # let _ = conn.feed(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
    /// # let ClientEvent::Response(resp) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(resp.status(), 200);
    /// ```
    #[must_use]
    pub fn status(&self) -> u16 {
        self.info.status
    }

    /// The reason phrase, if it is UTF-8 (it carries no meaning; RFC 9112
    /// tells clients to ignore it).
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ClientConn, ClientEvent, Request};
    /// # let mut conn = ClientConn::new();
    /// # conn.send_request(&Request::get("/").header("host", "a"), &mut Vec::new()).unwrap();
    /// # let _ = conn.feed(b"HTTP/1.1 200 \r\nContent-Length: 0\r\n\r\n");
    /// # let ClientEvent::Response(resp) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(resp.reason(), "");
    /// ```
    #[must_use]
    pub fn reason(&self) -> &'a str {
        core::str::from_utf8(self.info.reason.get(self.head)).unwrap_or("")
    }

    /// The protocol version.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ClientConn, ClientEvent, Request, Version};
    /// # let mut conn = ClientConn::new();
    /// # conn.send_request(&Request::get("/").header("host", "a"), &mut Vec::new()).unwrap();
    /// # let _ = conn.feed(b"HTTP/1.0 200 OK\r\n\r\n");
    /// # let ClientEvent::Response(resp) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(resp.version(), Version::Http10);
    /// ```
    #[must_use]
    pub fn version(&self) -> Version {
        self.info.version
    }

    /// All fields in arrival order.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ClientConn, ClientEvent, Request};
    /// # let mut conn = ClientConn::new();
    /// # conn.send_request(&Request::get("/").header("host", "a"), &mut Vec::new()).unwrap();
    /// # let _ = conn.feed(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nX: y\r\n\r\n");
    /// # let ClientEvent::Response(resp) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(resp.headers().count(), 2);
    /// ```
    #[must_use]
    pub fn headers(&self) -> Headers<'a> {
        Headers {
            head: self.head,
            fields: self.fields.iter(),
        }
    }

    /// The value of the first field named `name` (ASCII case-insensitive).
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ClientConn, ClientEvent, Request};
    /// # let mut conn = ClientConn::new();
    /// # conn.send_request(&Request::get("/").header("host", "a"), &mut Vec::new()).unwrap();
    /// # let _ = conn.feed(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 0\r\n\r\n");
    /// # let ClientEvent::Response(resp) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(resp.header("content-type"), Some(&b"text/plain"[..]));
    /// ```
    #[must_use]
    pub fn header(&self, name: &str) -> Option<&'a [u8]> {
        find_header(self.head, self.fields, name)
    }

    /// Like [`header`](Self::header), but only when the value is UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ClientConn, ClientEvent, Request};
    /// # let mut conn = ClientConn::new();
    /// # conn.send_request(&Request::get("/").header("host", "a"), &mut Vec::new()).unwrap();
    /// # let _ = conn.feed(b"HTTP/1.1 200 OK\r\nServer: x\r\nContent-Length: 0\r\n\r\n");
    /// # let ClientEvent::Response(resp) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(resp.header_str("server"), Some("x"));
    /// ```
    #[must_use]
    pub fn header_str(&self, name: &str) -> Option<&'a str> {
        self.header(name).and_then(|v| core::str::from_utf8(v).ok())
    }

    /// How the response body is delimited (accounts for `HEAD` requests and
    /// bodiless status codes).
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{BodyFraming, ClientConn, ClientEvent, Request};
    /// # let mut conn = ClientConn::new();
    /// # conn.send_request(&Request::get("/").header("host", "a"), &mut Vec::new()).unwrap();
    /// # let _ = conn.feed(b"HTTP/1.1 200 OK\r\n\r\n");
    /// # let ClientEvent::Response(resp) = conn.poll().unwrap() else { panic!() };
    /// assert_eq!(resp.framing(), BodyFraming::UntilClose);
    /// ```
    #[must_use]
    pub fn framing(&self) -> BodyFraming {
        self.info.framing
    }

    /// Whether the connection can carry another request after this response.
    ///
    /// # Examples
    ///
    /// ```
    /// # use http_net::{ClientConn, ClientEvent, Request};
    /// # let mut conn = ClientConn::new();
    /// # conn.send_request(&Request::get("/").header("host", "a"), &mut Vec::new()).unwrap();
    /// # let _ = conn.feed(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
    /// # let ClientEvent::Response(resp) = conn.poll().unwrap() else { panic!() };
    /// assert!(resp.keep_alive());
    /// ```
    #[must_use]
    pub fn keep_alive(&self) -> bool {
        self.info.keep_alive
    }
}

impl fmt::Debug for ResponseHead<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ResponseHead")
            .field("status", &self.status())
            .field("reason", &self.reason())
            .field("version", &self.version())
            .field("headers", &self.headers())
            .field("framing", &self.framing())
            .finish()
    }
}

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

    fn scan(msg: &[u8], kind: HeadKind) -> Result<(HeadScanner, usize), HttpError> {
        let mut s = HeadScanner::new();
        match s.advance(msg, &Limits::new(), kind, true)? {
            Progress::Done(n) => Ok((s, n)),
            Progress::Partial => Err(HttpError::UnexpectedEof),
        }
    }

    #[test]
    fn test_scanner_resumes_without_rescanning() {
        let msg = b"GET / HTTP/1.1\r\nHost: a\r\n\r\n";
        let mut s = HeadScanner::new();
        for end in 1..msg.len() {
            assert!(matches!(
                s.advance(&msg[..end], &Limits::new(), HeadKind::Request, true),
                Ok(Progress::Partial)
            ));
        }
        assert!(matches!(
            s.advance(msg, &Limits::new(), HeadKind::Request, true),
            Ok(Progress::Done(n)) if n == msg.len()
        ));
        assert_eq!(s.fields.len(), 1);
    }

    #[test]
    fn test_scanner_rejects_line_shapes() {
        let cases: &[(&[u8], HttpError)] = &[
            (b"GET / HTTP/1.1\nHost: a\r\n\r\n", HttpError::BareLf),
            (b"GET / HTTP/1.1\r\n Host: a\r\n\r\n", HttpError::ObsFold),
            (
                b"GET / HTTP/1.1\r\nHost : a\r\n\r\n",
                HttpError::WhitespaceBeforeColon,
            ),
            (
                b"GET / HTTP/1.1\r\nHost\r\n\r\n",
                HttpError::InvalidHeaderName,
            ),
            (
                b"GET / HTTP/1.1\r\n: a\r\n\r\n",
                HttpError::InvalidHeaderName,
            ),
            (b"GET / HTTP/1.1\r\nHo\rst: a\r\n\r\n", HttpError::BareCr),
            (b"GET / HTTP/1.1\r\nHost: a\rb\r\n\r\n", HttpError::BareCr),
            (b"GET /\r HTTP/1.1\r\n\r\n", HttpError::BareCr),
            (
                b"GET / HTTP/1.1\r\nHost: a\x00\r\n\r\n",
                HttpError::InvalidHeaderValue,
            ),
        ];
        for (msg, err) in cases {
            assert_eq!(scan(msg, HeadKind::Request).err(), Some(*err), "{msg:?}");
        }
    }

    #[test]
    fn test_scanner_skips_leading_empty_lines_for_requests_only() {
        assert!(scan(b"\r\n\r\nGET / HTTP/1.1\r\n\r\n", HeadKind::Request).is_ok());
        assert_eq!(
            scan(b"\r\nHTTP/1.1 200 OK\r\n\r\n", HeadKind::Response).err(),
            Some(HttpError::InvalidStartLine)
        );
    }

    #[test]
    fn test_scanner_enforces_limits_at_boundaries() {
        let limits = Limits::new().with_max_start_line(16);
        // "GET / HTTP/1.1\r\n" is exactly 16 bytes.
        let mut s = HeadScanner::new();
        assert!(
            s.advance(b"GET / HTTP/1.1\r\n\r\n", &limits, HeadKind::Request, true)
                .is_ok()
        );
        let mut s = HeadScanner::new();
        assert_eq!(
            s.advance(b"GET /a HTTP/1.1\r\n\r\n", &limits, HeadKind::Request, true)
                .err(),
            Some(HttpError::StartLineTooLong)
        );
        // Partial input already at the budget fails without waiting for LF.
        let mut s = HeadScanner::new();
        assert_eq!(
            s.advance(b"GET /aaaaaaaaaaaa", &limits, HeadKind::Request, true)
                .err(),
            Some(HttpError::StartLineTooLong)
        );

        let limits = Limits::new().with_max_headers(1);
        let mut s = HeadScanner::new();
        assert_eq!(
            s.advance(
                b"GET / HTTP/1.1\r\nA: 1\r\nB: 2\r\n\r\n",
                &limits,
                HeadKind::Request,
                true
            )
            .err(),
            Some(HttpError::TooManyHeaders)
        );

        // "A: 1\r\n" is 6 bytes; with 8 the final CRLF still fits.
        let limits = Limits::new().with_max_header_bytes(8);
        let mut s = HeadScanner::new();
        assert!(
            s.advance(
                b"GET / HTTP/1.1\r\nA: 1\r\n\r\n",
                &limits,
                HeadKind::Request,
                true
            )
            .is_ok()
        );
        let mut s = HeadScanner::new();
        assert_eq!(
            s.advance(
                b"GET / HTTP/1.1\r\nA: 12\r\nB: 1\r\n\r\n",
                &limits,
                HeadKind::Request,
                true
            )
            .err(),
            Some(HttpError::HeadersTooLarge)
        );
    }

    #[test]
    fn test_versions() {
        assert_eq!(parse_version(b"HTTP/1.1"), Ok(Version::Http11));
        assert_eq!(parse_version(b"HTTP/1.0"), Ok(Version::Http10));
        assert_eq!(parse_version(b"HTTP/1.9"), Ok(Version::Http11));
        assert_eq!(
            parse_version(b"HTTP/2.0"),
            Err(HttpError::UnsupportedVersion)
        );
        assert_eq!(
            parse_version(b"HTTP/0.9"),
            Err(HttpError::UnsupportedVersion)
        );
        assert_eq!(parse_version(b"http/1.1"), Err(HttpError::InvalidVersion));
        assert_eq!(parse_version(b"HTTP/1.10"), Err(HttpError::InvalidVersion));
        assert_eq!(parse_version(b"HTTP/1"), Err(HttpError::InvalidVersion));
    }

    #[test]
    fn test_target_forms_follow_method() {
        assert!(check_target(Method::Get, b"/").is_ok());
        assert!(check_target(Method::Options, b"*").is_ok());
        assert!(check_target(Method::Get, b"*").is_err());
        assert!(check_target(Method::Connect, b"example.com:443").is_ok());
        assert!(check_target(Method::Connect, b"[::1]:443").is_ok());
        assert!(check_target(Method::Connect, b"example.com").is_err());
        assert!(check_target(Method::Connect, b"/").is_err());
        assert!(check_target(Method::Get, b"http://example.com/a?b").is_ok());
        assert!(check_target(Method::Get, b"http://[::1]:80/").is_ok());
        assert!(check_target(Method::Get, b"http://x").is_ok());
        assert!(check_target(Method::Get, b"http://x?q").is_ok());
        assert!(check_target(Method::Get, b"http://u@x/").is_err());
        assert!(check_target(Method::Get, b"http:x").is_err());
        assert!(check_target(Method::Get, b"http://:80/").is_err());
        assert!(check_target(Method::Get, b"http://x/[a]").is_err());
        assert!(check_target(Method::Connect, b":443").is_err());
        assert!(check_target(Method::Get, b"1http://x").is_err());
        assert!(check_target(Method::Get, b"example.com").is_err());
        assert!(check_target(Method::Get, b"").is_err());
    }
}