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
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
use super::*;
/// Implements the `std::error::Error` trait for `RequestError`.
impl Error for RequestError {}
/// Provides a default value for `RequestError`.
impl Default for RequestError {
/// Provides a default value for `RequestError`.
///
/// Returns a `RequestError::Unknown` with `HttpStatus::InternalServerError`.
#[inline(always)]
fn default() -> Self {
RequestError::Unknown(HttpStatus::InternalServerError)
}
}
/// Converts an I/O error to a `RequestError`.
///
/// Maps connection reset and aborted errors to `ClientDisconnected`,
/// all other I/O errors are mapped to `ReadConnection`.
impl From<io::Error> for RequestError {
/// Converts an I/O error to a `RequestError`.
///
/// # Arguments
///
/// - `io::Error` - The I/O error to convert.
///
/// # Returns
///
/// - `RequestError` - The corresponding request error.
#[inline(always)]
fn from(error: io::Error) -> Self {
let kind: ErrorKind = error.kind();
if kind == ErrorKind::ConnectionReset || kind == ErrorKind::ConnectionAborted {
return RequestError::ClientDisconnected(HttpStatus::BadRequest);
}
RequestError::ReadConnection(HttpStatus::BadRequest)
}
}
/// Converts a timeout elapsed error to a `RequestError`.
///
/// Maps timeout errors to `ReadTimeout` with `HttpStatus::RequestTimeout`.
impl From<Elapsed> for RequestError {
/// Converts a timeout elapsed error to a `RequestError`.
///
/// # Arguments
///
/// - `Elapsed` - The elapsed error to convert.
///
/// # Returns
///
/// - `RequestError` - The corresponding request error as `ReadTimeout`.
#[inline(always)]
fn from(_: Elapsed) -> Self {
RequestError::ReadTimeout(HttpStatus::RequestTimeout)
}
}
/// Converts a parse int error to a `RequestError`.
///
/// Maps parse int errors to `InvalidContentLength` with `HttpStatus::BadRequest`.
impl From<ParseIntError> for RequestError {
/// Converts a parse int error to a `RequestError`.
///
/// # Arguments
///
/// - `ParseIntError` - The parse error to convert.
///
/// # Returns
///
/// - `RequestError` - The corresponding request error as `InvalidContentLength`.
#[inline(always)]
fn from(_: ParseIntError) -> Self {
RequestError::InvalidContentLength(HttpStatus::BadRequest)
}
}
/// Converts a response error to a `RequestError`.
///
/// Maps response errors to `WriteTimeout` with `HttpStatus::InternalServerError`.
impl From<ResponseError> for RequestError {
/// Converts a response error to a `RequestError`.
///
/// # Arguments
///
/// - `ResponseError` - The response error to convert.
///
/// # Returns
///
/// - `RequestError` - The corresponding request error as `WriteTimeout`.
#[inline(always)]
fn from(_: ResponseError) -> Self {
RequestError::WriteTimeout(HttpStatus::InternalServerError)
}
}
/// Inherent implementation of [`RequestError`].
impl RequestError {
/// Gets the HTTP status associated with this error.
///
/// Returns the HttpStatus enum variant that corresponds to this error.
///
/// # Returns
///
/// - `HttpStatus` - The HTTP status associated with this error.
pub fn get_http_status(&self) -> HttpStatus {
match self {
Self::HttpRead(status) => *status,
Self::GetTcpStream(status) => *status,
Self::GetTlsStream(status) => *status,
Self::ReadConnection(status) => *status,
Self::RequestAborted(status) => *status,
Self::TlsStreamConnect(status) => *status,
Self::NeedOpenRedirect(status) => *status,
Self::MaxRedirectTimes(status) => *status,
Self::MethodsNotSupport(status) => *status,
Self::RedirectInvalidUrl(status) => *status,
Self::ClientDisconnected(status) => *status,
Self::RedirectUrlDeadLoop(status) => *status,
Self::ClientClosedConnection(status) => *status,
Self::ServerClosedConnection(status) => *status,
Self::IncompleteWebSocketFrame(status) => *status,
Self::RequestTooLong(status) => *status,
Self::PathTooLong(status) => *status,
Self::QueryTooLong(status) => *status,
Self::HeaderLineTooLong(status) => *status,
Self::TooManyHeaders(status) => *status,
Self::HeaderKeyTooLong(status) => *status,
Self::HeaderValueTooLong(status) => *status,
Self::ContentLengthTooLarge(status) => *status,
Self::InvalidContentLength(status) => *status,
Self::InvalidUrlScheme(status) => *status,
Self::InvalidUrlHost(status) => *status,
Self::InvalidUrlPort(status) => *status,
Self::InvalidUrlPath(status) => *status,
Self::InvalidUrlQuery(status) => *status,
Self::InvalidUrlFragment(status) => *status,
Self::ReadTimeout(status) => *status,
Self::WriteTimeout(status) => *status,
Self::TcpConnectionFailed(status) => *status,
Self::TlsHandshakeFailed(status) => *status,
Self::TlsCertificateInvalid(status) => *status,
Self::WebSocketFrameTooLarge(status) => *status,
Self::WebSocketOpcodeUnsupported(status) => *status,
Self::WebSocketMaskMissing(status) => *status,
Self::WebSocketPayloadCorrupted(status) => *status,
Self::WebSocketInvalidUtf8(status) => *status,
Self::WebSocketInvalidCloseCode(status) => *status,
Self::WebSocketInvalidExtension(status) => *status,
Self::HttpRequestPartsInsufficient(status) => *status,
Self::TcpStreamConnect(status) => *status,
Self::TlsConnectorBuild(status) => *status,
Self::InvalidUrl(status) => *status,
Self::ConfigReadError(status) => *status,
Self::TcpStreamConnectString(status) => *status,
Self::TlsConnectorBuildString(status) => *status,
Self::Request(_) => HttpStatus::BadRequest,
Self::Unknown(status) => *status,
}
}
/// Gets the numeric HTTP status code associated with this error.
///
/// Returns the numeric status code (e.g., 400, 404, 500) that corresponds to this error.
///
/// # Returns
///
/// - `ResponseStatusCode` - The numeric HTTP status code.
pub fn get_http_status_code(&self) -> ResponseStatusCode {
self.get_http_status().code()
}
}
/// Implementation of `Default` trait for `RequestConfig`.
impl Default for RequestConfig {
/// Creates a new `RequestConfig` with default secure settings.
///
/// This constructor initializes the configuration with standard security limits
/// suitable for most HTTP request parsing scenarios.
///
/// # Returns
///
/// - `Self` - A new `RequestConfig` instance with default settings.
#[inline(always)]
fn default() -> Self {
Self {
buffer_size: DEFAULT_BUFFER_SIZE,
max_path_size: DEFAULT_MAX_PATH_SIZE,
max_header_count: DEFAULT_MAX_HEADER_COUNT,
max_header_key_size: DEFAULT_MAX_HEADER_KEY_SIZE,
max_header_value_size: DEFAULT_MAX_HEADER_VALUE_SIZE,
max_body_size: DEFAULT_MAX_BODY_SIZE,
read_timeout_ms: DEFAULT_READ_TIMEOUT_MS,
}
}
}
/// Inherent implementation of [`RequestConfig`].
impl RequestConfig {
/// Creates a new `RequestConfig` from a JSON string.
///
/// # Arguments
///
/// - `C` - The configuration, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// - `Result<RequestConfig, serde_json::Error>` - The parsed `RequestConfig` or an error.
pub fn from_json<C>(json: C) -> Result<RequestConfig, serde_json::Error>
where
C: AsRef<str>,
{
from_str(json.as_ref())
}
/// Creates a new `RequestConfig` with low-security settings.
///
/// This constructor initializes the configuration with less restrictive limits
/// for environments where higher limits are needed.
///
/// # Returns
///
/// - `Self` - A new `RequestConfig` instance with low-security settings.
#[inline(always)]
pub fn low_security() -> Self {
Self {
buffer_size: DEFAULT_LOW_SECURITY_BUFFER_SIZE,
max_path_size: DEFAULT_LOW_SECURITY_MAX_PATH_SIZE,
max_header_count: DEFAULT_LOW_SECURITY_MAX_HEADER_COUNT,
max_header_key_size: DEFAULT_LOW_SECURITY_MAX_HEADER_KEY_SIZE,
max_header_value_size: DEFAULT_LOW_SECURITY_MAX_HEADER_VALUE_SIZE,
max_body_size: DEFAULT_LOW_SECURITY_MAX_BODY_SIZE,
read_timeout_ms: DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS,
}
}
/// Creates a new `RequestConfig` with high-security settings.
///
/// This constructor initializes the configuration with more restrictive limits
/// to provide maximum protection against various attacks in high-risk environments.
///
/// # Returns
///
/// - `Self` - A new `RequestConfig` instance with high-security settings.
#[inline(always)]
pub fn high_security() -> Self {
Self {
buffer_size: DEFAULT_HIGH_SECURITY_BUFFER_SIZE,
max_path_size: DEFAULT_HIGH_SECURITY_MAX_PATH_SIZE,
max_header_count: DEFAULT_HIGH_SECURITY_MAX_HEADER_COUNT,
max_header_key_size: DEFAULT_HIGH_SECURITY_MAX_HEADER_KEY_SIZE,
max_header_value_size: DEFAULT_HIGH_SECURITY_MAX_HEADER_VALUE_SIZE,
max_body_size: DEFAULT_HIGH_SECURITY_MAX_BODY_SIZE,
read_timeout_ms: DEFAULT_HIGH_SECURITY_READ_TIMEOUT_MS,
}
}
}
/// Provides a default value for `Request`.
///
/// Returns a new `Request` instance with all fields initialized to their default values.
impl Default for Request {
/// Builds the default `Request` with all fields set to their defaults.
#[inline(always)]
fn default() -> Self {
Self {
method: Method::default(),
host: String::new(),
version: HttpVersion::default(),
path: String::new(),
querys: hash_map_xx_hash3_64(),
headers: hash_map_xx_hash3_64(),
body: Vec::new(),
}
}
}
/// Inherent implementation of [`Request`].
impl Request {
/// Resets the request to its default state while retaining allocated capacity.
///
/// This keeps the header map, query map, body, and string allocations so
/// persistent (keep-alive) connections avoid repeated allocation per request.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
pub fn reset(&mut self) -> &mut Self {
self.set_method(Method::default());
self.get_mut_host().clear();
self.set_version(HttpVersion::default());
self.get_mut_path().clear();
self.recycle_querys();
self.recycle_headers();
self.get_mut_body().clear();
self
}
/// Hands the query entries to the pool and empties the query map.
fn recycle_querys(&mut self) {
let querys: &mut RequestQuerys = self.get_mut_querys();
if querys.is_empty() {
return;
}
return_header_entries(querys.drain());
}
/// Hands the header entries to the pool and empties the header map.
///
/// The map ends up empty, exactly as clearing it would, but the name and
/// the value buffers of every header survive in the pool. The next
/// request on the same connection takes them back and overwrites them,
/// so a connection that keeps its headers stops allocating for them.
///
/// # Returns
///
/// - `()` - The headers have been recycled.
fn recycle_headers(&mut self) {
let headers: &mut RequestHeaders = self.get_mut_headers();
if headers.is_empty() {
return;
}
return_header_entries(headers.drain());
}
/// Parses the first line of HTTP request into method, path, and version components.
///
/// # Arguments
///
/// - `&str` - The first line string of HTTP request to parse.
///
/// # Returns
///
/// - `Result<(RequestMethod, &str, RequestVersion), RequestError>` - A tuple containing:
/// - The parsed HTTP method
/// - The full path string
/// - The parsed HTTP version
/// - Or an error if parsing fails
#[inline(always)]
pub(crate) fn get_http_first_line(
line: &str,
) -> Result<(RequestMethod, &str, RequestVersion), RequestError> {
let (method_str, full_path, version_str): (&str, &str, &str) = if line.is_ascii() {
let bytes: &[u8] = line.as_bytes();
let mut idx: usize = 0;
let len: usize = bytes.len();
while idx < len && bytes[idx].is_ascii_whitespace() {
idx += 1;
}
let m_start: usize = idx;
while idx < len && !bytes[idx].is_ascii_whitespace() {
idx += 1;
}
if m_start == idx {
return Err(RequestError::HttpRequestPartsInsufficient(
HttpStatus::BadRequest,
));
}
let m_end: usize = idx;
while idx < len && bytes[idx].is_ascii_whitespace() {
idx += 1;
}
let p_start: usize = idx;
while idx < len && !bytes[idx].is_ascii_whitespace() {
idx += 1;
}
if p_start == idx {
return Err(RequestError::HttpRequestPartsInsufficient(
HttpStatus::BadRequest,
));
}
let p_end: usize = idx;
while idx < len && bytes[idx].is_ascii_whitespace() {
idx += 1;
}
let v_start: usize = idx;
while idx < len && !bytes[idx].is_ascii_whitespace() {
idx += 1;
}
if v_start == idx {
return Err(RequestError::HttpRequestPartsInsufficient(
HttpStatus::BadRequest,
));
}
let v_end: usize = idx;
while idx < len && bytes[idx].is_ascii_whitespace() {
idx += 1;
}
if idx != len {
return Err(RequestError::HttpRequestPartsInsufficient(
HttpStatus::BadRequest,
));
}
(
&line[m_start..m_end],
&line[p_start..p_end],
&line[v_start..v_end],
)
} else {
let mut parts: SplitWhitespace<'_> = line.split_whitespace();
let method_str: &str =
parts
.next()
.ok_or(RequestError::HttpRequestPartsInsufficient(
HttpStatus::BadRequest,
))?;
let full_path: &str =
parts
.next()
.ok_or(RequestError::HttpRequestPartsInsufficient(
HttpStatus::BadRequest,
))?;
let version_str: &str =
parts
.next()
.ok_or(RequestError::HttpRequestPartsInsufficient(
HttpStatus::BadRequest,
))?;
if parts.next().is_some() {
return Err(RequestError::HttpRequestPartsInsufficient(
HttpStatus::BadRequest,
));
}
(method_str, full_path, version_str)
};
let method: RequestMethod = match method_str.as_bytes() {
WIRE_METHOD_GET => Method::Get,
WIRE_METHOD_POST => Method::Post,
WIRE_METHOD_PUT => Method::Put,
WIRE_METHOD_DELETE => Method::Delete,
WIRE_METHOD_HEAD => Method::Head,
WIRE_METHOD_OPTIONS => Method::Options,
WIRE_METHOD_PATCH => Method::Patch,
WIRE_METHOD_CONNECT => Method::Connect,
WIRE_METHOD_TRACE => Method::Trace,
_ => Method::Unknown(method_str.to_owned()),
};
let version: RequestVersion = match version_str.as_bytes() {
WIRE_VERSION_1_1 => HttpVersion::Http1_1,
WIRE_VERSION_1_0 => HttpVersion::Http1_0,
WIRE_VERSION_0_9 => HttpVersion::Http0_9,
WIRE_VERSION_2 => HttpVersion::Http2,
WIRE_VERSION_3 => HttpVersion::Http3,
_ => match version_str.parse::<RequestVersion>() {
Ok(RequestVersion::Unknown(_)) | Err(_) => {
return Err(RequestError::HttpRequestPartsInsufficient(
HttpStatus::BadRequest,
));
}
Ok(version) => version,
},
};
Ok((method, full_path, version))
}
/// Validates the path length against the maximum allowed size.
///
/// # Arguments
///
/// - `&str` - The path string to check.
/// - `usize` - The maximum allowed path size.
///
/// # Returns
///
/// - `Result<(), RequestError>` - Ok if valid, or an error if the path is too long.
#[inline(always)]
pub(crate) fn check_http_path_size(path: &str, max_size: usize) -> Result<(), RequestError> {
if path.len() > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
return Err(RequestError::PathTooLong(HttpStatus::URITooLong));
}
Ok(())
}
/// Parses the query string from the full path.
///
/// Handles both query parameters (after `?`) and hash fragments (after `#`),
/// ensuring proper parsing when both are present.
///
/// # Arguments
///
/// - `&str` - The full path string containing the query.
/// - `Option<usize>` - The index of the query separator (`?`), if present.
/// - `Option<usize>` - The index of the hash separator (`#`), if present.
///
/// # Returns
///
/// - `&str` - The parsed query string slice, or empty string if no query.
#[inline(always)]
pub(crate) fn get_http_query(
path: &str,
query_index: Option<usize>,
hash_index: Option<usize>,
) -> &str {
query_index.map_or(EMPTY_STR, |query_index: usize| {
let temp: &str = &path[query_index + 1..];
match hash_index {
None => temp,
Some(hash_index) if hash_index <= query_index => temp,
Some(hash_index) => &temp[..hash_index - query_index - 1],
}
})
}
/// Parses the request path without query string or hash fragment.
///
/// # Arguments
///
/// - `&str` - The full path string.
/// - `Option<usize>` - The index of the query separator (`?`), if present.
/// - `Option<usize>` - The index of the hash separator (`#`), if present.
///
/// # Returns
///
/// - `&str` - The request path slice without query or hash.
#[inline(always)]
pub(crate) fn get_http_path(
path: &str,
query_index: Option<usize>,
hash_index: Option<usize>,
) -> &str {
match query_index.or(hash_index) {
Some(separator_index) => &path[..separator_index],
None => path,
}
}
/// Parses a query string as_ref key-value pairs into the given map.
///
/// Expects format "key1=value1&key2=value2". Empty values are allowed, and a
/// key that repeats keeps every value instead of letting the last one win.
/// The target map is expected to be empty; entries are inserted without
/// reallocating the map when it already has sufficient capacity.
///
/// # Arguments
///
/// - `&str` - The query string to parse.
/// - `&mut RequestQuerys` - The map to insert parsed parameters into.
#[inline(always)]
pub(crate) fn fill_http_querys(query: &str, querys: &mut RequestQuerys) {
if query.is_empty() {
return;
}
for pair in query.split(AND) {
if let Some((key, value)) = pair.split_once(EQUAL) {
if !key.is_empty() {
if let Some(existing) = querys.get_mut(key) {
existing.push_back(value.to_owned());
} else {
let (mut pooled_key, mut pooled_values): (String, VecDeque<String>) =
take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
pooled_key.clear();
pooled_key.push_str(key);
while pooled_values.len() > 1 {
pooled_values.pop_back();
}
if let Some(slot) = pooled_values.front_mut() {
slot.clear();
slot.push_str(value);
} else {
pooled_values.push_back(value.to_owned());
}
querys.insert(pooled_key, pooled_values);
}
}
} else if !pair.is_empty() && !querys.contains_key(pair) {
let (mut pooled_key, mut pooled_values): (String, VecDeque<String>) =
take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
pooled_key.clear();
pooled_key.push_str(pair);
pooled_values.clear();
querys.insert(pooled_key, pooled_values);
}
}
}
/// Checks if the header count exceeds the maximum allowed.
///
/// # Arguments
///
/// - `usize` - The current number of headers parsed.
/// - `usize` - The maximum allowed number of headers.
///
/// # Returns
///
/// - `Result<(), RequestError>` - Returns an error if the limit is exceeded and not in low security mode.
#[inline(always)]
pub(crate) fn check_http_header_count(
count: usize,
max_count: usize,
) -> Result<(), RequestError> {
if count > max_count && max_count != DEFAULT_LOW_SECURITY_MAX_HEADER_COUNT {
return Err(RequestError::TooManyHeaders(
HttpStatus::RequestHeaderFieldsTooLarge,
));
}
Ok(())
}
/// Checks if a header key exceeds the maximum allowed length.
///
/// # Arguments
///
/// - `&str` - The header key to check.
/// - `usize` - The maximum allowed length for a header key.
///
/// # Returns
///
/// - `Result<(), RequestError>` - Returns an error if the limit is exceeded and not in low security mode.
#[inline(always)]
pub(crate) fn check_http_header_key_size(
key: &str,
max_size: usize,
) -> Result<(), RequestError> {
if key.len() > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_HEADER_KEY_SIZE {
return Err(RequestError::HeaderKeyTooLong(
HttpStatus::RequestHeaderFieldsTooLarge,
));
}
Ok(())
}
/// Checks if a header value exceeds the maximum allowed length.
///
/// # Arguments
///
/// - `&str` - The header value to check.
/// - `usize` - The maximum allowed length for a header value.
///
/// # Returns
///
/// - `Result<(), RequestError>` - Returns an error if the limit is exceeded and not in low security mode.
#[inline(always)]
pub(crate) fn check_http_header_value_size(
value: &str,
max_size: usize,
) -> Result<(), RequestError> {
if value.len() > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_HEADER_VALUE_SIZE {
return Err(RequestError::HeaderValueTooLong(
HttpStatus::RequestHeaderFieldsTooLarge,
));
}
Ok(())
}
/// Parses the Content-Length header value and checks it against max body size.
///
/// # Arguments
///
/// - `&str` - The Content-Length header value string.
/// - `usize` - The maximum allowed body size.
///
/// # Returns
///
/// - `Result<usize, RequestError>` - The parsed content length or an error.
#[inline(always)]
pub(crate) fn check_http_body_size(
value: &str,
max_size: usize,
) -> Result<usize, RequestError> {
if value.is_empty() || !value.bytes().all(|byte: u8| byte.is_ascii_digit()) {
return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
}
let length: usize = value.parse::<usize>()?;
if length > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE {
return Err(RequestError::ContentLengthTooLarge(
HttpStatus::PayloadTooLarge,
));
}
Ok(length)
}
/// Parses a complete HTTP/1.1 request head (request line and all headers)
/// directly from an already-buffered byte slice without per-line copying.
///
/// Returns `Ok(None)` when the buffered slice does not yet contain the
/// terminating blank line, leaving the caller to fall back to incremental
/// line reads without losing any bytes.
///
/// # Arguments
///
/// - `&[u8]` - The buffered unread bytes from the stream.
/// - `&RequestConfig` - Security limits for path, headers and body.
/// - `&mut String` - The stream's request-line buffer populated for downstream inspection.
///
/// # Returns
///
/// - `Result<Option<(RequestFraming, usize)>, RequestError>` - The framing and
/// number of bytes consumed when a full head was parsed, `None` when more
/// input is required, or a protocol error.
pub(crate) fn parse_http_head_from_slice(
&mut self,
buffer: &[u8],
config: &RequestConfig,
line_buffer: &mut String,
) -> Result<Option<(RequestFraming, usize)>, RequestError> {
let Some(first_lf) = buffer.iter().position(|byte: &u8| *byte == BR_U8) else {
return Ok(None);
};
let first_line_end: usize = first_lf + 1;
let first_line: &str = match from_utf8(&buffer[..first_line_end]) {
Ok(text) => text,
Err(_) => return Err(RequestError::ReadConnection(HttpStatus::BadRequest)),
};
line_buffer.clear();
line_buffer.push_str(first_line);
let (method, full_path, version): (RequestMethod, &str, RequestVersion) =
Self::get_http_first_line(first_line)?;
Self::check_http_path_size(full_path, config.get_max_path_size())?;
let hash_index: Option<usize> = full_path.find(HASH);
let query_index: Option<usize> = full_path.find(QUERY);
let query: &str = Self::get_http_query(full_path, query_index, hash_index);
Self::fill_http_querys(query, self.get_mut_querys());
let path_slice: &str = Self::get_http_path(full_path, query_index, hash_index);
self.get_mut_path().push_str(path_slice);
self.set_version(version);
self.set_method(method);
let Request {
headers,
host,
version,
..
} = self;
let max_header_count: usize = config.get_max_header_count();
let max_header_key_size: usize = config.get_max_header_key_size();
let max_header_value_size: usize = config.get_max_header_value_size();
let max_body_size: usize = config.get_max_body_size();
let mut content_size: usize = 0;
let mut header_count: usize = 0;
let mut content_length_seen: bool = false;
let mut transfer_encoding_seen: bool = false;
let mut host_seen: bool = false;
let mut pos: usize = first_line_end;
let mut incomplete_head: bool = false;
let header_result: Result<(), RequestError> = HEADER_ENTRY_POOL.with(
|pool: &RefCell<Vec<(String, VecDeque<String>)>>| -> Result<(), RequestError> {
let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
loop {
let rest: &[u8] = &buffer[pos..];
let Some(rel_lf) = rest.iter().position(|byte: &u8| *byte == BR_U8) else {
incomplete_head = true;
return Ok(());
};
let line_end: usize = pos + rel_lf;
let raw_line: &[u8] = if line_end > pos && buffer[line_end - 1] == b'\r' {
&buffer[pos..line_end - 1]
} else {
&buffer[pos..line_end]
};
pos = line_end + 1;
if raw_line.is_empty() {
break;
}
let first_byte: u8 = raw_line[0];
if first_byte == SPACE_U8 || first_byte == TAB_U8 {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
header_count += 1;
Self::check_http_header_count(header_count, max_header_count)?;
let Some(colon_pos) = raw_line.iter().position(|byte: &u8| *byte == COLON_U8)
else {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
};
let key_bytes: &[u8] = &raw_line[..colon_pos];
if key_bytes.is_empty() {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
let mut has_upper: bool = false;
for &byte in key_bytes {
if !HTTP_HEADER_TOKEN_TABLE[byte as usize] {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
if byte.is_ascii_uppercase() {
has_upper = true;
}
}
// SAFETY: Every byte passed `HTTP_HEADER_TOKEN_TABLE`, which only accepts ASCII (< 0x80).
let key: &str = unsafe { from_utf8_unchecked(key_bytes) };
Self::check_http_header_key_size(key, max_header_key_size)?;
let raw_val: &[u8] = &raw_line[colon_pos + 1..];
let mut val_non_ascii: u8 = 0;
for &byte in raw_val {
if !HTTP_HEADER_VALUE_VALID_TABLE[byte as usize] {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
val_non_ascii |= byte & 0x80;
}
let mut val_start: usize = 0;
let mut val_end: usize = raw_val.len();
while val_start < val_end
&& (raw_val[val_start] == SPACE_U8 || raw_val[val_start] == TAB_U8)
{
val_start += 1;
}
while val_end > val_start
&& (raw_val[val_end - 1] == SPACE_U8 || raw_val[val_end - 1] == TAB_U8)
{
val_end -= 1;
}
let value: &str = if val_non_ascii == 0 {
// SAFETY: `val_non_ascii == 0` guarantees every byte in `raw_val` is ASCII (< 0x80).
unsafe { from_utf8_unchecked(&raw_val[val_start..val_end]) }
} else {
match from_utf8(&raw_val[val_start..val_end]) {
Ok(text) => text,
Err(_) => {
return Err(RequestError::ReadConnection(HttpStatus::BadRequest));
}
}
};
Self::check_http_header_value_size(value, max_header_value_size)?;
match key.len() {
4 if key.eq_ignore_ascii_case(HOST) => {
if host_seen {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
host_seen = true;
host.clear();
host.push_str(value);
}
14 if key.eq_ignore_ascii_case(CONTENT_LENGTH) => {
if transfer_encoding_seen {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
if content_length_seen {
return Err(RequestError::InvalidContentLength(
HttpStatus::BadRequest,
));
}
content_length_seen = true;
content_size = Self::check_http_body_size(value, max_body_size)?;
}
17 if key.eq_ignore_ascii_case(HTTP_HEADER_TRANSFER_ENCODING) => {
if *version != HTTP_HOST_REQUIRED_VERSION || content_length_seen {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
transfer_encoding_seen = true;
}
_ => {}
}
Self::insert_http_header_from_pool(headers, &mut pool, key, has_upper, value);
}
Ok(())
},
);
header_result?;
if incomplete_head {
self.reset();
line_buffer.clear();
return Ok(None);
}
if *version == HTTP_HOST_REQUIRED_VERSION && !host_seen {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
if transfer_encoding_seen {
let values: &RequestHeadersValue = headers
.get(HTTP_HEADER_TRANSFER_ENCODING)
.ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
return Ok(Some((r#fn::parse_transfer_encoding(values)?, pos)));
}
Ok(Some((RequestFraming::Fixed(content_size), pos)))
}
/// Parses HTTP headers from a buffered reader into this request.
///
/// This method reads header lines from the provided buffered reader until an empty line
/// is encountered, which indicates the end of headers. It checks header count, length,
/// and content according to the provided configuration. The request's headers map and
/// host string are expected to be empty; they are filled without reallocating when they
/// already have sufficient capacity.
///
/// The line buffer belongs to the caller so that a keep-alive connection
/// reads every header line of every request into the same allocation.
///
/// # Arguments
///
/// - `&mut R` - A mutable reference to a buffered reader, which requires the
/// `AsyncBufReadExt + Unpin` bound.
/// - `&RequestConfig` - Configuration for security limits and buffer settings.
/// - `&mut String` - The buffer the header lines are read into.
///
/// # Returns
///
/// - `Result<RequestFraming, RequestError>` - The body framing, or an error if parsing fails.
pub(crate) async fn get_http_headers<R>(
&mut self,
reader: &mut R,
config: &RequestConfig,
header_line_buffer: &mut String,
) -> Result<RequestFraming, RequestError>
where
R: AsyncBufReadExt + Unpin,
{
let Request {
headers,
host,
version,
..
} = self;
let max_header_count: usize = config.get_max_header_count();
let max_header_key_size: usize = config.get_max_header_key_size();
let max_header_value_size: usize = config.get_max_header_value_size();
let max_body_size: usize = config.get_max_body_size();
let mut content_size: usize = 0;
let mut header_count: usize = 0;
let mut content_length_seen: bool = false;
let mut transfer_encoding_seen: bool = false;
let mut host_seen: bool = false;
loop {
header_line_buffer.clear();
AsyncBufReadExt::read_line(reader, header_line_buffer).await?;
let header_line: &str = header_line_buffer
.strip_suffix(HTTP_HEADER_LINE_FEED)
.ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
let header_line: &str = header_line
.strip_suffix(HTTP_HEADER_CARRIAGE_RETURN)
.unwrap_or(header_line);
if header_line.is_empty() {
break;
}
if header_line.starts_with(HTTP_HEADER_OPTIONAL_WHITESPACE) {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
header_count += 1;
Self::check_http_header_count(header_count, max_header_count)?;
let (key, value_part): (&str, &str) = header_line
.split_once(COLON)
.ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
let valid_key: bool = key.bytes().all(|byte: u8| {
byte.is_ascii_alphanumeric() || HTTP_HEADER_TOKEN_PUNCTUATION.contains(&byte)
});
if key.is_empty() || !valid_key {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
Self::check_http_header_key_size(key, max_header_key_size)?;
if value_part.bytes().any(|byte: u8| {
(byte < HTTP_HEADER_CONTROL_LIMIT && byte != HTTP_HEADER_TAB)
|| byte == HTTP_HEADER_DELETE
}) {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
let value: &str = value_part.trim_matches(HTTP_HEADER_OPTIONAL_WHITESPACE);
Self::check_http_header_value_size(value, max_header_value_size)?;
match key {
key if key.eq_ignore_ascii_case(HTTP_HEADER_TRANSFER_ENCODING) => {
if *version != HTTP_HOST_REQUIRED_VERSION || content_length_seen {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
transfer_encoding_seen = true;
}
key if key.eq_ignore_ascii_case(HOST) => {
if host_seen {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
host_seen = true;
host.clear();
host.push_str(value);
}
key if key.eq_ignore_ascii_case(CONTENT_LENGTH) => {
if transfer_encoding_seen {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
if content_length_seen {
return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
}
content_length_seen = true;
content_size = Self::check_http_body_size(value, max_body_size)?;
}
_ => {}
}
Self::insert_http_header(headers, key, value);
}
if *version == HTTP_HOST_REQUIRED_VERSION && !host_seen {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
if transfer_encoding_seen {
let values: &RequestHeadersValue = headers
.get(HTTP_HEADER_TRANSFER_ENCODING)
.ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
return r#fn::parse_transfer_encoding(values);
}
Ok(RequestFraming::Fixed(content_size))
}
/// Replaces wire chunk framing with the decoded content length.
#[cold]
pub(crate) fn normalize_chunked_headers(&mut self) {
let mut digits: [u8; B_20] = [0; B_20];
let length: &str = render_length(self.get_body().len(), &mut digits);
let headers: &mut RequestHeaders = self.get_mut_headers();
headers.remove(HTTP_HEADER_TRANSFER_ENCODING);
headers.remove(HTTP_HEADER_TRAILER);
Self::insert_http_header(headers, CONTENT_LENGTH, length);
}
/// Stores one ASCII header using an already-borrowed worker-local entry pool.
///
/// # Arguments
///
/// - `&mut RequestHeaders` - The header map to store the header in.
/// - `&mut Vec<(String, VecDeque<String>)>` - Borrowed worker-local header entry pool.
/// - `&str` - The validated ASCII header name, as it arrived.
/// - `bool` - Whether `key` contains any ASCII uppercase character.
/// - `&str` - The header value.
#[inline(always)]
fn insert_http_header_from_pool(
headers: &mut RequestHeaders,
pool: &mut Vec<(String, VecDeque<String>)>,
key: &str,
has_upper: bool,
value: &str,
) {
if !has_upper {
if let Some(existing) = headers.get_mut(key) {
existing.push_back(value.to_owned());
return;
}
let (mut name, mut values): (String, VecDeque<String>) = pool
.pop()
.unwrap_or_else(|| (String::new(), VecDeque::new()));
name.clear();
name.push_str(key);
while values.len() > 1 {
values.pop_back();
}
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value);
} else {
values.push_back(value.to_owned());
}
headers.insert(name, values);
return;
}
if key.len() <= STACK_HEADER_KEY_LIMIT {
let mut stack_buf: [MaybeUninit<u8>; STACK_HEADER_KEY_LIMIT] =
[const { MaybeUninit::uninit() }; STACK_HEADER_KEY_LIMIT];
let key_bytes: &[u8] = key.as_bytes();
let mut idx: usize = 0;
while idx < key_bytes.len() {
stack_buf[idx].write(key_bytes[idx].to_ascii_lowercase());
idx += 1;
}
// SAFETY: `key` is validated ASCII (< 0x80), lowercasing preserves ASCII, and
// `0..key_bytes.len()` elements of `stack_buf` were initialized above.
let lower: &str = unsafe {
from_utf8_unchecked(slice::from_raw_parts(
stack_buf.as_ptr().cast::<u8>(),
key_bytes.len(),
))
};
if let Some(existing) = headers.get_mut(lower) {
existing.push_back(value.to_owned());
return;
}
let (mut name, mut values): (String, VecDeque<String>) = pool
.pop()
.unwrap_or_else(|| (String::new(), VecDeque::new()));
name.clear();
name.push_str(lower);
while values.len() > 1 {
values.pop_back();
}
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value);
} else {
values.push_back(value.to_owned());
}
headers.insert(name, values);
return;
}
let (mut name, mut values): (String, VecDeque<String>) = pool
.pop()
.unwrap_or_else(|| (String::new(), VecDeque::new()));
name.clear();
for ch in key.chars() {
name.push(ch.to_ascii_lowercase());
}
if let Some(existing) = headers.get_mut(&name) {
existing.push_back(value.to_owned());
if name.capacity() <= MAX_POOLED_HEADER_STRING_CAPACITY
&& values.capacity() <= MAX_POOLED_HEADER_VALUE_CAPACITY
&& pool.len() < MAX_POOLED_HEADER_ENTRIES
{
pool.push((name, values));
}
return;
}
while values.len() > 1 {
values.pop_back();
}
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value);
} else {
values.push_back(value.to_owned());
}
headers.insert(name, values);
}
/// Stores one header, reusing a pooled name and value where possible.
///
/// The name is lowercased into the buffer of a recycled entry and the
/// value is written into that entry's value buffer, so a header that was
/// already seen on this connection costs no allocation at all.
///
/// # Arguments
///
/// - `&mut RequestHeaders` - The header map to store the header in.
/// - `&str` - The header name, as it arrived.
/// - `&str` - The header value.
fn insert_http_header(headers: &mut RequestHeaders, key: &str, value: &str) {
let (mut name, mut values): (String, VecDeque<String>) =
take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
name.clear();
name.push_str(key);
name.make_ascii_lowercase();
match headers.entry(name) {
Entry::Occupied(mut occupied) => {
// The header repeats: it keeps every value it was given.
occupied.get_mut().push_back(value.to_string());
return_header_entry((String::new(), values));
}
Entry::Vacant(vacant) => {
// A recycled entry may carry the values of a header that was
// sent more than once. Those values belong to that header, so
// only the first one is kept and the rest are dropped.
while values.len() > 1 {
values.pop_back();
}
if values.is_empty() {
values.push_back(String::new());
}
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value);
}
vacant.insert(values);
}
}
}
/// Reads the request body from the buffered reader into the given buffer.
///
/// The target buffer is cleared and resized to the expected content size,
/// retaining its allocation when it already has sufficient capacity.
///
/// # Arguments
///
/// - `&mut R` - The buffered reader to read from, which requires the `AsyncRead + Unpin` bound.
/// - `&mut RequestBody` - The buffer to read the body bytes into.
/// - `usize` - The expected content size.
///
/// # Returns
///
/// - `Result<(), RequestError>` - Ok on success, or an error if reading fails.
#[inline(always)]
pub(crate) async fn fill_http_body<R>(
reader: &mut R,
body: &mut RequestBody,
content_size: usize,
) -> Result<(), RequestError>
where
R: AsyncRead + Unpin,
{
body.clear();
if content_size > 0 {
body.resize(content_size, 0);
AsyncReadExt::read_exact(reader, body).await?;
}
Ok(())
}
/// Tries to get a query parameter by key.
///
/// The key type must implement `AsRef<str>` conversion. A key that repeats in
/// the query carries every one of its values.
///
/// # Arguments
///
/// - `K` - The query parameter key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `Option<RequestQuerysValue>` - Every value of the parameter if it exists.
#[inline(always)]
pub fn try_get_query<K>(&self, key: K) -> Option<RequestQuerysValue>
where
K: AsRef<str>,
{
self.get_querys().get(key.as_ref()).cloned()
}
/// Tries to get the first query parameter value by key.
///
/// Use this when the parameter is expected to appear once; use
/// `try_get_query` when every value matters.
///
/// # Arguments
///
/// - `K` - The query parameter key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `Option<RequestQuerysValueItem>` - The first parameter value if it exists.
#[inline(always)]
pub fn try_get_query_front<K>(&self, key: K) -> Option<RequestQuerysValueItem>
where
K: AsRef<str>,
{
self.get_querys()
.get(key.as_ref())
.and_then(|values: &VecDeque<String>| values.front().cloned())
}
/// Tries to get the last query parameter value by key.
///
/// # Arguments
///
/// - `K` - The query parameter key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `Option<RequestQuerysValueItem>` - The last parameter value if it exists.
#[inline(always)]
pub fn try_get_query_back<K>(&self, key: K) -> Option<RequestQuerysValueItem>
where
K: AsRef<str>,
{
self.get_querys()
.get(key.as_ref())
.and_then(|values: &VecDeque<String>| values.back().cloned())
}
/// Tries to get the number of values of a query parameter.
///
/// # Arguments
///
/// - `K` - The query parameter key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `Option<usize>` - The number of values if the parameter exists.
#[inline(always)]
pub fn try_get_query_size<K>(&self, key: K) -> Option<usize>
where
K: AsRef<str>,
{
self.get_querys()
.get(key.as_ref())
.map(|values: &VecDeque<String>| values.len())
}
/// Checks whether a query parameter exists.
///
/// # Arguments
///
/// - `K` - The query parameter key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `bool` - Whether the parameter exists.
#[inline(always)]
pub fn has_query<K>(&self, key: K) -> bool
where
K: AsRef<str>,
{
self.get_querys().contains_key(key.as_ref())
}
/// Gets a query parameter by key.
///
/// # Arguments
///
/// - `K` - The query parameter key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `RequestQuerysValue` - Every value of the parameter.
///
/// # Panics
///
/// This function will panic if the query parameter key is not found.
#[inline(always)]
pub fn get_query<K>(&self, key: K) -> RequestQuerysValue
where
K: AsRef<str>,
{
self.try_get_query(key).unwrap()
}
/// Gets the first query parameter value by key.
///
/// # Arguments
///
/// - `K` - The query parameter key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `RequestQuerysValueItem` - The first parameter value.
///
/// # Panics
///
/// This function will panic if the query parameter key is not found.
#[inline(always)]
pub fn get_query_front<K>(&self, key: K) -> RequestQuerysValueItem
where
K: AsRef<str>,
{
self.try_get_query_front(key).unwrap()
}
/// Retrieves the number of query parameters.
///
/// # Returns
///
/// - `usize` - The count of distinct query parameter keys.
#[inline(always)]
pub fn get_querys_size(&self) -> usize {
self.get_querys().len()
}
/// Looks up a header value list case-insensitively without allocating when
/// the key is already lowercase or fits in the stack buffer.
///
/// # Arguments
///
/// - `&str` - The header name to look up.
///
/// # Returns
///
/// - `Option<&RequestHeadersValue>` - Reference to the stored values, if present.
#[inline(always)]
fn get_header_ref(&self, key: &str) -> Option<&RequestHeadersValue> {
let bytes: &[u8] = key.as_bytes();
if !bytes.iter().any(|byte: &u8| byte.is_ascii_uppercase()) {
return self.get_headers().get(key);
}
if bytes.len() <= STACK_HEADER_KEY_LIMIT {
let mut stack_buf: [u8; STACK_HEADER_KEY_LIMIT] = [0; STACK_HEADER_KEY_LIMIT];
let mut idx: usize = 0;
while idx < bytes.len() {
stack_buf[idx] = bytes[idx].to_ascii_lowercase();
idx += 1;
}
if let Ok(lower) = from_utf8(&stack_buf[..bytes.len()]) {
return self.get_headers().get(lower);
}
}
self.get_headers().get(&key.to_ascii_lowercase())
}
/// Tries to retrieve the value of a request header by its key.
///
/// The key is matched case-insensitively, because the parser stores every
/// header name lowercased and an HTTP header name is case-insensitive by
/// specification. Looking a header up with `Content-Type` and with
/// `content-type` therefore find the same value.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `Option<RequestHeadersValue>` - The optional header values.
#[inline(always)]
pub fn try_get_header<K>(&self, key: K) -> Option<RequestHeadersValue>
where
K: AsRef<str>,
{
self.get_header_ref(key.as_ref()).cloned()
}
/// Retrieves the value of a request header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `RequestHeadersValue` - The optional header values.
///
/// # Panics
///
/// This function will panic if the header key is not found.
#[inline(always)]
pub fn get_header<K>(&self, key: K) -> RequestHeadersValue
where
K: AsRef<str>,
{
self.try_get_header(key).unwrap()
}
/// Tries to retrieve the first value of a request header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `Option<RequestHeadersValueItem>` - The first header value if exists.
#[inline(always)]
pub fn try_get_header_front<K>(&self, key: K) -> Option<RequestHeadersValueItem>
where
K: AsRef<str>,
{
self.get_header_ref(key.as_ref())
.and_then(|header_values: &VecDeque<String>| header_values.front().cloned())
}
/// Retrieves the first value of a request header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `RequestHeadersValueItem` - The first header value if exists.
///
/// # Panics
///
/// This function will panic if the header key is not found.
#[inline(always)]
pub fn get_header_front<K>(&self, key: K) -> RequestHeadersValueItem
where
K: AsRef<str>,
{
self.try_get_header_front(key).unwrap()
}
/// Tries to retrieve the last value of a request header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `Option<RequestHeadersValueItem>` - The last header value if exists.
#[inline(always)]
pub fn try_get_header_back<K>(&self, key: K) -> Option<RequestHeadersValueItem>
where
K: AsRef<str>,
{
self.get_header_ref(key.as_ref())
.and_then(|header_values: &VecDeque<String>| header_values.back().cloned())
}
/// Retrieves the last value of a request header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `RequestHeadersValueItem` - The last header value if exists.
///
/// # Panics
///
/// This function will panic if the header key is not found.
#[inline(always)]
pub fn get_header_back<K>(&self, key: K) -> RequestHeadersValueItem
where
K: AsRef<str>,
{
self.try_get_header_back(key).unwrap()
}
/// Tries to retrieve the number of values for a specific header.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `Option<usize>` - The count of values for the header if exists.
#[inline(always)]
pub fn try_get_header_size<K>(&self, key: K) -> Option<usize>
where
K: AsRef<str>,
{
self.get_header_ref(key.as_ref())
.map(|header_values: &VecDeque<String>| header_values.len())
}
/// Retrieves the number of values for a specific header.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `usize` - The count of values for the header.
///
/// # Panics
///
/// This function will panic if the header key is not found.
#[inline(always)]
pub fn get_header_size<K>(&self, key: K) -> usize
where
K: AsRef<str>,
{
self.try_get_header_size(key).unwrap()
}
/// Retrieves the total number of header values across all headers.
///
/// # Returns
///
/// - `usize` - The total count of all header values.
#[inline(always)]
pub fn get_headers_values_size(&self) -> usize {
self.get_headers()
.values()
.map(|header_values: &VecDeque<String>| header_values.len())
.sum()
}
/// Retrieves the number of unique headers.
///
/// # Returns
///
/// - `usize` - The count of unique header keys.
#[inline(always)]
pub fn get_headers_size(&self) -> usize {
self.get_headers().len()
}
/// Checks if a specific header exists.
///
/// # Arguments
///
/// - `K` - The header key to check, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `bool` - Whether the header exists.
#[inline(always)]
pub fn has_header<K>(&self, key: K) -> bool
where
K: AsRef<str>,
{
self.get_header_ref(key.as_ref()).is_some()
}
/// Checks if a header contains a specific value.
///
/// # Arguments
///
/// - `K` - The header key to check, which must implement `AsRef<str>`.
/// - `V` - The value to search for, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `bool` - Whether the header contains the value.
#[inline(always)]
pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
where
K: AsRef<str>,
V: AsRef<str>,
{
if let Some(values) = self.get_header_ref(key.as_ref()) {
values.iter().any(|data: &String| data == value.as_ref())
} else {
false
}
}
/// Checks `If-None-Match` against the entity-tag of an existing representation.
///
/// This explicitly invoked helper borrows normalized request headers and allocates nothing.
/// Strong and weak tags use case-sensitive weak comparison of their opaque values.
/// Repeated fields form one list; optional spaces, tabs, and empty list members are ignored.
/// A wildcard matches only when the entire field combination is a standalone `*`.
/// Missing headers, empty lists, invalid tags, or any malformed suffix return `false`,
/// even if an earlier tag matched. The current tag must be exactly one valid entity-tag,
/// without surrounding whitespace. Quoted commas and empty opaque values are valid;
/// backslashes are literal bytes, not escape characters.
///
/// Call only for a representation that already exists. This does not send a response,
/// automatically generate a 304, or implement complete HTTP precondition evaluation.
/// Callers decide whether to send 304 for GET/HEAD or 412 for other methods and must
/// handle precondition ordering themselves. Do not use this for `If-Match`, which
/// requires strong comparison.
///
/// # Arguments
///
/// - `&str` - The current representation's complete strong or weak entity-tag.
///
/// # Returns
///
/// - `bool` - Whether a completely valid `If-None-Match` matches the existing representation.
#[must_use]
pub fn matches_if_none_match(&self, current_etag: &str) -> bool {
let current: &[u8] = match r#fn::parse_entity_tag(current_etag.as_bytes()) {
Some((opaque, [])) => opaque,
_ => return false,
};
let values: &RequestHeadersValue = match self.get_headers().get(IF_NONE_MATCH) {
Some(values) => values,
None => return false,
};
if values.len() == 1
&& values.front().is_some_and(|value: &String| {
value
.trim_matches(&HTTP_HEADER_OPTIONAL_WHITESPACE[..])
.as_bytes()
== ENTITY_TAG_WILDCARD
})
{
return true;
}
let mut matched: bool = false;
for value in values {
let mut remaining: &[u8] = value.as_bytes();
while !remaining.is_empty() {
while remaining
.first()
.is_some_and(|byte: &u8| ENTITY_TAG_LIST_PADDING.contains(byte))
{
remaining = &remaining[1..];
}
if remaining.is_empty() {
break;
}
let (candidate, suffix): (&[u8], &[u8]) = match r#fn::parse_entity_tag(remaining) {
Some(parsed) => parsed,
None => return false,
};
matched |= candidate == current;
remaining = suffix;
while remaining
.first()
.is_some_and(|byte: &u8| ENTITY_TAG_OPTIONAL_WHITESPACE.contains(byte))
{
remaining = &remaining[1..];
}
if remaining.is_empty() {
break;
}
if remaining.first() != Some(&ENTITY_TAG_SEPARATOR) {
return false;
}
remaining = &remaining[1..];
}
}
matched
}
/// Tries to parse cookies from the `Cookie` header.
///
/// This method retrieves the `Cookie` header value and parses it into
/// a collection of key-value pairs representing the cookies.
///
/// # Returns
///
/// - `Option<Cookies>` - The parsed cookies if the header exists, otherwise `None`.
#[inline(always)]
pub fn try_get_cookies(&self) -> Option<Cookies> {
self.try_get_header_back(COOKIE)
.map(|cookie_header: String| Cookie::parse(cookie_header))
}
/// Parses cookies from the `Cookie` header.
///
/// This method retrieves the `Cookie` header value and parses it into
/// a collection of key-value pairs representing the cookies.
///
/// # Returns
///
/// - `Cookies` - The parsed cookies.
///
/// # Panics
///
/// This function will panic if the `Cookie` header is not found.
#[inline(always)]
pub fn get_cookies(&self) -> Cookies {
self.try_get_cookies().unwrap()
}
/// Tries to get a cookie value by its key.
///
/// This method first parses the cookies from the `Cookie` header,
/// then attempts to retrieve the value for the specified key.
///
/// # Arguments
///
/// - `K` - The cookie key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `Option<CookieValue>` - The cookie value if exists.
#[inline(always)]
pub fn try_get_cookie<K>(&self, key: K) -> Option<CookieValue>
where
K: AsRef<str>,
{
self.try_get_cookies()
.and_then(|cookies: Cookies| cookies.get(key.as_ref()).cloned())
}
/// Gets a cookie value by its key.
///
/// This method first parses the cookies from the `Cookie` header,
/// then retrieves the value for the specified key.
///
/// # Arguments
///
/// - `K` - The cookie key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `CookieValue` - The cookie value.
///
/// # Panics
///
/// This function will panic if the `Cookie` header is not found
/// or the cookie key does not exist.
#[inline(always)]
pub fn get_cookie<K>(&self, key: K) -> CookieValue
where
K: AsRef<str>,
{
self.try_get_cookie(key).unwrap()
}
/// Retrieves the upgrade type from the request headers.
///
/// This method looks for the `UPGRADE` header and attempts to parse its value
/// as_ref an `UpgradeType`. If the header is missing or the value is invalid,
/// it returns the default `UpgradeType`.
///
/// # Returns
///
/// - `UpgradeType` - The parsed upgrade type.
#[inline(always)]
pub fn get_upgrade_type(&self) -> UpgradeType {
self.get_headers()
.get(UPGRADE)
.and_then(|values: &VecDeque<String>| values.back())
.and_then(|data: &String| data.parse::<UpgradeType>().ok())
.unwrap_or_default()
}
/// Retrieves the body content of the request as a UTF-8 encoded string.
///
/// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as a string.
/// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
///
/// # Returns
///
/// - `String` - The body content as a string.
#[inline(always)]
pub fn get_body_string(&self) -> String {
String::from_utf8_lossy(self.get_body()).into_owned()
}
/// Deserializes the body content of the request as_ref a specified type `T`.
///
/// This method first retrieves the body content as a byte slice using `self.get_body()`.
/// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
///
/// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
///
/// # Returns
///
/// - `Result<T, serde_json::Error>` - The deserialization result.
#[inline(always)]
pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
where
T: DeserializeOwned,
{
from_slice(self.get_body())
}
/// Deserializes the body content of the request as_ref a specified type `T`.
///
/// This method first retrieves the body content as a byte slice using `self.get_body()`.
/// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
///
/// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
///
/// # Returns
///
/// - `T` - The deserialized body content.
///
/// # Panics
///
/// This function will panic if the deserialization fails.
#[inline(always)]
pub fn get_body_json<T>(&self) -> T
where
T: DeserializeOwned,
{
self.try_get_body_json().unwrap()
}
/// Checks whether the WebSocket upgrade is enabled for this request.
///
/// This method determines if the `UPGRADE` header indicates a WebSocket connection.
///
/// # Returns
///
/// - `bool` - Whether WebSocket upgrade is enabled.
#[inline(always)]
pub fn is_ws_upgrade_type(&self) -> bool {
self.get_upgrade_type().is_ws()
}
/// Checks whether the request declares a `multipart/form-data` body.
///
/// # Returns
///
/// - `bool` - Whether the request content type is `multipart/form-data`.
#[inline(always)]
pub fn is_multipart_form_data(&self) -> bool {
self.try_get_content_type()
.map(|content_type: String| MultipartFormData::is_form_data(content_type))
.unwrap_or(false)
}
/// Tries to get the request content type with its parameters stripped.
///
/// A `Content-Type` header such as `text/html; charset=utf-8` yields the
/// media type alone, so a caller comparing against a media type does not
/// have to know that parameters may follow it.
///
/// # Returns
///
/// - `Option<RequestContentType>` - The media type, or `None` when the header is absent.
#[inline(always)]
pub fn try_get_content_type(&self) -> Option<RequestContentType> {
self.try_get_header_front(CONTENT_TYPE)
.map(|value: String| {
value
.split(SEMICOLON)
.next()
.unwrap_or(EMPTY_STR)
.trim()
.to_ascii_lowercase()
})
}
/// Tries to get one parameter of the request `Content-Type` header.
///
/// The name is matched case-insensitively and a quoted value is unquoted,
/// so both `boundary=abc` and `boundary="abc"` yield `abc`.
///
/// # Arguments
///
/// - `K` - The parameter name, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// - `Option<RequestContentTypeParameter>` - The parameter value, or `None` when absent.
pub fn try_get_content_type_parameter<K>(&self, name: K) -> Option<RequestContentTypeParameter>
where
K: AsRef<str>,
{
let content_type: String = self.try_get_header_front(CONTENT_TYPE)?;
let name: &str = name.as_ref();
for parameter in content_type.split(SEMICOLON).skip(1) {
let (key, value) = parameter.trim().split_once(EQUAL)?;
if !key.trim().eq_ignore_ascii_case(name) {
continue;
}
let value: &str = value.trim();
let value: &str = value
.strip_prefix(MULTIPART_PARAMETER_QUOTE)
.and_then(|value: &str| value.strip_suffix(MULTIPART_PARAMETER_QUOTE))
.unwrap_or(value);
if !value.is_empty() {
return Some(value.to_string());
}
}
None
}
/// Tries to decode a `multipart/form-data` body into its parts.
///
/// The boundary is read from the request `Content-Type` header rather than
/// guessed, so a body whose content type declares no boundary, a truncated
/// body, and a part without a name all yield `None`.
///
/// # Returns
///
/// - `Option<MultipartFormDataParts>` - The decoded parts, or `None` when unavailable.
pub fn try_get_body_form_data(&self) -> Option<MultipartFormDataParts> {
let boundary: MultipartFormDataBoundary =
self.try_get_content_type_parameter(MULTIPART_BOUNDARY_PARAMETER)?;
MultipartFormData::parse(self.get_body(), &boundary)
}
/// Decodes an `application/x-www-form-urlencoded` body into its fields.
///
/// # Returns
///
/// - `BodyForm` - The decoded form fields.
#[inline(always)]
pub fn get_body_form(&self) -> BodyForm {
MultipartFormData::parse_url_encoded(self.get_body())
}
/// Tries to get a plain text field of a `multipart/form-data` body.
///
/// A part that uploads a file is skipped, so a file field never silently
/// decodes as text.
///
/// # Arguments
///
/// - `K` - The form field name, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// - `Option<BodyFormValue>` - The field value, or `None` when absent or a file.
pub fn try_get_body_form_data_text<K>(&self, name: K) -> Option<BodyFormValue>
where
K: AsRef<str>,
{
let parts: MultipartFormDataParts = self.try_get_body_form_data()?;
MultipartFormData::try_get_part_text(&parts, name)
}
/// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
///
/// # Returns
///
/// - `bool` - Whether the upgrade type is h2c.
#[inline(always)]
pub fn is_h2c_upgrade_type(&self) -> bool {
self.get_upgrade_type().is_h2c()
}
/// Checks if the current upgrade type is TLS (any version).
///
/// # Returns
///
/// - `bool` - Whether the upgrade type is TLS.
#[inline(always)]
pub fn is_tls_upgrade_type(&self) -> bool {
self.get_upgrade_type().is_tls()
}
/// Checks whether the upgrade type is unknown.
///
/// # Returns
///
/// - `bool` - Whether the upgrade type is unknown.
#[inline(always)]
pub fn is_unknown_upgrade_type(&self) -> bool {
self.get_upgrade_type().is_unknown()
}
/// Determines if a keep-alive connection should be enabled for this request.
///
/// This function checks the `Connection` header and the HTTP version to determine
/// if keep-alive should be enabled. The logic is as follows:
///
/// 1. If the `Connection` header exists:
/// - Returns `true` if the header value is "keep-alive" (case-insensitive).
/// - Returns `false` if the header value is "close" (case-insensitive).
/// 2. If no `Connection` header is present:
/// - Returns `true` if the HTTP version is 1.1 or higher.
/// - Returns `false` otherwise.
///
/// # Returns
///
/// - `bool` - Whether keep-alive should be enabled.
#[inline(always)]
pub fn is_enable_keep_alive(&self) -> bool {
if let Some(connection_value) = self
.get_headers()
.get(CONNECTION)
.and_then(|values: &VecDeque<String>| values.back())
{
if connection_value.eq_ignore_ascii_case(KEEP_ALIVE) {
return true;
} else if connection_value.eq_ignore_ascii_case(CLOSE) {
return self.is_ws_upgrade_type();
}
}
self.get_version().is_http1_1_or_higher() || self.is_ws_upgrade_type()
}
/// Determines if keep-alive should be disabled for this request.
///
/// # Returns
///
/// - `bool` - Whether keep-alive should be disabled.
#[inline(always)]
pub fn is_disable_keep_alive(&self) -> bool {
!self.is_enable_keep_alive()
}
}