http-request 23.3.0

http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, automatic handling of redirects (including detecting redirect loops), and enhanced response body decoding (both automatic and manual), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects.
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
use super::*;

/// Split on a multi-byte delimiter, returning each slice. Used to split an
/// HTTP response into status line / headers / body.
/// Matches do not overlap, and an empty delimiter leaves the input unchanged.
///
/// # Arguments
///
/// - `&'a [u8]` - The buffer to split.
/// - `&'a [u8]` - The multi-byte delimiter to split on.
///
/// # Returns
///
/// - `Vec<&'a [u8]>`: The delimiter-separated slices, including any trailing remainder.
#[cfg(test)]
pub(crate) fn split_multi_byte<'a>(data: &'a [u8], delimiter: &'a [u8]) -> Vec<&'a [u8]> {
    if delimiter.is_empty() {
        return vec![data];
    }
    let mut result: Vec<&[u8]> = Vec::new();
    let mut start: usize = 0;
    while let Some(offset) = data[start..]
        .windows(delimiter.len())
        .position(|window: &[u8]| window == delimiter)
    {
        let end: usize = start + offset;
        result.push(&data[start..end]);
        start = end + delimiter.len();
    }
    if start < data.len() {
        result.push(&data[start..]);
    }
    result
}

/// Split on whitespace (space or tab).
///
/// # Arguments
///
/// - `&[u8]` - The buffer to split.
///
/// # Returns
///
/// - `Vec<&[u8]>`: The non-empty whitespace-separated slices.
#[cfg(test)]
pub(crate) fn split_whitespace(input: &[u8]) -> Vec<&[u8]> {
    let mut parts: Vec<&[u8]> = Vec::new();
    let mut start: usize = 0;
    for (i, &byte) in input.iter().enumerate() {
        if byte == SPACE_U8 || byte == TAB_U8 {
            if i > start {
                parts.push(&input[start..i]);
            }
            start = i + 1;
        }
    }
    if start < input.len() {
        parts.push(&input[start..]);
    }
    parts
}

/// Build the raw HTTP request line + headers + optional body into a single
/// `Vec<u8>` suitable for writing to the wire.
///
/// # Arguments
///
/// - `&str` - The HTTP method token.
/// - `String` - The request path, with any query string already appended.
/// - `Vec<u8>` - The wire-format header block bytes.
/// - `Option<Vec<u8>>` - The wire-format body bytes, or `None` when there is no body.
/// - `String` - The HTTP version token.
///
/// # Returns
///
/// - `Vec<u8>`: The complete request bytes, ready to write to the wire.
#[cfg(test)]
pub(crate) fn build_http_request(
    method: &str,
    path: String,
    header_bytes: Vec<u8>,
    body_bytes: Option<Vec<u8>>,
    http_version_str: String,
) -> Vec<u8> {
    let request_line_size: usize = method.len() + 1 + path.len() + 1 + http_version_str.len();
    let body_size: usize = body_bytes.as_ref().map_or(0, |b: &Vec<u8>| b.len());
    let total_size: usize = request_line_size + 2 + header_bytes.len() + 2 + body_size;
    let mut request: Vec<u8> = Vec::with_capacity(total_size);
    request.extend_from_slice(method.as_bytes());
    request.push(b' ');
    request.extend_from_slice(path.as_bytes());
    request.push(b' ');
    request.extend_from_slice(http_version_str.as_bytes());
    request.extend_from_slice(HTTP_BR_BYTES);
    request.extend_from_slice(&header_bytes);
    request.extend_from_slice(HTTP_BR_BYTES);
    if let Some(body) = body_bytes {
        request.extend_from_slice(&body);
    }
    request
}

/// Parse a chunked transfer-encoded body into the concatenated raw bytes.
///
/// Walks the `chunk-size CRLF chunk-data CRLF` sequence until it sees a
/// terminating zero-size chunk.
///
/// # Arguments
///
/// - `&[u8]` - The raw chunked body bytes.
///
/// # Returns
///
/// - `Result<Vec<u8>, RequestError>` - The complete decoded payload, or invalid or incomplete framing.
#[cfg(test)]
pub(crate) fn parse_chunked_body(body_bytes: &[u8]) -> Result<Vec<u8>, RequestError> {
    let (body_end, total_decoded): (usize, usize) = chunked_body_end_with_len(body_bytes)?.ok_or(
        RequestError::HttpRequestPartsInsufficient(HttpStatus::BadRequest),
    )?;
    let mut result: Vec<u8> = Vec::with_capacity(total_decoded);
    let mut pos: usize = 0;
    while pos < body_end {
        let line_end: usize = find_crlf(body_bytes, pos).ok_or(
            RequestError::HttpRequestPartsInsufficient(HttpStatus::BadRequest),
        )?;
        let chunk_size: usize = parse_chunk_size(&body_bytes[pos..line_end])?;
        if chunk_size == 0 {
            break;
        }
        let data_start: usize = line_end + HTTP_BR_BYTES.len();
        let data_end: usize = data_start
            .checked_add(chunk_size)
            .ok_or(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest))?;
        result.extend_from_slice(&body_bytes[data_start..data_end]);
        pos = data_end + HTTP_BR_BYTES.len();
    }
    Ok(result)
}

/// Parse a strict hexadecimal chunk size, accepting optional extensions.
///
/// RFC 9112 §7.1.1 permits bad whitespace before the extension delimiter,
/// but not after a chunk size with no extension.
///
/// # Arguments
///
/// - `&[u8]` - The complete chunk-size line without its CRLF.
///
/// # Returns
///
/// - `Result<usize, RequestError>` - The bounded size, or an error for invalid syntax or overflow.
pub(crate) fn parse_chunk_size(line: &[u8]) -> Result<usize, RequestError> {
    if !is_valid_header_value(line) {
        return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
    }
    let extension_start: Option<usize> = line
        .iter()
        .position(|byte: &u8| *byte == CHUNK_EXTENSION_SEPARATOR);
    let size_bytes: &[u8] = match extension_start {
        Some(end) => line[..end].trim_ascii_end(),
        None => line,
    };
    if size_bytes.is_empty() || !size_bytes.iter().all(u8::is_ascii_hexdigit) {
        return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
    }
    let size: usize = from_utf8(size_bytes)
        .ok()
        .and_then(|value: &str| usize::from_str_radix(value, 16).ok())
        .ok_or(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest))?;
    if size > MAX_RESPONSE_CHUNK_SIZE {
        return Err(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
    }
    Ok(size)
}

/// Validate chunk boundaries and locate the terminating trailer section along with total decoded bytes.
///
/// # Arguments
///
/// - `&[u8]` - The chunked bytes received so far.
///
/// # Returns
///
/// - `Result<Option<(usize, usize)>, RequestError>` - `(end_offset, decoded_len)`, incomplete input, or invalid framing.
#[cfg(test)]
pub(crate) fn chunked_body_end_with_len(
    body_bytes: &[u8],
) -> Result<Option<(usize, usize)>, RequestError> {
    let mut pos: usize = 0;
    let mut total_decoded: usize = 0;
    while pos < body_bytes.len() {
        let Some(line_end) = find_crlf(body_bytes, pos) else {
            return Ok(None);
        };
        let chunk_size: usize = parse_chunk_size(&body_bytes[pos..line_end])?;
        let data_start: usize = line_end + HTTP_BR_BYTES.len();
        if chunk_size == 0 {
            if body_bytes[data_start..].starts_with(HTTP_CARRIAGE_RETURN_LINE_FEED) {
                return Ok(Some((data_start + HTTP_BR_BYTES.len(), total_decoded)));
            }
            if let Some(trailer_end) = find_double_crlf(body_bytes, data_start) {
                let end: usize = trailer_end + HTTP_BR_BYTES.len() * 2;
                let _: Option<&[u8]> =
                    validate_header_block(&body_bytes[data_start..end], &[], false)?;
                return Ok(Some((end, total_decoded)));
            }
            if body_bytes.len().saturating_sub(data_start) > MAX_RESPONSE_HEAD_BYTES {
                return Err(RequestError::Request(RESPONSE_TOO_LARGE.to_owned()));
            }
            return Ok(None);
        }
        total_decoded = total_decoded
            .checked_add(chunk_size)
            .ok_or(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest))?;
        if total_decoded > MAX_RESPONSE_BODY_BYTES {
            return Err(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
        }
        let data_end: usize = data_start
            .checked_add(chunk_size)
            .ok_or(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest))?;
        let next: usize = data_end
            .checked_add(HTTP_BR_BYTES.len())
            .ok_or(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest))?;
        if next > body_bytes.len() {
            return Ok(None);
        }
        if &body_bytes[data_end..next] != HTTP_BR_BYTES {
            return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
        }
        pos = next;
    }
    Ok(None)
}

/// Validate chunk boundaries and locate the complete terminating trailer section.
///
/// # Arguments
///
/// - `&[u8]` - The chunked bytes received so far.
///
/// # Returns
///
/// - `Result<Option<usize>, RequestError>` - The completed body end, incomplete input, or invalid framing.
#[cfg(test)]
#[inline(always)]
pub(crate) fn chunked_body_end(body_bytes: &[u8]) -> Result<Option<usize>, RequestError> {
    Ok(chunked_body_end_with_len(body_bytes)?.map(|(end, _): (usize, usize)| end))
}

/// Finds the next `\n` byte offset inside `bytes` using 8-byte SWAR scanning.
///
/// # Arguments
///
/// - `&[u8]` - Slice to search.
///
/// # Returns
///
/// - `Option<usize>` - Relative index of the first `\n` byte, if present.
#[inline(always)]
fn find_lf_swar(bytes: &[u8]) -> Option<usize> {
    let len: usize = bytes.len();
    let mut index: usize = 0;
    while index + 8 <= len {
        let word: u64 = u64::from_ne_bytes([
            bytes[index],
            bytes[index + 1],
            bytes[index + 2],
            bytes[index + 3],
            bytes[index + 4],
            bytes[index + 5],
            bytes[index + 6],
            bytes[index + 7],
        ]);
        let xored: u64 = word ^ REQ_SWAR_LF_MASK;
        let has_match: u64 = xored.wrapping_sub(REQ_SWAR_LO_ONES) & !xored & REQ_SWAR_HI_BITS;
        if has_match != 0 {
            let bit_index: usize = if cfg!(target_endian = "little") {
                has_match.trailing_zeros() as usize
            } else {
                has_match.leading_zeros() as usize
            };
            return Some(index + (bit_index >> 3));
        }
        index += 8;
    }
    while index < len {
        if bytes[index] == b'\n' {
            return Some(index);
        }
        index += 1;
    }
    None
}

/// Locate `\r\n\r\n` (end of response headers) starting at `start`.
///
/// # Arguments
///
/// - `&[u8]` - The buffer to search.
/// - `usize` - The offset at which the search starts.
///
/// # Returns
///
/// - `Option<usize>`: The absolute offset of the terminator, or `None` when absent.
pub(crate) fn find_double_crlf(data: &[u8], start: usize) -> Option<usize> {
    let len: usize = data.len();
    if len.saturating_sub(start) < 4 {
        return None;
    }
    let mut pos: usize = start + 1;
    while pos + 2 < len {
        let rel: usize = find_lf_swar(&data[pos..len - 2])?;
        let lf_idx: usize = pos + rel;
        if data[lf_idx - 1] == b'\r' && data[lf_idx + 1] == b'\r' && data[lf_idx + 2] == b'\n' {
            return Some(lf_idx - 1);
        }
        pos = lf_idx + 1;
    }
    None
}

/// Find a byte-pattern in a haystack, ASCII-case-insensitive.
///
/// # Arguments
///
/// - `&[u8]` - The haystack to search.
/// - `&[u8]` - The byte pattern to look for.
///
/// # Returns
///
/// - `Option<usize>`: The offset of the first match, or `None` when absent.
#[cfg(test)]
pub(crate) fn find_pattern_case_insensitive(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || haystack.len() < needle.len() {
        return None;
    }
    let needle_len: usize = needle.len();
    let search_len: usize = haystack.len() - needle_len + 1;
    let first_needle_lower: u8 = needle[0].to_ascii_lowercase();
    'outer: for i in 0..search_len {
        if haystack[i].to_ascii_lowercase() != first_needle_lower {
            continue;
        }
        for j in 1..needle_len {
            if !haystack[i + j].eq_ignore_ascii_case(&needle[j]) {
                continue 'outer;
            }
        }
        return Some(i);
    }
    None
}

/// Locate the next `\r\n` after `start`.
///
/// # Arguments
///
/// - `&[u8]` - The buffer to search.
/// - `usize` - The offset at which the search starts.
///
/// # Returns
///
/// - `Option<usize>`: The absolute offset of the terminator, or `None` when absent.
pub(crate) fn find_crlf(data: &[u8], start: usize) -> Option<usize> {
    let len: usize = data.len();
    if len.saturating_sub(start) < 2 {
        return None;
    }
    let mut pos: usize = start + 1;
    while pos < len {
        let rel: usize = find_lf_swar(&data[pos..])?;
        let lf_idx: usize = pos + rel;
        if data[lf_idx - 1] == b'\r' {
            return Some(lf_idx - 1);
        }
        pos = lf_idx + 1;
    }
    None
}

/// Extract `Content-Length` from the response fields, distinguishing absence from zero.
///
/// # Arguments
///
/// - `&[u8]` - The raw response header bytes.
///
/// # Returns
///
/// - `Result<Option<usize>, RequestError>` - The declared length, absence, or invalid framing.
#[cfg(test)]
pub(crate) fn get_content_length(response_bytes: &[u8]) -> Result<Option<usize>, RequestError> {
    let value: Option<&[u8]> = response_header_value(
        response_bytes,
        &CONTENT_LENGTH_PATTERN[..CONTENT_LENGTH_PATTERN.len() - 1],
    )?;
    match value {
        Some(bytes) => {
            let length: usize = parse_decimal_bytes(bytes)?;
            if length > isize::MAX as usize {
                return Err(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
            }
            Ok(Some(length))
        }
        None => Ok(None),
    }
}

/// Determine whether the response has exactly one supported transfer coding.
///
/// # Arguments
///
/// - `&[u8]` - The raw response headers, optionally followed by a body.
///
/// # Returns
///
/// - `Result<bool, RequestError>` - Whether chunked framing is present, or an error for unsupported coding.
#[cfg(test)]
pub(crate) fn is_chunked_encoding(headers_bytes: &[u8]) -> Result<bool, RequestError> {
    let name: &[u8] = &TRANSFER_ENCODING_PATTERN[..TRANSFER_ENCODING_PATTERN.len() - 1];
    match response_header_value(headers_bytes, name)? {
        Some(value) if value.eq_ignore_ascii_case(CHUNKED_PATTERN) => Ok(true),
        Some(_) => Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned())),
        None => Ok(false),
    }
}

/// Parse a nonempty sequence of decimal digits without truncation or overflow.
///
/// # Arguments
///
/// - `&[u8]` - The ASCII decimal digits, without surrounding whitespace.
///
/// # Returns
///
/// - `Result<usize, RequestError>` - The exact length, or an error for invalid digits or overflow.
pub(crate) fn parse_decimal_bytes(bytes: &[u8]) -> Result<usize, RequestError> {
    if bytes.is_empty()
        || !bytes
            .iter()
            .all(|byte: &u8| (ASCII_ZERO..=ASCII_NINE).contains(byte))
    {
        return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
    }
    let mut result: usize = 0;
    for &byte in bytes {
        result = result
            .checked_mul(10)
            .and_then(|value: usize| value.checked_add((byte - ASCII_ZERO) as usize))
            .ok_or(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest))?;
    }
    Ok(result)
}

/// Check an HTTP field name against the nonempty RFC token grammar.
///
/// # Arguments
///
/// - `&[u8]` - The field name bytes.
///
/// # Returns
///
/// - `bool` - Whether every byte is an allowed token character.
#[inline(always)]
pub(crate) fn is_valid_header_name(name: &[u8]) -> bool {
    !name.is_empty()
        && name
            .iter()
            .all(|byte: &u8| HEADER_NAME_TOKEN_TABLE[usize::from(*byte)])
}

/// Validates an HTTP header name and reports whether all ASCII letters are already lowercase.
///
/// # Arguments
///
/// - `&[u8]` - Candidate header name bytes.
///
/// # Returns
///
/// - `Option<bool>` - `Some(true)` if valid and already lowercase, `Some(false)` if valid with uppercase, or `None` if invalid.
#[inline(always)]
pub(crate) fn validate_header_name_lower(name: &[u8]) -> Option<bool> {
    if name.is_empty() {
        return None;
    }
    let mut has_upper: bool = false;
    for &byte in name {
        if !HEADER_NAME_TOKEN_TABLE[usize::from(byte)] {
            return None;
        }
        if byte.is_ascii_uppercase() {
            has_upper = true;
        }
    }
    Some(!has_upper)
}

/// Check a field value for forbidden control bytes, permitting horizontal tabs.
///
/// Uses an 8-byte SWAR fast path for printable ASCII slices (`0x20..=0x7E`) of length `>= 8`.
///
/// # Arguments
///
/// - `&[u8]` - The field value bytes.
///
/// # Returns
///
/// - `bool` - Whether the value can be serialized as one header line.
#[inline(always)]
pub(crate) fn is_valid_header_value(value: &[u8]) -> bool {
    let len: usize = value.len();
    let mut idx: usize = 0;
    if len >= 8 {
        while idx + 8 <= len {
            let chunk: [u8; 8] = [
                value[idx],
                value[idx + 1],
                value[idx + 2],
                value[idx + 3],
                value[idx + 4],
                value[idx + 5],
                value[idx + 6],
                value[idx + 7],
            ];
            let word: u64 = u64::from_le_bytes(chunk);
            let non_printable: u64 = (word
                | word.wrapping_sub(0x2020_2020_2020_2020)
                | word.wrapping_add(REQ_SWAR_LO_ONES))
                & REQ_SWAR_HI_BITS;
            if non_printable != 0 {
                for &byte in &chunk {
                    if byte.is_ascii_control() && byte != TAB_U8 {
                        return false;
                    }
                }
            }
            idx += 8;
        }
    }
    while idx < len {
        let byte: u8 = value[idx];
        if byte.is_ascii_control() && byte != TAB_U8 {
            return false;
        }
        idx += 1;
    }
    true
}

/// Validate every outgoing field before opening a stream or serializing headers.
///
/// # Arguments
///
/// - `&HashMap<String, String>` - The caller-provided header map, with arbitrary key casing.
///
/// # Returns
///
/// - `Result<(), RequestError>` - Success for valid fields, or an error before bytes can be sent.
pub(crate) fn validate_request_headers(
    headers: &HashMap<String, String>,
) -> Result<(), RequestError> {
    for (name, value) in headers {
        if !is_valid_header_name(name.as_bytes()) || !is_valid_header_value(value.as_bytes()) {
            return Err(RequestError::Request(INVALID_REQUEST_HEADER.to_owned()));
        }
    }
    Ok(())
}

/// Validate every header field line in `headers_bytes` and optionally extract `field_name`.
///
/// # Arguments
///
/// - `&'a [u8]` - The header or trailer block bytes.
/// - `&[u8]` - The exact field name without its colon (or empty to validate only).
/// - `bool` - Whether line 0 may be an HTTP status line starting with `HTTP/`.
///
/// # Returns
///
/// - `Result<Option<&'a [u8]>, RequestError>` - The trimmed value, absence, or framing error.
pub(crate) fn validate_header_block<'a>(
    headers_bytes: &'a [u8],
    field_name: &[u8],
    skip_status_line: bool,
) -> Result<Option<&'a [u8]>, RequestError> {
    let mut value: Option<&[u8]> = None;
    let mut pos: usize = 0;
    while pos < headers_bytes.len() {
        let end: usize = find_crlf(headers_bytes, pos).unwrap_or(headers_bytes.len());
        let line: &[u8] = &headers_bytes[pos..end];
        if line.is_empty() {
            break;
        }
        if !(skip_status_line && pos == 0 && line.starts_with(HTTP_STATUS_PREFIX)) {
            let separator: usize = line
                .iter()
                .position(|byte: &u8| *byte == COLON_U8)
                .ok_or_else(|| RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()))?;
            let name: &[u8] = &line[..separator];
            let raw_value: &[u8] = &line[separator + 1..];
            if !is_valid_header_name(name) || !is_valid_header_value(raw_value) {
                return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
            }
            if !field_name.is_empty() && name.eq_ignore_ascii_case(field_name) {
                if value.is_some() {
                    return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
                }
                value = Some(raw_value.trim_ascii());
            }
        }
        if end == headers_bytes.len() {
            break;
        }
        pos = end + HTTP_BR_BYTES.len();
    }
    Ok(value)
}

/// Look up one complete field name, stopping at the header/body boundary.
///
/// # Arguments
///
/// - `&'a [u8]` - The response header block, optionally followed by body bytes.
/// - `&[u8]` - The exact field name without its colon.
///
/// # Returns
///
/// - `Result<Option<&'a [u8]>, RequestError>` - The trimmed value, absence, or invalid or duplicate fields.
#[cfg(test)]
pub(crate) fn response_header_value<'a>(
    headers_bytes: &'a [u8],
    field_name: &[u8],
) -> Result<Option<&'a [u8]>, RequestError> {
    validate_header_block(headers_bytes, field_name, true)
}

/// Parse the 3-byte ASCII status code from the response status line.
///
/// # Arguments
///
/// - `&[u8]` - The status-line bytes following the HTTP version.
///
/// # Returns
///
/// - `usize`: The status code, or `0` when the slice is not three digits.
pub(crate) fn parse_status_code(status_bytes: &[u8]) -> usize {
    if status_bytes.len() != 3 {
        return 0;
    }
    let mut result: usize = 0;
    for &byte in status_bytes {
        if byte.is_ascii_digit() {
            result = result * 10 + (byte - ASCII_ZERO) as usize;
        } else {
            return 0;
        }
    }
    result
}

/// Calculate the next buffer capacity for growing the response buffer.
///
/// # Arguments
///
/// - `&[u8]` - The response bytes accumulated so far.
/// - `usize` - The number of bytes just read.
/// - `usize` - The current capacity of the response buffer.
///
/// # Returns
///
/// - `usize`: The new capacity to reserve, or `0` when no growth is needed.
pub(crate) fn calculate_buffer_capacity(
    response_bytes: &[u8],
    n: usize,
    current_capacity: usize,
) -> usize {
    let needed_cap: usize = response_bytes.len().saturating_add(n);
    if needed_cap <= current_capacity {
        return 0;
    }
    if current_capacity == 0 {
        needed_cap.max(1024)
    } else if needed_cap <= current_capacity.saturating_mul(2) {
        current_capacity.saturating_mul(2)
    } else {
        needed_cap.saturating_add(needed_cap / 2)
    }
}

/// Resolve HTTP/1 response framing from a complete field section.
///
/// For HEAD, framing fields are representation metadata (RFC 9112 §6.3).
///
/// # Arguments
///
/// - `&[u8]` - The raw response header bytes.
/// - `bool` - Whether the response answers a HEAD request.
///
/// # Returns
///
/// - `Result<Option<ResponseHeadFields>, RequestError>` - The final framing and redirect, or `None` for an interim response.
#[cfg(test)]
pub(crate) fn parse_response_headers(
    headers_bytes: &[u8],
    is_head: bool,
) -> Result<Option<ResponseHeadFields>, RequestError> {
    let status_start: usize = HTTP_STATUS_CODE_OFFSET;
    let status_code: usize = headers_bytes
        .get(status_start..status_start + 3)
        .map_or(0, parse_status_code);
    if headers_bytes
        .get(..HTTP_STATUS_PREFIX.len())
        .is_none_or(|prefix: &[u8]| {
            find_pattern_case_insensitive(prefix, HTTP_STATUS_PREFIX).is_none()
        })
        || headers_bytes.get(status_start - 1) != Some(&SPACE_U8)
        || !(100..=599).contains(&status_code)
        || !matches!(headers_bytes.get(status_start + 3), Some(b' ' | b'\r'))
    {
        return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
    }
    let is_redirect_status: bool = [301, 302, 303, 307, 308].contains(&status_code);
    let cl_name: &[u8] = &CONTENT_LENGTH_PATTERN[..CONTENT_LENGTH_PATTERN.len() - 1];
    let te_name: &[u8] = &TRANSFER_ENCODING_PATTERN[..TRANSFER_ENCODING_PATTERN.len() - 1];
    let loc_name: &[u8] = LOCATION.as_bytes();
    let mut cl_raw: Option<&[u8]> = None;
    let mut te_raw: Option<&[u8]> = None;
    let mut loc_raw: Option<&[u8]> = None;
    let mut pos: usize = 0;
    while pos < headers_bytes.len() {
        let end: usize = find_crlf(headers_bytes, pos).unwrap_or(headers_bytes.len());
        let line: &[u8] = &headers_bytes[pos..end];
        if line.is_empty() {
            break;
        }
        if !(pos == 0 && line.starts_with(HTTP_STATUS_PREFIX)) {
            let separator: usize = line
                .iter()
                .position(|byte: &u8| *byte == COLON_U8)
                .ok_or_else(|| RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()))?;
            let name: &[u8] = &line[..separator];
            let raw_value: &[u8] = &line[separator + 1..];
            if !is_valid_header_name(name) || !is_valid_header_value(raw_value) {
                return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
            }
            if !is_head && name.eq_ignore_ascii_case(cl_name) {
                if cl_raw.is_some() {
                    return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
                }
                cl_raw = Some(raw_value.trim_ascii());
            } else if !is_head && name.eq_ignore_ascii_case(te_name) {
                if te_raw.is_some() {
                    return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
                }
                te_raw = Some(raw_value.trim_ascii());
            } else if is_redirect_status && name.eq_ignore_ascii_case(loc_name) {
                if loc_raw.is_some() {
                    return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
                }
                loc_raw = Some(raw_value.trim_ascii());
            }
        }
        if end == headers_bytes.len() {
            break;
        }
        pos = end + HTTP_BR_BYTES.len();
    }
    let framing: ResponseFraming = if is_head {
        ResponseFraming::Fixed(0)
    } else {
        let length: Option<usize> = match cl_raw {
            Some(bytes) => {
                let parsed: usize = parse_decimal_bytes(bytes)?;
                if parsed > isize::MAX as usize {
                    return Err(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
                }
                Some(parsed)
            }
            None => None,
        };
        let chunked: bool = match te_raw {
            Some(value) if value.eq_ignore_ascii_case(CHUNKED_PATTERN) => true,
            Some(_) => return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned())),
            None => false,
        };
        match (length, chunked) {
            (Some(_), true) => {
                return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
            }
            (None, true) => ResponseFraming::Chunked,
            (Some(length), false) => {
                if length > MAX_RESPONSE_BODY_BYTES {
                    return Err(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
                }
                ResponseFraming::Fixed(length)
            }
            (None, false) => ResponseFraming::Close,
        }
    };
    if status_code == HttpStatus::SwitchingProtocols.code()
        || status_code == HttpStatus::NoContent.code()
        || status_code == HttpStatus::ResetContent.code()
        || status_code == HttpStatus::NotModified.code()
    {
        return Ok(Some((ResponseFraming::Fixed(0), None)));
    }
    if status_code < HttpStatus::Ok.code() {
        return Ok(None);
    }
    let redirect: Option<Vec<u8>> = loc_raw.map(<[u8]>::to_vec);
    Ok(Some((framing, redirect)))
}

/// Parses, validates, and extracts framing, keep-alive, and response headers in a single pass.
///
/// Eliminates redundant scans for header validation, `Connection` inspection, and `HttpResponse`
/// map construction on every HTTP/1 response.
///
/// # Arguments
///
/// - `&[u8]` - Raw response header block up to and including `\r\n\r\n`.
/// - `usize` - Byte length of the head block (`head_end`).
/// - `bool` - Whether this response answers a `HEAD` request.
///
/// # Returns
///
/// - `Result<Option<ParsedFinalHead>, RequestError>` - Parsed final head, or `None` for `1xx` interim responses.
pub(crate) fn parse_final_response_head(
    headers_bytes: &[u8],
    head_end: usize,
    is_head: bool,
) -> Result<Option<ParsedFinalHead>, RequestError> {
    let status_start: usize = HTTP_STATUS_CODE_OFFSET;
    let status_code: usize = headers_bytes
        .get(status_start..status_start + 3)
        .map_or(0, parse_status_code);
    if headers_bytes
        .get(..HTTP_STATUS_PREFIX.len())
        .is_none_or(|prefix: &[u8]| !prefix.eq_ignore_ascii_case(HTTP_STATUS_PREFIX))
        || headers_bytes.get(status_start - 1) != Some(&SPACE_U8)
        || !(100..=599).contains(&status_code)
        || !matches!(headers_bytes.get(status_start + 3), Some(b' ' | b'\r'))
    {
        return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
    }
    let status_line_end: usize = find_crlf(headers_bytes, 0).unwrap_or(headers_bytes.len());
    let is_interim: bool =
        status_code < HttpStatus::Ok.code() && status_code != HttpStatus::SwitchingProtocols.code();
    let is_bodyless: bool = status_code == HttpStatus::SwitchingProtocols.code()
        || status_code == HttpStatus::NoContent.code()
        || status_code == HttpStatus::ResetContent.code()
        || status_code == HttpStatus::NotModified.code();
    let is_redirect_status: bool = [301, 302, 303, 307, 308].contains(&status_code);
    let version_bytes: &[u8] = &headers_bytes[..status_start - 1];
    let is_http_1_0: bool = version_bytes == HTTP_VERSION_1_0.as_bytes();
    let version: HttpVersion = if version_bytes == HTTP_VERSION_1_1.as_bytes() {
        HttpVersion::Http1_1
    } else if is_http_1_0 {
        HttpVersion::Http1_0
    } else if version_bytes == HTTP_VERSION_2.as_bytes() {
        HttpVersion::Http2
    } else {
        from_utf8(version_bytes)
            .ok()
            .and_then(|v: &str| v.parse::<HttpVersion>().ok())
            .unwrap_or_default()
    };
    let cl_name: &[u8] = &CONTENT_LENGTH_PATTERN[..CONTENT_LENGTH_PATTERN.len() - 1];
    let te_name: &[u8] = &TRANSFER_ENCODING_PATTERN[..TRANSFER_ENCODING_PATTERN.len() - 1];
    let loc_name: &[u8] = LOCATION.as_bytes();
    let conn_name: &[u8] = CONNECTION.as_bytes();
    let mut cl_raw: Option<&[u8]> = None;
    let mut te_raw: Option<&[u8]> = None;
    let mut loc_raw: Option<&[u8]> = None;
    let mut saw_close: bool = false;
    let mut saw_keep_alive: bool = false;
    let mut pos: usize = if status_line_end < headers_bytes.len() {
        status_line_end + HTTP_BR_BYTES.len()
    } else {
        headers_bytes.len()
    };
    let mut headers: HashMapXxHash3_64<String, String> = if !is_interim
        && pos < headers_bytes.len()
        && !headers_bytes[pos..].starts_with(HTTP_BR_BYTES)
    {
        HashMap::with_capacity_and_hasher(4, BuildHasherDefault::default())
    } else {
        new_response_headers()
    };
    while pos < headers_bytes.len() {
        let end: usize = find_crlf(headers_bytes, pos).unwrap_or(headers_bytes.len());
        let line: &[u8] = &headers_bytes[pos..end];
        if line.is_empty() {
            break;
        }
        let separator: usize = line
            .iter()
            .position(|byte: &u8| *byte == COLON_U8)
            .ok_or_else(|| RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()))?;
        let name: &[u8] = &line[..separator];
        let raw_value: &[u8] = &line[separator + 1..];
        let Some(already_lower) = validate_header_name_lower(name) else {
            return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
        };
        if !is_valid_header_value(raw_value) {
            return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
        }
        let trimmed_value: &[u8] = raw_value.trim_ascii();
        match name.len() {
            14 if !is_head && name.eq_ignore_ascii_case(cl_name) => {
                if cl_raw.is_some() {
                    return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
                }
                cl_raw = Some(trimmed_value);
            }
            17 if !is_head && name.eq_ignore_ascii_case(te_name) => {
                if te_raw.is_some() {
                    return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
                }
                te_raw = Some(trimmed_value);
            }
            8 if is_redirect_status && name.eq_ignore_ascii_case(loc_name) => {
                if loc_raw.is_some() {
                    return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
                }
                loc_raw = Some(trimmed_value);
            }
            10 if !is_interim && name.eq_ignore_ascii_case(conn_name) => {
                for token in trimmed_value.split(|b: &u8| *b == COMMA_U8) {
                    let tok: &[u8] = token.trim_ascii();
                    if tok.eq_ignore_ascii_case(CLOSE.as_bytes()) {
                        saw_close = true;
                    } else if tok.eq_ignore_ascii_case(KEEP_ALIVE.as_bytes()) {
                        saw_keep_alive = true;
                    }
                }
            }
            _ => {}
        }
        if !is_interim
            && separator > 0
            && separator + 1 < line.len()
            && let (Ok(key_str), Ok(val_str)) = (from_utf8(name), from_utf8(trimmed_value))
        {
            let key_owned: String = if already_lower {
                key_str.to_owned()
            } else {
                key_str.to_ascii_lowercase()
            };
            if key_owned == SET_COOKIE
                && let Some(existing) = headers.get_mut(SET_COOKIE)
            {
                existing.push(SET_COOKIE_DELIMITER);
                existing.push_str(val_str);
            } else {
                headers.insert(key_owned, val_str.to_owned());
            }
        }
        if end == headers_bytes.len() {
            break;
        }
        pos = end + HTTP_BR_BYTES.len();
    }
    let framing: ResponseFraming = if is_head {
        ResponseFraming::Fixed(0)
    } else {
        let length: Option<usize> = match cl_raw {
            Some(bytes) => {
                let parsed: usize = parse_decimal_bytes(bytes)?;
                if parsed > isize::MAX as usize {
                    return Err(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
                }
                Some(parsed)
            }
            None => None,
        };
        let chunked: bool = match te_raw {
            Some(value) if value.eq_ignore_ascii_case(CHUNKED_PATTERN) => true,
            Some(_) => return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned())),
            None => false,
        };
        match (length, chunked) {
            (Some(_), true) => {
                return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
            }
            (None, true) => ResponseFraming::Chunked,
            (Some(length), false) => {
                if length > MAX_RESPONSE_BODY_BYTES {
                    return Err(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
                }
                ResponseFraming::Fixed(length)
            }
            (None, false) => ResponseFraming::Close,
        }
    };
    if is_interim {
        return Ok(None);
    }
    let final_framing: ResponseFraming = if is_bodyless {
        ResponseFraming::Fixed(0)
    } else {
        framing
    };
    let reason_start: usize = (status_start + 3).min(status_line_end);
    let reason_bytes: &[u8] = headers_bytes[reason_start..status_line_end].trim_ascii();
    let reason_phrase: String = if reason_bytes.is_empty() {
        HttpStatus::Unknown.to_string()
    } else if reason_bytes == b"OK" {
        "OK".to_owned()
    } else {
        let needs_ws_collapse: bool = reason_bytes.windows(2).any(|pair: &[u8]| {
            pair[0] == TAB_U8 || pair[1] == TAB_U8 || (pair[0] == SPACE_U8 && pair[1] == SPACE_U8)
        }) || reason_bytes[0] == TAB_U8;
        if !needs_ws_collapse && let Ok(reason_str) = from_utf8(reason_bytes) {
            reason_str.to_owned()
        } else {
            let mut result: String = String::with_capacity(reason_bytes.len());
            let mut r_pos: usize = 0;
            let mut first_word: bool = true;
            while r_pos < reason_bytes.len() {
                while r_pos < reason_bytes.len()
                    && (reason_bytes[r_pos] == SPACE_U8 || reason_bytes[r_pos] == TAB_U8)
                {
                    r_pos += 1;
                }
                let w_start: usize = r_pos;
                while r_pos < reason_bytes.len()
                    && reason_bytes[r_pos] != SPACE_U8
                    && reason_bytes[r_pos] != TAB_U8
                {
                    r_pos += 1;
                }
                if r_pos > w_start {
                    if !first_word {
                        result.push(' ');
                    }
                    first_word = false;
                    result.push_str(&String::from_utf8_lossy(&reason_bytes[w_start..r_pos]));
                }
            }
            result
        }
    };
    let allows_keep_alive: bool =
        final_framing != ResponseFraming::Close && !saw_close && (!is_http_1_0 || saw_keep_alive);
    let redirect_url: Option<Vec<u8>> = if is_bodyless {
        None
    } else {
        loc_raw.map(<[u8]>::to_vec)
    };
    Ok(Some(ParsedFinalHead {
        head_end,
        framing: final_framing,
        redirect_url,
        allows_keep_alive,
        version,
        status_code,
        reason_phrase,
        headers,
    }))
}

/// Finds and parses the final response head in one pass, discarding any preceding `1xx` interim heads.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Accumulated response bytes.
/// - `usize` - Earliest position where a new `\r\n\r\n` terminator could start.
/// - `bool` - Whether the response answers a `HEAD` request.
/// - `&mut usize` - Running count of `1xx` interim responses already discarded.
///
/// # Returns
///
/// - `Result<Option<ParsedFinalHead>, RequestError>` - Fully parsed final head, or `None` when more bytes are needed.
pub(crate) fn find_parsed_final_head(
    bytes: &mut Vec<u8>,
    mut search_start: usize,
    is_head: bool,
    interim_count: &mut usize,
) -> Result<Option<ParsedFinalHead>, RequestError> {
    let mut start: usize = 0;
    while let Some(position) = find_double_crlf(bytes, search_start) {
        let end: usize = position + HTTP_BR_BYTES.len() * 2;
        if end.saturating_sub(start) > MAX_RESPONSE_HEAD_BYTES {
            return Err(RequestError::Request(RESPONSE_TOO_LARGE.to_owned()));
        }
        if let Some(parsed) = parse_final_response_head(&bytes[start..end], end - start, is_head)? {
            if start != 0 {
                drop(bytes.drain(..start));
            }
            return Ok(Some(parsed));
        }
        *interim_count += 1;
        if *interim_count > MAX_INTERIM_RESPONSES {
            return Err(RequestError::Request(TOO_MANY_INTERIM_RESPONSES.to_owned()));
        }
        start = end;
        search_start = end;
    }
    if start != 0 {
        drop(bytes.drain(..start));
    }
    if bytes.len() > MAX_RESPONSE_HEAD_BYTES {
        return Err(RequestError::Request(RESPONSE_TOO_LARGE.to_owned()));
    }
    Ok(None)
}