http_type/request/impl.rs
1use super::*;
2
3/// Implements the `std::error::Error` trait for `RequestError`.
4impl Error for RequestError {}
5
6/// Provides a default value for `RequestError`.
7impl Default for RequestError {
8 /// Provides a default value for `RequestError`.
9 ///
10 /// Returns a `RequestError::Unknown` with `HttpStatus::InternalServerError`.
11 #[inline(always)]
12 fn default() -> Self {
13 RequestError::Unknown(HttpStatus::InternalServerError)
14 }
15}
16
17/// Converts an I/O error to a `RequestError`.
18///
19/// Maps connection reset and aborted errors to `ClientDisconnected`,
20/// all other I/O errors are mapped to `ReadConnection`.
21impl From<io::Error> for RequestError {
22 /// Converts an I/O error to a `RequestError`.
23 ///
24 /// # Arguments
25 ///
26 /// - `io::Error` - The I/O error to convert.
27 ///
28 /// # Returns
29 ///
30 /// - `RequestError` - The corresponding request error.
31 #[inline(always)]
32 fn from(error: io::Error) -> Self {
33 let kind: ErrorKind = error.kind();
34 if kind == ErrorKind::ConnectionReset || kind == ErrorKind::ConnectionAborted {
35 return RequestError::ClientDisconnected(HttpStatus::BadRequest);
36 }
37 RequestError::ReadConnection(HttpStatus::BadRequest)
38 }
39}
40
41/// Converts a timeout elapsed error to a `RequestError`.
42///
43/// Maps timeout errors to `ReadTimeout` with `HttpStatus::RequestTimeout`.
44impl From<Elapsed> for RequestError {
45 /// Converts a timeout elapsed error to a `RequestError`.
46 ///
47 /// # Arguments
48 ///
49 /// - `Elapsed` - The elapsed error to convert.
50 ///
51 /// # Returns
52 ///
53 /// - `RequestError` - The corresponding request error as `ReadTimeout`.
54 #[inline(always)]
55 fn from(_: Elapsed) -> Self {
56 RequestError::ReadTimeout(HttpStatus::RequestTimeout)
57 }
58}
59
60/// Converts a parse int error to a `RequestError`.
61///
62/// Maps parse int errors to `InvalidContentLength` with `HttpStatus::BadRequest`.
63impl From<ParseIntError> for RequestError {
64 /// Converts a parse int error to a `RequestError`.
65 ///
66 /// # Arguments
67 ///
68 /// - `ParseIntError` - The parse error to convert.
69 ///
70 /// # Returns
71 ///
72 /// - `RequestError` - The corresponding request error as `InvalidContentLength`.
73 #[inline(always)]
74 fn from(_: ParseIntError) -> Self {
75 RequestError::InvalidContentLength(HttpStatus::BadRequest)
76 }
77}
78
79/// Converts a response error to a `RequestError`.
80///
81/// Maps response errors to `WriteTimeout` with `HttpStatus::InternalServerError`.
82impl From<ResponseError> for RequestError {
83 /// Converts a response error to a `RequestError`.
84 ///
85 /// # Arguments
86 ///
87 /// - `ResponseError` - The response error to convert.
88 ///
89 /// # Returns
90 ///
91 /// - `RequestError` - The corresponding request error as `WriteTimeout`.
92 #[inline(always)]
93 fn from(_: ResponseError) -> Self {
94 RequestError::WriteTimeout(HttpStatus::InternalServerError)
95 }
96}
97
98/// Inherent implementation of [`RequestError`].
99impl RequestError {
100 /// Gets the HTTP status associated with this error.
101 ///
102 /// Returns the HttpStatus enum variant that corresponds to this error.
103 ///
104 /// # Returns
105 ///
106 /// - `HttpStatus` - The HTTP status associated with this error.
107 pub fn get_http_status(&self) -> HttpStatus {
108 match self {
109 Self::HttpRead(status) => *status,
110 Self::GetTcpStream(status) => *status,
111 Self::GetTlsStream(status) => *status,
112 Self::ReadConnection(status) => *status,
113 Self::RequestAborted(status) => *status,
114 Self::TlsStreamConnect(status) => *status,
115 Self::NeedOpenRedirect(status) => *status,
116 Self::MaxRedirectTimes(status) => *status,
117 Self::MethodsNotSupport(status) => *status,
118 Self::RedirectInvalidUrl(status) => *status,
119 Self::ClientDisconnected(status) => *status,
120 Self::RedirectUrlDeadLoop(status) => *status,
121 Self::ClientClosedConnection(status) => *status,
122 Self::ServerClosedConnection(status) => *status,
123 Self::IncompleteWebSocketFrame(status) => *status,
124 Self::RequestTooLong(status) => *status,
125 Self::PathTooLong(status) => *status,
126 Self::QueryTooLong(status) => *status,
127 Self::HeaderLineTooLong(status) => *status,
128 Self::TooManyHeaders(status) => *status,
129 Self::HeaderKeyTooLong(status) => *status,
130 Self::HeaderValueTooLong(status) => *status,
131 Self::ContentLengthTooLarge(status) => *status,
132 Self::InvalidContentLength(status) => *status,
133 Self::InvalidUrlScheme(status) => *status,
134 Self::InvalidUrlHost(status) => *status,
135 Self::InvalidUrlPort(status) => *status,
136 Self::InvalidUrlPath(status) => *status,
137 Self::InvalidUrlQuery(status) => *status,
138 Self::InvalidUrlFragment(status) => *status,
139 Self::ReadTimeout(status) => *status,
140 Self::WriteTimeout(status) => *status,
141 Self::TcpConnectionFailed(status) => *status,
142 Self::TlsHandshakeFailed(status) => *status,
143 Self::TlsCertificateInvalid(status) => *status,
144 Self::WebSocketFrameTooLarge(status) => *status,
145 Self::WebSocketOpcodeUnsupported(status) => *status,
146 Self::WebSocketMaskMissing(status) => *status,
147 Self::WebSocketPayloadCorrupted(status) => *status,
148 Self::WebSocketInvalidUtf8(status) => *status,
149 Self::WebSocketInvalidCloseCode(status) => *status,
150 Self::WebSocketInvalidExtension(status) => *status,
151 Self::HttpRequestPartsInsufficient(status) => *status,
152 Self::TcpStreamConnect(status) => *status,
153 Self::TlsConnectorBuild(status) => *status,
154 Self::InvalidUrl(status) => *status,
155 Self::ConfigReadError(status) => *status,
156 Self::TcpStreamConnectString(status) => *status,
157 Self::TlsConnectorBuildString(status) => *status,
158 Self::Request(_) => HttpStatus::BadRequest,
159 Self::Unknown(status) => *status,
160 }
161 }
162
163 /// Gets the numeric HTTP status code associated with this error.
164 ///
165 /// Returns the numeric status code (e.g., 400, 404, 500) that corresponds to this error.
166 ///
167 /// # Returns
168 ///
169 /// - `usize` - The numeric HTTP status code.
170 pub fn get_http_status_code(&self) -> usize {
171 self.get_http_status().code()
172 }
173}
174
175/// Implementation of `Default` trait for `RequestConfig`.
176impl Default for RequestConfig {
177 /// Creates a new `RequestConfig` with default secure settings.
178 ///
179 /// This constructor initializes the configuration with standard security limits
180 /// suitable for most HTTP request parsing scenarios.
181 ///
182 /// # Returns
183 ///
184 /// - `Self` - A new `RequestConfig` instance with default settings.
185 #[inline(always)]
186 fn default() -> Self {
187 Self {
188 buffer_size: DEFAULT_BUFFER_SIZE,
189 max_path_size: DEFAULT_MAX_PATH_SIZE,
190 max_header_count: DEFAULT_MAX_HEADER_COUNT,
191 max_header_key_size: DEFAULT_MAX_HEADER_KEY_SIZE,
192 max_header_value_size: DEFAULT_MAX_HEADER_VALUE_SIZE,
193 max_body_size: DEFAULT_MAX_BODY_SIZE,
194 read_timeout_ms: DEFAULT_READ_TIMEOUT_MS,
195 }
196 }
197}
198
199/// Inherent implementation of [`RequestConfig`].
200impl RequestConfig {
201 /// Creates a new `RequestConfig` from a JSON string.
202 ///
203 /// # Arguments
204 ///
205 /// - `C` - The configuration, which requires the `AsRef<str>` bound.
206 ///
207 /// # Returns
208 ///
209 /// - `Result<RequestConfig, serde_json::Error>` - The parsed `RequestConfig` or an error.
210 pub fn from_json<C>(json: C) -> Result<RequestConfig, serde_json::Error>
211 where
212 C: AsRef<str>,
213 {
214 from_str(json.as_ref())
215 }
216
217 /// Creates a new `RequestConfig` with low-security settings.
218 ///
219 /// This constructor initializes the configuration with less restrictive limits
220 /// for environments where higher limits are needed.
221 ///
222 /// # Returns
223 ///
224 /// - `Self` - A new `RequestConfig` instance with low-security settings.
225 #[inline(always)]
226 pub fn low_security() -> Self {
227 Self {
228 buffer_size: DEFAULT_LOW_SECURITY_BUFFER_SIZE,
229 max_path_size: DEFAULT_LOW_SECURITY_MAX_PATH_SIZE,
230 max_header_count: DEFAULT_LOW_SECURITY_MAX_HEADER_COUNT,
231 max_header_key_size: DEFAULT_LOW_SECURITY_MAX_HEADER_KEY_SIZE,
232 max_header_value_size: DEFAULT_LOW_SECURITY_MAX_HEADER_VALUE_SIZE,
233 max_body_size: DEFAULT_LOW_SECURITY_MAX_BODY_SIZE,
234 read_timeout_ms: DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS,
235 }
236 }
237
238 /// Creates a new `RequestConfig` with high-security settings.
239 ///
240 /// This constructor initializes the configuration with more restrictive limits
241 /// to provide maximum protection against various attacks in high-risk environments.
242 ///
243 /// # Returns
244 ///
245 /// - `Self` - A new `RequestConfig` instance with high-security settings.
246 #[inline(always)]
247 pub fn high_security() -> Self {
248 Self {
249 buffer_size: DEFAULT_HIGH_SECURITY_BUFFER_SIZE,
250 max_path_size: DEFAULT_HIGH_SECURITY_MAX_PATH_SIZE,
251 max_header_count: DEFAULT_HIGH_SECURITY_MAX_HEADER_COUNT,
252 max_header_key_size: DEFAULT_HIGH_SECURITY_MAX_HEADER_KEY_SIZE,
253 max_header_value_size: DEFAULT_HIGH_SECURITY_MAX_HEADER_VALUE_SIZE,
254 max_body_size: DEFAULT_HIGH_SECURITY_MAX_BODY_SIZE,
255 read_timeout_ms: DEFAULT_HIGH_SECURITY_READ_TIMEOUT_MS,
256 }
257 }
258}
259
260/// Provides a default value for `Request`.
261///
262/// Returns a new `Request` instance with all fields initialized to their default values.
263impl Default for Request {
264 /// Builds the default `Request` with all fields set to their defaults.
265 #[inline(always)]
266 fn default() -> Self {
267 Self {
268 method: Method::default(),
269 host: String::new(),
270 version: HttpVersion::default(),
271 path: String::new(),
272 querys: hash_map_xx_hash3_64(),
273 headers: hash_map_xx_hash3_64(),
274 body: Vec::new(),
275 }
276 }
277}
278
279/// Inherent implementation of [`Request`].
280impl Request {
281 /// Resets the request to its default state while retaining allocated capacity.
282 ///
283 /// This keeps the header map, query map, body, and string allocations so
284 /// persistent (keep-alive) connections avoid repeated allocation per request.
285 ///
286 /// # Returns
287 ///
288 /// - `&mut Self` - A mutable reference to self for chaining.
289 pub fn reset(&mut self) -> &mut Self {
290 self.set_method(Method::default());
291 self.get_mut_host().clear();
292 self.set_version(HttpVersion::default());
293 self.get_mut_path().clear();
294 self.recycle_querys();
295 self.recycle_headers();
296 self.get_mut_body().clear();
297 self
298 }
299
300 /// Hands the query entries to the pool and empties the query map.
301 fn recycle_querys(&mut self) {
302 let querys: &mut RequestQuerys = self.get_mut_querys();
303 if querys.is_empty() {
304 return;
305 }
306 return_header_entries(querys.drain());
307 }
308
309 /// Hands the header entries to the pool and empties the header map.
310 ///
311 /// The map ends up empty, exactly as clearing it would, but the name and
312 /// the value buffers of every header survive in the pool. The next
313 /// request on the same connection takes them back and overwrites them,
314 /// so a connection that keeps its headers stops allocating for them.
315 ///
316 /// # Returns
317 ///
318 /// - `()` - The headers have been recycled.
319 fn recycle_headers(&mut self) {
320 let headers: &mut RequestHeaders = self.get_mut_headers();
321 if headers.is_empty() {
322 return;
323 }
324 return_header_entries(headers.drain());
325 }
326
327 /// Parses the HTTP request line into method, target, separator indices, and version in one scan.
328 ///
329 /// # Arguments
330 ///
331 /// - `&str` - The first line string of the HTTP request.
332 ///
333 /// # Returns
334 ///
335 /// - `Result<ParsedHttpFirstLine<'_>, RequestError>` - Parsed method, raw target, optional `?`
336 /// and `#` offsets inside the target, and HTTP version.
337 #[inline(always)]
338 fn parse_http_first_line_fused(line: &str) -> Result<ParsedHttpFirstLine<'_>, RequestError> {
339 let trimmed_lf: &str = line.strip_suffix(HTTP_HEADER_LINE_FEED).unwrap_or(line);
340 let raw: &str = trimmed_lf
341 .strip_suffix(HTTP_HEADER_CARRIAGE_RETURN)
342 .unwrap_or(trimmed_lf);
343 let bytes: &[u8] = raw.as_bytes();
344 let len: usize = bytes.len();
345 if (len < 14 || bytes[0] == SPACE_U8) && (len == 0 || bytes[0] == SPACE_U8) {
346 return Err(RequestError::HttpRequestPartsInsufficient(
347 HttpStatus::BadRequest,
348 ));
349 }
350 let (method, path_start): (Method, usize) =
351 if len >= 4 && &bytes[..3] == WIRE_METHOD_GET && bytes[3] == SPACE_U8 {
352 (Method::Get, 4)
353 } else if len >= 5 && &bytes[..4] == WIRE_METHOD_POST && bytes[4] == SPACE_U8 {
354 (Method::Post, 5)
355 } else {
356 let Some(first_sp) = bytes.iter().position(|byte: &u8| *byte == SPACE_U8) else {
357 return Err(RequestError::HttpRequestPartsInsufficient(
358 HttpStatus::BadRequest,
359 ));
360 };
361 let method_bytes: &[u8] = &bytes[..first_sp];
362 if method_bytes.is_empty() {
363 return Err(RequestError::HttpRequestPartsInsufficient(
364 HttpStatus::BadRequest,
365 ));
366 }
367 let parsed_method: Method = match method_bytes {
368 WIRE_METHOD_PUT => Method::Put,
369 WIRE_METHOD_DELETE => Method::Delete,
370 WIRE_METHOD_HEAD => Method::Head,
371 WIRE_METHOD_OPTIONS => Method::Options,
372 WIRE_METHOD_PATCH => Method::Patch,
373 WIRE_METHOD_CONNECT => Method::Connect,
374 WIRE_METHOD_TRACE => Method::Trace,
375 _ => {
376 if !method_bytes
377 .iter()
378 .all(|byte: &u8| HTTP_HEADER_TOKEN_TABLE[*byte as usize])
379 {
380 return Err(RequestError::HttpRequestPartsInsufficient(
381 HttpStatus::BadRequest,
382 ));
383 }
384 Method::Unknown(raw[..first_sp].to_owned())
385 }
386 };
387 (parsed_method, first_sp + 1)
388 };
389 let rest: &[u8] = &bytes[path_start..];
390 let mut rel_second_sp: usize = rest.len();
391 let mut query_index: Option<usize> = None;
392 let mut hash_index: Option<usize> = None;
393 for (idx, &byte) in rest.iter().enumerate() {
394 if byte == SPACE_U8 {
395 rel_second_sp = idx;
396 break;
397 }
398 if byte < SPACE_U8 || byte == HTTP_HEADER_DELETE {
399 return Err(RequestError::HttpRequestPartsInsufficient(
400 HttpStatus::BadRequest,
401 ));
402 }
403 if byte == QUERY_U8 && query_index.is_none() && hash_index.is_none() {
404 query_index = Some(idx);
405 } else if byte == HASH_U8 && hash_index.is_none() {
406 hash_index = Some(idx);
407 }
408 }
409 if rel_second_sp == 0 || rel_second_sp == rest.len() {
410 return Err(RequestError::HttpRequestPartsInsufficient(
411 HttpStatus::BadRequest,
412 ));
413 }
414 let second_sp: usize = path_start + rel_second_sp;
415 let version_bytes: &[u8] = &bytes[second_sp + 1..];
416 let version: HttpVersion = match version_bytes {
417 WIRE_VERSION_1_1 => HttpVersion::Http1_1,
418 WIRE_VERSION_1_0 => HttpVersion::Http1_0,
419 _ => {
420 return Err(RequestError::HttpRequestPartsInsufficient(
421 HttpStatus::BadRequest,
422 ));
423 }
424 };
425 let full_path: &str = &raw[path_start..second_sp];
426 Ok((method, full_path, query_index, hash_index, version))
427 }
428
429 /// Parses the first line of HTTP request into method, path, and version components.
430 ///
431 /// # Arguments
432 ///
433 /// - `&str` - The first line string of HTTP request to parse.
434 ///
435 /// # Returns
436 ///
437 /// - `Result<(Method, &str, HttpVersion), RequestError>` - A tuple containing:
438 /// - The parsed HTTP method
439 /// - The full path string
440 /// - The parsed HTTP version
441 /// - Or an error if parsing fails
442 #[inline(always)]
443 pub(crate) fn get_http_first_line(
444 line: &str,
445 ) -> Result<(Method, &str, HttpVersion), RequestError> {
446 let (method, full_path, _, _, version): (
447 Method,
448 &str,
449 Option<usize>,
450 Option<usize>,
451 HttpVersion,
452 ) = Self::parse_http_first_line_fused(line)?;
453 Ok((method, full_path, version))
454 }
455
456 /// Finds the first `?` and `#` separator indices of a request target in a single pass.
457 ///
458 /// # Arguments
459 ///
460 /// - `&str` - The full request target string.
461 ///
462 /// # Returns
463 ///
464 /// - `(Option<usize>, Option<usize>)` - `(query_index, hash_index)`.
465 #[inline(always)]
466 pub(crate) fn find_path_separators(path: &str) -> (Option<usize>, Option<usize>) {
467 let mut query_index: Option<usize> = None;
468 let mut hash_index: Option<usize> = None;
469 for (idx, byte) in path.bytes().enumerate() {
470 if byte == QUERY_U8 && query_index.is_none() && hash_index.is_none() {
471 query_index = Some(idx);
472 } else if byte == HASH_U8 {
473 hash_index = Some(idx);
474 break;
475 }
476 }
477 (query_index, hash_index)
478 }
479
480 /// Validates the path length against the maximum allowed size.
481 ///
482 /// # Arguments
483 ///
484 /// - `&str` - The path string to check.
485 /// - `usize` - The maximum allowed path size.
486 ///
487 /// # Returns
488 ///
489 /// - `Result<(), RequestError>` - Ok if valid, or an error if the path is too long.
490 #[inline(always)]
491 pub(crate) fn check_http_path_size(path: &str, max_size: usize) -> Result<(), RequestError> {
492 if path.len() > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
493 return Err(RequestError::PathTooLong(HttpStatus::URITooLong));
494 }
495 Ok(())
496 }
497
498 /// Parses the query string from the full path.
499 ///
500 /// Handles both query parameters (after `?`) and hash fragments (after `#`),
501 /// ensuring proper parsing when both are present.
502 ///
503 /// # Arguments
504 ///
505 /// - `&str` - The full path string containing the query.
506 /// - `Option<usize>` - The index of the query separator (`?`), if present.
507 /// - `Option<usize>` - The index of the hash separator (`#`), if present.
508 ///
509 /// # Returns
510 ///
511 /// - `&str` - The parsed query string slice, or empty string if no query.
512 #[inline(always)]
513 pub(crate) fn get_http_query(
514 path: &str,
515 query_index: Option<usize>,
516 hash_index: Option<usize>,
517 ) -> &str {
518 query_index.map_or(EMPTY_STR, |query_index: usize| match hash_index {
519 None => &path[query_index + 1..],
520 Some(hash_index) if hash_index < query_index => EMPTY_STR,
521 Some(hash_index) => &path[query_index + 1..hash_index],
522 })
523 }
524
525 /// Parses the request path without query string or hash fragment.
526 ///
527 /// # Arguments
528 ///
529 /// - `&str` - The full path string.
530 /// - `Option<usize>` - The index of the query separator (`?`), if present.
531 /// - `Option<usize>` - The index of the hash separator (`#`), if present.
532 ///
533 /// # Returns
534 ///
535 /// - `&str` - The request path slice without query or hash.
536 #[inline(always)]
537 pub(crate) fn get_http_path(
538 path: &str,
539 query_index: Option<usize>,
540 hash_index: Option<usize>,
541 ) -> &str {
542 let separator_index: Option<usize> = match (query_index, hash_index) {
543 (Some(q), Some(h)) => Some(q.min(h)),
544 (Some(q), None) => Some(q),
545 (None, Some(h)) => Some(h),
546 (None, None) => None,
547 };
548 match separator_index {
549 Some(index) => &path[..index],
550 None => path,
551 }
552 }
553
554 /// Parses a query string into key-value pairs in the given map with an upper entry bound.
555 ///
556 /// Expects format "key1=value1&key2=value2". Empty values are allowed, and a
557 /// key that repeats keeps every value instead of letting the last one win.
558 /// The target map is expected to be empty; entries are inserted without
559 /// reallocating the map when it already has sufficient capacity.
560 ///
561 /// # Arguments
562 ///
563 /// - `&str` - The query string to parse.
564 /// - `&mut RequestQuerys` - The map to insert parsed parameters into.
565 /// - `usize` - The maximum allowed number of query parameters (`usize::MAX` disables the cap).
566 ///
567 /// # Returns
568 ///
569 /// - `Result<(), RequestError>` - Ok on success, or `QueryTooLong` when the limit is exceeded.
570 #[inline(always)]
571 pub(crate) fn fill_http_querys(
572 query: &str,
573 querys: &mut RequestQuerys,
574 max_count: usize,
575 ) -> Result<(), RequestError> {
576 if query.is_empty() {
577 return Ok(());
578 }
579 let mut count: usize = 0;
580 for pair in query.split(AND) {
581 if let Some((key, value)) = pair.split_once(EQUAL) {
582 if !key.is_empty() {
583 count += 1;
584 if count > max_count {
585 return Err(RequestError::QueryTooLong(HttpStatus::URITooLong));
586 }
587 let (mut pooled_key, mut pooled_values): (String, VecDeque<String>) =
588 take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
589 pooled_key.clear();
590 pooled_key.push_str(key);
591 match querys.entry(pooled_key) {
592 Entry::Occupied(mut occupied) => {
593 let mut val_slot: String =
594 pooled_values.pop_front().unwrap_or_default();
595 val_slot.clear();
596 val_slot.push_str(value);
597 occupied.get_mut().push_back(val_slot);
598 }
599 Entry::Vacant(vacant) => {
600 if pooled_values.len() == 1 {
601 let slot: &mut String = &mut pooled_values[0];
602 slot.clear();
603 slot.push_str(value);
604 } else {
605 while pooled_values.len() > 1 {
606 pooled_values.pop_back();
607 }
608 if let Some(slot) = pooled_values.front_mut() {
609 slot.clear();
610 slot.push_str(value);
611 } else {
612 pooled_values.push_back(value.to_owned());
613 }
614 }
615 vacant.insert(pooled_values);
616 }
617 }
618 }
619 } else if !pair.is_empty() {
620 if !querys.is_empty() && querys.contains_key(pair) {
621 continue;
622 }
623 count += 1;
624 if count > max_count {
625 return Err(RequestError::QueryTooLong(HttpStatus::URITooLong));
626 }
627 let (mut pooled_key, mut pooled_values): (String, VecDeque<String>) =
628 take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
629 pooled_key.clear();
630 pooled_key.push_str(pair);
631 pooled_values.clear();
632 querys.insert(pooled_key, pooled_values);
633 }
634 }
635 Ok(())
636 }
637
638 /// Checks if the header count exceeds the maximum allowed.
639 ///
640 /// # Arguments
641 ///
642 /// - `usize` - The current number of headers parsed.
643 /// - `usize` - The maximum allowed number of headers.
644 ///
645 /// # Returns
646 ///
647 /// - `Result<(), RequestError>` - Returns an error if the limit is exceeded and not in low security mode.
648 #[inline(always)]
649 pub(crate) fn check_http_header_count(
650 count: usize,
651 max_count: usize,
652 ) -> Result<(), RequestError> {
653 if count > max_count && max_count != DEFAULT_LOW_SECURITY_MAX_HEADER_COUNT {
654 return Err(RequestError::TooManyHeaders(
655 HttpStatus::RequestHeaderFieldsTooLarge,
656 ));
657 }
658 Ok(())
659 }
660
661 /// Checks if a header key exceeds the maximum allowed length.
662 ///
663 /// # Arguments
664 ///
665 /// - `&str` - The header key to check.
666 /// - `usize` - The maximum allowed length for a header key.
667 ///
668 /// # Returns
669 ///
670 /// - `Result<(), RequestError>` - Returns an error if the limit is exceeded and not in low security mode.
671 #[inline(always)]
672 pub(crate) fn check_http_header_key_size(
673 key: &str,
674 max_size: usize,
675 ) -> Result<(), RequestError> {
676 if key.len() > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_HEADER_KEY_SIZE {
677 return Err(RequestError::HeaderKeyTooLong(
678 HttpStatus::RequestHeaderFieldsTooLarge,
679 ));
680 }
681 Ok(())
682 }
683
684 /// Checks if a header value exceeds the maximum allowed length.
685 ///
686 /// # Arguments
687 ///
688 /// - `&str` - The header value to check.
689 /// - `usize` - The maximum allowed length for a header value.
690 ///
691 /// # Returns
692 ///
693 /// - `Result<(), RequestError>` - Returns an error if the limit is exceeded and not in low security mode.
694 #[inline(always)]
695 pub(crate) fn check_http_header_value_size(
696 value: &str,
697 max_size: usize,
698 ) -> Result<(), RequestError> {
699 if value.len() > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_HEADER_VALUE_SIZE {
700 return Err(RequestError::HeaderValueTooLong(
701 HttpStatus::RequestHeaderFieldsTooLarge,
702 ));
703 }
704 Ok(())
705 }
706
707 /// Parses the Content-Length header value and checks it against max body size.
708 ///
709 /// # Arguments
710 ///
711 /// - `&str` - The Content-Length header value string.
712 /// - `usize` - The maximum allowed body size.
713 ///
714 /// # Returns
715 ///
716 /// - `Result<usize, RequestError>` - The parsed content length or an error.
717 #[inline(always)]
718 pub(crate) fn check_http_body_size(
719 value: &str,
720 max_size: usize,
721 ) -> Result<usize, RequestError> {
722 if value.is_empty() || !value.bytes().all(|byte: u8| byte.is_ascii_digit()) {
723 return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
724 }
725 let length: usize = value.parse::<usize>()?;
726 if length > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE {
727 return Err(RequestError::ContentLengthTooLarge(
728 HttpStatus::PayloadTooLarge,
729 ));
730 }
731 Ok(length)
732 }
733
734 /// Parses a complete HTTP/1.1 request head (request line and all headers)
735 /// directly from an already-buffered byte slice without per-line copying.
736 ///
737 /// Returns `Ok(None)` when the buffered slice does not yet contain the
738 /// terminating blank line, leaving the caller to fall back to incremental
739 /// line reads without losing any bytes.
740 ///
741 /// # Arguments
742 ///
743 /// - `&[u8]` - The buffered unread bytes from the stream.
744 /// - `&RequestConfig` - Security limits for path, headers and body.
745 /// - `&mut String` - The stream's request-line buffer populated for downstream inspection.
746 ///
747 /// # Returns
748 ///
749 /// - `Result<Option<(RequestFraming, usize, usize, usize)>, RequestError>` - The framing,
750 /// number of bytes consumed, and target byte offsets when a full head was parsed, `None` when more
751 /// input is required, or a protocol error.
752 pub(crate) fn parse_http_head_from_slice(
753 &mut self,
754 buffer: &[u8],
755 config: &RequestConfig,
756 line_buffer: &mut String,
757 ) -> Result<Option<(RequestFraming, usize, usize, usize)>, RequestError> {
758 let Some(first_lf) = r#fn::find_byte_swar(buffer, BR_U8) else {
759 return Ok(None);
760 };
761 let first_line_end: usize = first_lf + 1;
762 let first_line_bytes: &[u8] = &buffer[..first_line_end];
763 let first_line: &str = if first_line_bytes.is_ascii() {
764 // SAFETY: `is_ascii()` guarantees every byte is `< 0x80`, which is valid UTF-8.
765 unsafe { from_utf8_unchecked(first_line_bytes) }
766 } else {
767 match from_utf8(first_line_bytes) {
768 Ok(text) => text,
769 Err(_) => return Err(RequestError::ReadConnection(HttpStatus::BadRequest)),
770 }
771 };
772 line_buffer.clear();
773 line_buffer.push_str(first_line);
774 let (method, full_path, query_index, hash_index, version): (
775 Method,
776 &str,
777 Option<usize>,
778 Option<usize>,
779 HttpVersion,
780 ) = Self::parse_http_first_line_fused(first_line)?;
781 let target_start: usize = full_path.as_ptr() as usize - first_line.as_ptr() as usize;
782 let target_end: usize = target_start + full_path.len();
783 let max_path_size: usize = config.get_max_path_size();
784 Self::check_http_path_size(full_path, max_path_size)?;
785 let query: &str = Self::get_http_query(full_path, query_index, hash_index);
786 let max_query_count: usize = if max_path_size == DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
787 usize::MAX
788 } else {
789 HTTP_MAX_QUERY_PARAM_COUNT
790 };
791 Self::fill_http_querys(query, self.get_mut_querys(), max_query_count)?;
792 let path_slice: &str = Self::get_http_path(full_path, query_index, hash_index);
793 self.get_mut_path().push_str(path_slice);
794 self.set_version(version);
795 self.set_method(method);
796 let Request {
797 headers,
798 host,
799 version,
800 ..
801 } = self;
802 let max_header_count: usize = config.get_max_header_count();
803 let max_header_key_size: usize = config.get_max_header_key_size();
804 let max_header_value_size: usize = config.get_max_header_value_size();
805 let max_body_size: usize = config.get_max_body_size();
806 let mut content_size: usize = 0;
807 let mut header_count: usize = 0;
808 let mut content_length_seen: bool = false;
809 let mut transfer_encoding_seen: bool = false;
810 let mut host_seen: bool = false;
811 let mut pos: usize = first_line_end;
812 let mut incomplete_head: bool = false;
813 let header_result: Result<(), RequestError> = HEADER_ENTRY_POOL.with(
814 |pool: &RefCell<Vec<(String, VecDeque<String>)>>| -> Result<(), RequestError> {
815 let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
816 loop {
817 let rest: &[u8] = &buffer[pos..];
818 let Some(rel_lf) = r#fn::find_byte_swar(rest, BR_U8) else {
819 incomplete_head = true;
820 return Ok(());
821 };
822 let line_end: usize = pos + rel_lf;
823 let raw_line: &[u8] = if line_end > pos && buffer[line_end - 1] == b'\r' {
824 &buffer[pos..line_end - 1]
825 } else {
826 &buffer[pos..line_end]
827 };
828 pos = line_end + 1;
829 if raw_line.is_empty() {
830 break;
831 }
832 let first_byte: u8 = raw_line[0];
833 if first_byte == SPACE_U8 || first_byte == TAB_U8 {
834 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
835 }
836 header_count += 1;
837 Self::check_http_header_count(header_count, max_header_count)?;
838 let mut colon_pos: usize = raw_line.len();
839 let mut has_upper: bool = false;
840 for (scan_idx, &byte) in raw_line.iter().enumerate() {
841 if byte == COLON_U8 {
842 colon_pos = scan_idx;
843 break;
844 }
845 if !HTTP_HEADER_TOKEN_TABLE[byte as usize] {
846 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
847 }
848 if byte.is_ascii_uppercase() {
849 has_upper = true;
850 }
851 }
852 if colon_pos == 0 || colon_pos == raw_line.len() {
853 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
854 }
855 let key_bytes: &[u8] = &raw_line[..colon_pos];
856 // SAFETY: Every byte passed `HTTP_HEADER_TOKEN_TABLE`, which only accepts ASCII (< 0x80).
857 let key: &str = unsafe { from_utf8_unchecked(key_bytes) };
858 Self::check_http_header_key_size(key, max_header_key_size)?;
859 let raw_val: &[u8] = &raw_line[colon_pos + 1..];
860 let Some(is_ascii_val) = r#fn::validate_header_value_swar(raw_val) else {
861 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
862 };
863 let mut val_start: usize = 0;
864 let mut val_end: usize = raw_val.len();
865 while val_start < val_end
866 && (raw_val[val_start] == SPACE_U8 || raw_val[val_start] == TAB_U8)
867 {
868 val_start += 1;
869 }
870 while val_end > val_start
871 && (raw_val[val_end - 1] == SPACE_U8 || raw_val[val_end - 1] == TAB_U8)
872 {
873 val_end -= 1;
874 }
875 let value: &str = if is_ascii_val {
876 // SAFETY: `is_ascii_val` guarantees every byte in `raw_val` is ASCII (< 0x80).
877 unsafe { from_utf8_unchecked(&raw_val[val_start..val_end]) }
878 } else {
879 match from_utf8(&raw_val[val_start..val_end]) {
880 Ok(text) => text,
881 Err(_) => {
882 return Err(RequestError::ReadConnection(HttpStatus::BadRequest));
883 }
884 }
885 };
886 Self::check_http_header_value_size(value, max_header_value_size)?;
887 match key.len() {
888 4 if key.eq_ignore_ascii_case(HOST) => {
889 if host_seen || !is_valid_http_host(value) {
890 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
891 }
892 host_seen = true;
893 host.clear();
894 host.push_str(value);
895 }
896 14 if key.eq_ignore_ascii_case(CONTENT_LENGTH) => {
897 if transfer_encoding_seen {
898 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
899 }
900 if content_length_seen {
901 return Err(RequestError::InvalidContentLength(
902 HttpStatus::BadRequest,
903 ));
904 }
905 content_length_seen = true;
906 content_size = Self::check_http_body_size(value, max_body_size)?;
907 }
908 17 if key.eq_ignore_ascii_case(HTTP_HEADER_TRANSFER_ENCODING) => {
909 if *version != HTTP_HOST_REQUIRED_VERSION || content_length_seen {
910 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
911 }
912 transfer_encoding_seen = true;
913 }
914 _ => {}
915 }
916 Self::insert_http_header_from_pool(headers, &mut pool, key, has_upper, value);
917 }
918 Ok(())
919 },
920 );
921 header_result?;
922 if incomplete_head {
923 self.reset();
924 line_buffer.clear();
925 return Ok(None);
926 }
927 if *version == HTTP_HOST_REQUIRED_VERSION && !host_seen {
928 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
929 }
930 if transfer_encoding_seen {
931 let values: &VecDeque<String> = headers
932 .get(HTTP_HEADER_TRANSFER_ENCODING)
933 .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
934 return Ok(Some((
935 r#fn::parse_transfer_encoding(values)?,
936 pos,
937 target_start,
938 target_end,
939 )));
940 }
941 Ok(Some((
942 RequestFraming::Fixed(content_size),
943 pos,
944 target_start,
945 target_end,
946 )))
947 }
948
949 /// Parses HTTP headers from a buffered reader into this request.
950 ///
951 /// This method reads header lines from the provided buffered reader until an empty line
952 /// is encountered, which indicates the end of headers. It checks header count, length,
953 /// and content according to the provided configuration. The request's headers map and
954 /// host string are expected to be empty; they are filled without reallocating when they
955 /// already have sufficient capacity.
956 ///
957 /// The line buffer belongs to the caller so that a keep-alive connection
958 /// reads every header line of every request into the same allocation.
959 ///
960 /// # Arguments
961 ///
962 /// - `&mut R` - A mutable reference to a buffered reader, which requires the
963 /// `AsyncBufReadExt + Unpin` bound.
964 /// - `&RequestConfig` - Configuration for security limits and buffer settings.
965 /// - `&mut String` - The buffer the header lines are read into.
966 ///
967 /// # Returns
968 ///
969 /// - `Result<RequestFraming, RequestError>` - The body framing, or an error if parsing fails.
970 pub(crate) async fn get_http_headers<R>(
971 &mut self,
972 reader: &mut R,
973 config: &RequestConfig,
974 header_line_buffer: &mut String,
975 ) -> Result<RequestFraming, RequestError>
976 where
977 R: AsyncBufReadExt + Unpin,
978 {
979 let Request {
980 headers,
981 host,
982 version,
983 ..
984 } = self;
985 let max_header_count: usize = config.get_max_header_count();
986 let max_header_key_size: usize = config.get_max_header_key_size();
987 let max_header_value_size: usize = config.get_max_header_value_size();
988 let max_body_size: usize = config.get_max_body_size();
989 let mut content_size: usize = 0;
990 let mut header_count: usize = 0;
991 let mut content_length_seen: bool = false;
992 let mut transfer_encoding_seen: bool = false;
993 let mut host_seen: bool = false;
994 let max_header_line: usize = if max_header_key_size
995 == DEFAULT_LOW_SECURITY_MAX_HEADER_KEY_SIZE
996 || max_header_value_size == DEFAULT_LOW_SECURITY_MAX_HEADER_VALUE_SIZE
997 {
998 usize::MAX
999 } else {
1000 max_header_key_size
1001 .saturating_add(max_header_value_size)
1002 .saturating_add(HTTP_HEADER_LINE_OVERHEAD)
1003 };
1004 loop {
1005 let line_len: usize = read_http_line_bounded(
1006 reader,
1007 header_line_buffer,
1008 max_header_line,
1009 RequestError::HeaderLineTooLong(HttpStatus::RequestHeaderFieldsTooLarge),
1010 )
1011 .await?;
1012 if line_len == 0 {
1013 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1014 }
1015 let header_line: &str = header_line_buffer
1016 .strip_suffix(HTTP_HEADER_LINE_FEED)
1017 .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
1018 let header_line: &str = header_line
1019 .strip_suffix(HTTP_HEADER_CARRIAGE_RETURN)
1020 .unwrap_or(header_line);
1021 if header_line.is_empty() {
1022 break;
1023 }
1024 if header_line.starts_with(HTTP_HEADER_OPTIONAL_WHITESPACE) {
1025 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1026 }
1027 header_count += 1;
1028 Self::check_http_header_count(header_count, max_header_count)?;
1029 let (key, value_part): (&str, &str) = header_line
1030 .split_once(COLON)
1031 .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
1032 let valid_key: bool = key.bytes().all(|byte: u8| {
1033 byte.is_ascii_alphanumeric() || HTTP_HEADER_TOKEN_PUNCTUATION.contains(&byte)
1034 });
1035 if key.is_empty() || !valid_key {
1036 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1037 }
1038 Self::check_http_header_key_size(key, max_header_key_size)?;
1039 if value_part.bytes().any(|byte: u8| {
1040 (byte < HTTP_HEADER_CONTROL_LIMIT && byte != HTTP_HEADER_TAB)
1041 || byte == HTTP_HEADER_DELETE
1042 }) {
1043 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1044 }
1045 let value: &str = value_part.trim_matches(HTTP_HEADER_OPTIONAL_WHITESPACE);
1046 Self::check_http_header_value_size(value, max_header_value_size)?;
1047 match key {
1048 key if key.eq_ignore_ascii_case(HTTP_HEADER_TRANSFER_ENCODING) => {
1049 if *version != HTTP_HOST_REQUIRED_VERSION || content_length_seen {
1050 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1051 }
1052 transfer_encoding_seen = true;
1053 }
1054 key if key.eq_ignore_ascii_case(HOST) => {
1055 if host_seen || !is_valid_http_host(value) {
1056 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1057 }
1058 host_seen = true;
1059 host.clear();
1060 host.push_str(value);
1061 }
1062 key if key.eq_ignore_ascii_case(CONTENT_LENGTH) => {
1063 if transfer_encoding_seen {
1064 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1065 }
1066 if content_length_seen {
1067 return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
1068 }
1069 content_length_seen = true;
1070 content_size = Self::check_http_body_size(value, max_body_size)?;
1071 }
1072 _ => {}
1073 }
1074 Self::insert_http_header(headers, key, value);
1075 }
1076 if *version == HTTP_HOST_REQUIRED_VERSION && !host_seen {
1077 return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1078 }
1079 if transfer_encoding_seen {
1080 let values: &VecDeque<String> = headers
1081 .get(HTTP_HEADER_TRANSFER_ENCODING)
1082 .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
1083 return r#fn::parse_transfer_encoding(values);
1084 }
1085 Ok(RequestFraming::Fixed(content_size))
1086 }
1087
1088 /// Replaces wire chunk framing with the decoded content length.
1089 #[cold]
1090 pub(crate) fn normalize_chunked_headers(&mut self) {
1091 let mut digits: [u8; B_20] = [0; B_20];
1092 let length: &str = render_length(self.get_body().len(), &mut digits);
1093 let headers: &mut RequestHeaders = self.get_mut_headers();
1094 headers.remove(HTTP_HEADER_TRANSFER_ENCODING);
1095 headers.remove(HTTP_HEADER_TRAILER);
1096 Self::insert_http_header(headers, CONTENT_LENGTH, length);
1097 }
1098
1099 /// Stores one ASCII header using an already-borrowed worker-local entry pool.
1100 ///
1101 /// # Arguments
1102 ///
1103 /// - `&mut RequestHeaders` - The header map to store the header in.
1104 /// - `&mut Vec<(String, VecDeque<String>)>` - Borrowed worker-local header entry pool.
1105 /// - `&str` - The validated ASCII header name, as it arrived.
1106 /// - `bool` - Whether `key` contains any ASCII uppercase character.
1107 /// - `&str` - The header value.
1108 #[inline(always)]
1109 fn insert_http_header_from_pool(
1110 headers: &mut RequestHeaders,
1111 pool: &mut Vec<(String, VecDeque<String>)>,
1112 key: &str,
1113 has_upper: bool,
1114 value: &str,
1115 ) {
1116 let (mut name, mut values): (String, VecDeque<String>) = pool
1117 .pop()
1118 .unwrap_or_else(|| (String::new(), VecDeque::new()));
1119 name.clear();
1120 name.push_str(key);
1121 if has_upper {
1122 name.make_ascii_lowercase();
1123 }
1124 match headers.entry(name) {
1125 Entry::Occupied(mut occupied) => {
1126 occupied.get_mut().push_back(value.to_owned());
1127 if values.capacity() <= MAX_POOLED_HEADER_VALUE_CAPACITY
1128 && pool.len() < MAX_POOLED_HEADER_ENTRIES
1129 {
1130 pool.push((String::new(), values));
1131 }
1132 }
1133 Entry::Vacant(vacant) => {
1134 if values.len() == 1 {
1135 values[0].clear();
1136 values[0].push_str(value);
1137 } else {
1138 while values.len() > 1 {
1139 values.pop_back();
1140 }
1141 if let Some(slot) = values.front_mut() {
1142 slot.clear();
1143 slot.push_str(value);
1144 } else {
1145 values.push_back(value.to_owned());
1146 }
1147 }
1148 vacant.insert(values);
1149 }
1150 }
1151 }
1152
1153 /// Stores one header, reusing a pooled name and value where possible.
1154 ///
1155 /// The name is lowercased into the buffer of a recycled entry and the
1156 /// value is written into that entry's value buffer, so a header that was
1157 /// already seen on this connection costs no allocation at all.
1158 ///
1159 /// # Arguments
1160 ///
1161 /// - `&mut RequestHeaders` - The header map to store the header in.
1162 /// - `&str` - The header name, as it arrived.
1163 /// - `&str` - The header value.
1164 fn insert_http_header(headers: &mut RequestHeaders, key: &str, value: &str) {
1165 let (mut name, mut values): (String, VecDeque<String>) =
1166 take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
1167 name.clear();
1168 name.push_str(key);
1169 name.make_ascii_lowercase();
1170 match headers.entry(name) {
1171 Entry::Occupied(mut occupied) => {
1172 // The header repeats: it keeps every value it was given.
1173 occupied.get_mut().push_back(value.to_string());
1174 return_header_entry((String::new(), values));
1175 }
1176 Entry::Vacant(vacant) => {
1177 // A recycled entry may carry the values of a header that was
1178 // sent more than once. Those values belong to that header, so
1179 // only the first one is kept and the rest are dropped.
1180 while values.len() > 1 {
1181 values.pop_back();
1182 }
1183 if values.is_empty() {
1184 values.push_back(String::new());
1185 }
1186 if let Some(slot) = values.front_mut() {
1187 slot.clear();
1188 slot.push_str(value);
1189 }
1190 vacant.insert(values);
1191 }
1192 }
1193 }
1194
1195 /// Reads the request body from the buffered reader into the given buffer.
1196 ///
1197 /// The target buffer is cleared and resized to the expected content size,
1198 /// retaining its allocation when it already has sufficient capacity.
1199 ///
1200 /// # Arguments
1201 ///
1202 /// - `&mut R` - The buffered reader to read from, which requires the `AsyncRead + Unpin` bound.
1203 /// - `&mut Vec<u8>` - The buffer to read the body bytes into.
1204 /// - `usize` - The expected content size.
1205 ///
1206 /// # Returns
1207 ///
1208 /// - `Result<(), RequestError>` - Ok on success, or an error if reading fails.
1209 #[inline(always)]
1210 pub(crate) async fn fill_http_body<R>(
1211 reader: &mut R,
1212 body: &mut Vec<u8>,
1213 content_size: usize,
1214 ) -> Result<(), RequestError>
1215 where
1216 R: AsyncRead + Unpin,
1217 {
1218 body.clear();
1219 let mut remaining: usize = content_size;
1220 while remaining > 0 {
1221 let step: usize = remaining.min(HTTP_BODY_READ_CHUNK_SIZE);
1222 let start: usize = body.len();
1223 body.try_reserve(step)
1224 .map_err(|_| RequestError::ContentLengthTooLarge(HttpStatus::PayloadTooLarge))?;
1225 body.resize(start + step, 0);
1226 let mut filled: usize = 0;
1227 while filled < step {
1228 let read_len: usize =
1229 AsyncReadExt::read(reader, &mut body[start + filled..]).await?;
1230 if read_len == 0 {
1231 body.truncate(start + filled);
1232 return Err(RequestError::ReadConnection(HttpStatus::BadRequest));
1233 }
1234 filled += read_len;
1235 }
1236 remaining -= step;
1237 }
1238 Ok(())
1239 }
1240
1241 /// Tries to get a query parameter by key.
1242 ///
1243 /// The key type must implement `AsRef<str>` conversion. A key that repeats in
1244 /// the query carries every one of its values.
1245 ///
1246 /// # Arguments
1247 ///
1248 /// - `K` - The query parameter key, which implements `AsRef<str>`.
1249 ///
1250 /// # Returns
1251 ///
1252 /// - `Option<VecDeque<String>>` - Every value of the parameter if it exists.
1253 #[inline(always)]
1254 pub fn try_get_query<K>(&self, key: K) -> Option<VecDeque<String>>
1255 where
1256 K: AsRef<str>,
1257 {
1258 self.get_querys().get(key.as_ref()).cloned()
1259 }
1260
1261 /// Tries to get the first query parameter value by key.
1262 ///
1263 /// Use this when the parameter is expected to appear once; use
1264 /// `try_get_query` when every value matters.
1265 ///
1266 /// # Arguments
1267 ///
1268 /// - `K` - The query parameter key, which implements `AsRef<str>`.
1269 ///
1270 /// # Returns
1271 ///
1272 /// - `Option<String>` - The first parameter value if it exists.
1273 #[inline(always)]
1274 pub fn try_get_query_front<K>(&self, key: K) -> Option<String>
1275 where
1276 K: AsRef<str>,
1277 {
1278 self.get_querys()
1279 .get(key.as_ref())
1280 .and_then(|values: &VecDeque<String>| values.front().cloned())
1281 }
1282
1283 /// Tries to get the last query parameter value by key.
1284 ///
1285 /// # Arguments
1286 ///
1287 /// - `K` - The query parameter key, which implements `AsRef<str>`.
1288 ///
1289 /// # Returns
1290 ///
1291 /// - `Option<String>` - The last parameter value if it exists.
1292 #[inline(always)]
1293 pub fn try_get_query_back<K>(&self, key: K) -> Option<String>
1294 where
1295 K: AsRef<str>,
1296 {
1297 self.get_querys()
1298 .get(key.as_ref())
1299 .and_then(|values: &VecDeque<String>| values.back().cloned())
1300 }
1301
1302 /// Tries to get the number of values of a query parameter.
1303 ///
1304 /// # Arguments
1305 ///
1306 /// - `K` - The query parameter key, which implements `AsRef<str>`.
1307 ///
1308 /// # Returns
1309 ///
1310 /// - `Option<usize>` - The number of values if the parameter exists.
1311 #[inline(always)]
1312 pub fn try_get_query_size<K>(&self, key: K) -> Option<usize>
1313 where
1314 K: AsRef<str>,
1315 {
1316 self.get_querys()
1317 .get(key.as_ref())
1318 .map(|values: &VecDeque<String>| values.len())
1319 }
1320
1321 /// Checks whether a query parameter exists.
1322 ///
1323 /// # Arguments
1324 ///
1325 /// - `K` - The query parameter key, which implements `AsRef<str>`.
1326 ///
1327 /// # Returns
1328 ///
1329 /// - `bool` - Whether the parameter exists.
1330 #[inline(always)]
1331 pub fn has_query<K>(&self, key: K) -> bool
1332 where
1333 K: AsRef<str>,
1334 {
1335 self.get_querys().contains_key(key.as_ref())
1336 }
1337
1338 /// Gets a query parameter by key.
1339 ///
1340 /// # Arguments
1341 ///
1342 /// - `K` - The query parameter key, which implements `AsRef<str>`.
1343 ///
1344 /// # Returns
1345 ///
1346 /// - `VecDeque<String>` - Every value of the parameter.
1347 ///
1348 /// # Panics
1349 ///
1350 /// This function will panic if the query parameter key is not found.
1351 #[inline(always)]
1352 pub fn get_query<K>(&self, key: K) -> VecDeque<String>
1353 where
1354 K: AsRef<str>,
1355 {
1356 self.try_get_query(key).unwrap()
1357 }
1358
1359 /// Gets the first query parameter value by key.
1360 ///
1361 /// # Arguments
1362 ///
1363 /// - `K` - The query parameter key, which implements `AsRef<str>`.
1364 ///
1365 /// # Returns
1366 ///
1367 /// - `String` - The first parameter value.
1368 ///
1369 /// # Panics
1370 ///
1371 /// This function will panic if the query parameter key is not found.
1372 #[inline(always)]
1373 pub fn get_query_front<K>(&self, key: K) -> String
1374 where
1375 K: AsRef<str>,
1376 {
1377 self.try_get_query_front(key).unwrap()
1378 }
1379
1380 /// Retrieves the number of query parameters.
1381 ///
1382 /// # Returns
1383 ///
1384 /// - `usize` - The count of distinct query parameter keys.
1385 #[inline(always)]
1386 pub fn get_querys_size(&self) -> usize {
1387 self.get_querys().len()
1388 }
1389
1390 /// Looks up a header value list case-insensitively without allocating when
1391 /// the key is already lowercase or fits in the stack buffer.
1392 ///
1393 /// # Arguments
1394 ///
1395 /// - `&str` - The header name to look up.
1396 ///
1397 /// # Returns
1398 ///
1399 /// - `Option<&VecDeque<String>>` - Reference to the stored values, if present.
1400 #[inline(always)]
1401 fn get_header_ref(&self, key: &str) -> Option<&VecDeque<String>> {
1402 let bytes: &[u8] = key.as_bytes();
1403 if !bytes.iter().any(|byte: &u8| byte.is_ascii_uppercase()) {
1404 return self.get_headers().get(key);
1405 }
1406 if bytes.len() <= STACK_HEADER_KEY_LIMIT {
1407 let mut stack_buf: [u8; STACK_HEADER_KEY_LIMIT] = [0; STACK_HEADER_KEY_LIMIT];
1408 let mut idx: usize = 0;
1409 while idx < bytes.len() {
1410 stack_buf[idx] = bytes[idx].to_ascii_lowercase();
1411 idx += 1;
1412 }
1413 if let Ok(lower) = from_utf8(&stack_buf[..bytes.len()]) {
1414 return self.get_headers().get(lower);
1415 }
1416 }
1417 self.get_headers().get(&key.to_ascii_lowercase())
1418 }
1419
1420 /// Tries to retrieve the value of a request header by its key.
1421 ///
1422 /// The key is matched case-insensitively, because the parser stores every
1423 /// header name lowercased and an HTTP header name is case-insensitive by
1424 /// specification. Looking a header up with `Content-Type` and with
1425 /// `content-type` therefore find the same value.
1426 ///
1427 /// # Arguments
1428 ///
1429 /// - `K` - The header's key, which must implement `AsRef<str>`.
1430 ///
1431 /// # Returns
1432 ///
1433 /// - `Option<VecDeque<String>>` - The optional header values.
1434 #[inline(always)]
1435 pub fn try_get_header<K>(&self, key: K) -> Option<VecDeque<String>>
1436 where
1437 K: AsRef<str>,
1438 {
1439 self.get_header_ref(key.as_ref()).cloned()
1440 }
1441
1442 /// Retrieves the value of a request header by its key.
1443 ///
1444 /// # Arguments
1445 ///
1446 /// - `K` - The header's key, which must implement `AsRef<str>`.
1447 ///
1448 /// # Returns
1449 ///
1450 /// - `VecDeque<String>` - The optional header values.
1451 ///
1452 /// # Panics
1453 ///
1454 /// This function will panic if the header key is not found.
1455 #[inline(always)]
1456 pub fn get_header<K>(&self, key: K) -> VecDeque<String>
1457 where
1458 K: AsRef<str>,
1459 {
1460 self.try_get_header(key).unwrap()
1461 }
1462
1463 /// Tries to retrieve the first value of a request header by its key.
1464 ///
1465 /// # Arguments
1466 ///
1467 /// - `K` - The header's key, which must implement `AsRef<str>`.
1468 ///
1469 /// # Returns
1470 ///
1471 /// - `Option<String>` - The first header value if exists.
1472 #[inline(always)]
1473 pub fn try_get_header_front<K>(&self, key: K) -> Option<String>
1474 where
1475 K: AsRef<str>,
1476 {
1477 self.get_header_ref(key.as_ref())
1478 .and_then(|header_values: &VecDeque<String>| header_values.front().cloned())
1479 }
1480
1481 /// Retrieves the first value of a request header by its key.
1482 ///
1483 /// # Arguments
1484 ///
1485 /// - `K` - The header's key, which must implement `AsRef<str>`.
1486 ///
1487 /// # Returns
1488 ///
1489 /// - `String` - The first header value if exists.
1490 ///
1491 /// # Panics
1492 ///
1493 /// This function will panic if the header key is not found.
1494 #[inline(always)]
1495 pub fn get_header_front<K>(&self, key: K) -> String
1496 where
1497 K: AsRef<str>,
1498 {
1499 self.try_get_header_front(key).unwrap()
1500 }
1501
1502 /// Tries to retrieve the last value of a request header by its key.
1503 ///
1504 /// # Arguments
1505 ///
1506 /// - `K` - The header's key, which must implement `AsRef<str>`.
1507 ///
1508 /// # Returns
1509 ///
1510 /// - `Option<String>` - The last header value if exists.
1511 #[inline(always)]
1512 pub fn try_get_header_back<K>(&self, key: K) -> Option<String>
1513 where
1514 K: AsRef<str>,
1515 {
1516 self.get_header_ref(key.as_ref())
1517 .and_then(|header_values: &VecDeque<String>| header_values.back().cloned())
1518 }
1519
1520 /// Retrieves the last value of a request header by its key.
1521 ///
1522 /// # Arguments
1523 ///
1524 /// - `K` - The header's key, which must implement `AsRef<str>`.
1525 ///
1526 /// # Returns
1527 ///
1528 /// - `String` - The last header value if exists.
1529 ///
1530 /// # Panics
1531 ///
1532 /// This function will panic if the header key is not found.
1533 #[inline(always)]
1534 pub fn get_header_back<K>(&self, key: K) -> String
1535 where
1536 K: AsRef<str>,
1537 {
1538 self.try_get_header_back(key).unwrap()
1539 }
1540
1541 /// Tries to retrieve the number of values for a specific header.
1542 ///
1543 /// # Arguments
1544 ///
1545 /// - `K` - The header's key, which must implement `AsRef<str>`.
1546 ///
1547 /// # Returns
1548 ///
1549 /// - `Option<usize>` - The count of values for the header if exists.
1550 #[inline(always)]
1551 pub fn try_get_header_size<K>(&self, key: K) -> Option<usize>
1552 where
1553 K: AsRef<str>,
1554 {
1555 self.get_header_ref(key.as_ref())
1556 .map(|header_values: &VecDeque<String>| header_values.len())
1557 }
1558
1559 /// Retrieves the number of values for a specific header.
1560 ///
1561 /// # Arguments
1562 ///
1563 /// - `K` - The header's key, which must implement `AsRef<str>`.
1564 ///
1565 /// # Returns
1566 ///
1567 /// - `usize` - The count of values for the header.
1568 ///
1569 /// # Panics
1570 ///
1571 /// This function will panic if the header key is not found.
1572 #[inline(always)]
1573 pub fn get_header_size<K>(&self, key: K) -> usize
1574 where
1575 K: AsRef<str>,
1576 {
1577 self.try_get_header_size(key).unwrap()
1578 }
1579
1580 /// Retrieves the total number of header values across all headers.
1581 ///
1582 /// # Returns
1583 ///
1584 /// - `usize` - The total count of all header values.
1585 #[inline(always)]
1586 pub fn get_headers_values_size(&self) -> usize {
1587 self.get_headers()
1588 .values()
1589 .map(|header_values: &VecDeque<String>| header_values.len())
1590 .sum()
1591 }
1592
1593 /// Retrieves the number of unique headers.
1594 ///
1595 /// # Returns
1596 ///
1597 /// - `usize` - The count of unique header keys.
1598 #[inline(always)]
1599 pub fn get_headers_size(&self) -> usize {
1600 self.get_headers().len()
1601 }
1602
1603 /// Checks if a specific header exists.
1604 ///
1605 /// # Arguments
1606 ///
1607 /// - `K` - The header key to check, which must implement `AsRef<str>`.
1608 ///
1609 /// # Returns
1610 ///
1611 /// - `bool` - Whether the header exists.
1612 #[inline(always)]
1613 pub fn has_header<K>(&self, key: K) -> bool
1614 where
1615 K: AsRef<str>,
1616 {
1617 self.get_header_ref(key.as_ref()).is_some()
1618 }
1619
1620 /// Checks if a header contains a specific value.
1621 ///
1622 /// # Arguments
1623 ///
1624 /// - `K` - The header key to check, which must implement `AsRef<str>`.
1625 /// - `V` - The value to search for, which must implement `AsRef<str>`.
1626 ///
1627 /// # Returns
1628 ///
1629 /// - `bool` - Whether the header contains the value.
1630 #[inline(always)]
1631 pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
1632 where
1633 K: AsRef<str>,
1634 V: AsRef<str>,
1635 {
1636 if let Some(values) = self.get_header_ref(key.as_ref()) {
1637 values.iter().any(|data: &String| data == value.as_ref())
1638 } else {
1639 false
1640 }
1641 }
1642
1643 /// Checks `If-None-Match` against the entity-tag of an existing representation.
1644 ///
1645 /// This explicitly invoked helper borrows normalized request headers and allocates nothing.
1646 /// Strong and weak tags use case-sensitive weak comparison of their opaque values.
1647 /// Repeated fields form one list; optional spaces, tabs, and empty list members are ignored.
1648 /// A wildcard matches only when the entire field combination is a standalone `*`.
1649 /// Missing headers, empty lists, invalid tags, or any malformed suffix return `false`,
1650 /// even if an earlier tag matched. The current tag must be exactly one valid entity-tag,
1651 /// without surrounding whitespace. Quoted commas and empty opaque values are valid;
1652 /// backslashes are literal bytes, not escape characters.
1653 ///
1654 /// Call only for a representation that already exists. This does not send a response,
1655 /// automatically generate a 304, or implement complete HTTP precondition evaluation.
1656 /// Callers decide whether to send 304 for GET/HEAD or 412 for other methods and must
1657 /// handle precondition ordering themselves. Do not use this for `If-Match`, which
1658 /// requires strong comparison.
1659 ///
1660 /// # Arguments
1661 ///
1662 /// - `&str` - The current representation's complete strong or weak entity-tag.
1663 ///
1664 /// # Returns
1665 ///
1666 /// - `bool` - Whether a completely valid `If-None-Match` matches the existing representation.
1667 #[must_use]
1668 pub fn matches_if_none_match(&self, current_etag: &str) -> bool {
1669 let current: &[u8] = match r#fn::parse_entity_tag(current_etag.as_bytes()) {
1670 Some((opaque, [])) => opaque,
1671 _ => return false,
1672 };
1673 let values: &VecDeque<String> = match self.get_headers().get(IF_NONE_MATCH) {
1674 Some(values) => values,
1675 None => return false,
1676 };
1677 if values.len() == 1
1678 && values.front().is_some_and(|value: &String| {
1679 value
1680 .trim_matches(&HTTP_HEADER_OPTIONAL_WHITESPACE[..])
1681 .as_bytes()
1682 == ENTITY_TAG_WILDCARD
1683 })
1684 {
1685 return true;
1686 }
1687 let mut matched: bool = false;
1688 for value in values {
1689 let mut remaining: &[u8] = value.as_bytes();
1690 while !remaining.is_empty() {
1691 while remaining
1692 .first()
1693 .is_some_and(|byte: &u8| ENTITY_TAG_LIST_PADDING.contains(byte))
1694 {
1695 remaining = &remaining[1..];
1696 }
1697 if remaining.is_empty() {
1698 break;
1699 }
1700 let (candidate, suffix): (&[u8], &[u8]) = match r#fn::parse_entity_tag(remaining) {
1701 Some(parsed) => parsed,
1702 None => return false,
1703 };
1704 matched |= candidate == current;
1705 remaining = suffix;
1706 while remaining
1707 .first()
1708 .is_some_and(|byte: &u8| ENTITY_TAG_OPTIONAL_WHITESPACE.contains(byte))
1709 {
1710 remaining = &remaining[1..];
1711 }
1712 if remaining.is_empty() {
1713 break;
1714 }
1715 if remaining.first() != Some(&ENTITY_TAG_SEPARATOR) {
1716 return false;
1717 }
1718 remaining = &remaining[1..];
1719 }
1720 }
1721 matched
1722 }
1723
1724 /// Tries to parse cookies from the `Cookie` header.
1725 ///
1726 /// This method retrieves the `Cookie` header value and parses it into
1727 /// a collection of key-value pairs representing the cookies.
1728 ///
1729 /// # Returns
1730 ///
1731 /// - `Option<HashMapXxHash3_64<String, String>>` - The parsed cookies if the header exists, otherwise `None`.
1732 #[inline(always)]
1733 pub fn try_get_cookies(&self) -> Option<HashMapXxHash3_64<String, String>> {
1734 let values: &VecDeque<String> = self.get_header_ref(COOKIE)?;
1735 if values.is_empty() {
1736 return None;
1737 }
1738 if values.len() == 1
1739 && let Some(single) = values.front()
1740 {
1741 return Some(Cookie::parse(single));
1742 }
1743 let mut merged: HashMapXxHash3_64<String, String> = hash_map_xx_hash3_64();
1744 for header_value in values {
1745 let parsed: HashMapXxHash3_64<String, String> = Cookie::parse(header_value);
1746 for (name, value) in parsed {
1747 merged.entry(name).or_insert(value);
1748 }
1749 }
1750 Some(merged)
1751 }
1752
1753 /// Parses cookies from the `Cookie` header.
1754 ///
1755 /// This method retrieves the `Cookie` header value and parses it into
1756 /// a collection of key-value pairs representing the cookies.
1757 ///
1758 /// # Returns
1759 ///
1760 /// - `HashMapXxHash3_64<String, String>` - The parsed cookies.
1761 ///
1762 /// # Panics
1763 ///
1764 /// This function will panic if the `Cookie` header is not found.
1765 #[inline(always)]
1766 pub fn get_cookies(&self) -> HashMapXxHash3_64<String, String> {
1767 self.try_get_cookies().unwrap()
1768 }
1769
1770 /// Tries to borrow a cookie value by its key without heap allocation.
1771 ///
1772 /// # Arguments
1773 ///
1774 /// - `K` - The cookie key, which implements `AsRef<str>`.
1775 ///
1776 /// # Returns
1777 ///
1778 /// - `Option<&str>` - Borrowed cookie value slice if present and valid.
1779 #[inline(always)]
1780 pub fn try_get_cookie_ref<K>(&self, key: K) -> Option<&str>
1781 where
1782 K: AsRef<str>,
1783 {
1784 let key_ref: &str = key.as_ref();
1785 let values: &VecDeque<String> = self.get_header_ref(COOKIE)?;
1786 for header_value in values {
1787 if let Some(found) = Cookie::find_value(header_value, key_ref) {
1788 return Some(found);
1789 }
1790 }
1791 None
1792 }
1793
1794 /// Tries to get a cookie value by its key.
1795 ///
1796 /// Scans the `Cookie` header slices directly without allocating an intermediate map.
1797 ///
1798 /// # Arguments
1799 ///
1800 /// - `K` - The cookie key, which implements `AsRef<str>`.
1801 ///
1802 /// # Returns
1803 ///
1804 /// - `Option<String>` - The cookie value if exists.
1805 #[inline(always)]
1806 pub fn try_get_cookie<K>(&self, key: K) -> Option<String>
1807 where
1808 K: AsRef<str>,
1809 {
1810 self.try_get_cookie_ref(key).map(str::to_owned)
1811 }
1812
1813 /// Gets a cookie value by its key.
1814 ///
1815 /// This method first parses the cookies from the `Cookie` header,
1816 /// then retrieves the value for the specified key.
1817 ///
1818 /// # Arguments
1819 ///
1820 /// - `K` - The cookie key, which implements `AsRef<str>`.
1821 ///
1822 /// # Returns
1823 ///
1824 /// - `String` - The cookie value.
1825 ///
1826 /// # Panics
1827 ///
1828 /// This function will panic if the `Cookie` header is not found
1829 /// or the cookie key does not exist.
1830 #[inline(always)]
1831 pub fn get_cookie<K>(&self, key: K) -> String
1832 where
1833 K: AsRef<str>,
1834 {
1835 self.try_get_cookie(key).unwrap()
1836 }
1837
1838 /// Retrieves the upgrade type from the request headers.
1839 ///
1840 /// This method looks for the `UPGRADE` header and attempts to parse its value
1841 /// as_ref an `UpgradeType`. If the header is missing or the value is invalid,
1842 /// it returns the default `UpgradeType`.
1843 ///
1844 /// # Returns
1845 ///
1846 /// - `UpgradeType` - The parsed upgrade type.
1847 #[inline(always)]
1848 pub fn get_upgrade_type(&self) -> UpgradeType {
1849 self.get_headers()
1850 .get(UPGRADE)
1851 .and_then(|values: &VecDeque<String>| values.back())
1852 .and_then(|data: &String| data.parse::<UpgradeType>().ok())
1853 .unwrap_or_default()
1854 }
1855
1856 /// Retrieves the body content of the request as a UTF-8 encoded string.
1857 ///
1858 /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as a string.
1859 /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
1860 ///
1861 /// # Returns
1862 ///
1863 /// - `String` - The body content as a string.
1864 #[inline(always)]
1865 pub fn get_body_string(&self) -> String {
1866 String::from_utf8_lossy(self.get_body()).into_owned()
1867 }
1868
1869 /// Deserializes the body content of the request as_ref a specified type `T`.
1870 ///
1871 /// This method first retrieves the body content as a byte slice using `self.get_body()`.
1872 /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
1873 ///
1874 /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
1875 ///
1876 /// # Returns
1877 ///
1878 /// - `Result<T, serde_json::Error>` - The deserialization result.
1879 #[inline(always)]
1880 pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
1881 where
1882 T: DeserializeOwned,
1883 {
1884 from_slice(self.get_body())
1885 }
1886
1887 /// Deserializes the body content of the request as_ref a specified type `T`.
1888 ///
1889 /// This method first retrieves the body content as a byte slice using `self.get_body()`.
1890 /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
1891 ///
1892 /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
1893 ///
1894 /// # Returns
1895 ///
1896 /// - `T` - The deserialized body content.
1897 ///
1898 /// # Panics
1899 ///
1900 /// This function will panic if the deserialization fails.
1901 #[inline(always)]
1902 pub fn get_body_json<T>(&self) -> T
1903 where
1904 T: DeserializeOwned,
1905 {
1906 self.try_get_body_json().unwrap()
1907 }
1908
1909 /// Checks whether the WebSocket upgrade is enabled for this request.
1910 ///
1911 /// This method determines if the `UPGRADE` header indicates a WebSocket connection.
1912 ///
1913 /// # Returns
1914 ///
1915 /// - `bool` - Whether WebSocket upgrade is enabled.
1916 #[inline(always)]
1917 pub fn is_ws_upgrade_type(&self) -> bool {
1918 self.get_upgrade_type().is_ws()
1919 }
1920
1921 /// Checks whether the request declares a `multipart/form-data` body.
1922 ///
1923 /// # Returns
1924 ///
1925 /// - `bool` - Whether the request content type is `multipart/form-data`.
1926 #[inline(always)]
1927 pub fn is_multipart_form_data(&self) -> bool {
1928 self.try_get_content_type()
1929 .map(|content_type: String| MultipartFormData::is_form_data(content_type))
1930 .unwrap_or(false)
1931 }
1932
1933 /// Tries to get the request content type with its parameters stripped.
1934 ///
1935 /// A `Content-Type` header such as `text/html; charset=utf-8` yields the
1936 /// media type alone, so a caller comparing against a media type does not
1937 /// have to know that parameters may follow it.
1938 ///
1939 /// # Returns
1940 ///
1941 /// - `Option<String>` - The media type, or `None` when the header is absent.
1942 #[inline(always)]
1943 pub fn try_get_content_type(&self) -> Option<String> {
1944 self.try_get_header_front(CONTENT_TYPE)
1945 .map(|value: String| {
1946 value
1947 .split(SEMICOLON)
1948 .next()
1949 .unwrap_or(EMPTY_STR)
1950 .trim()
1951 .to_ascii_lowercase()
1952 })
1953 }
1954
1955 /// Tries to get one parameter of the request `Content-Type` header.
1956 ///
1957 /// The name is matched case-insensitively and a quoted value is unquoted,
1958 /// so both `boundary=abc` and `boundary="abc"` yield `abc`.
1959 ///
1960 /// # Arguments
1961 ///
1962 /// - `K` - The parameter name, which requires the `AsRef<str>` bound.
1963 ///
1964 /// # Returns
1965 ///
1966 /// - `Option<String>` - The parameter value, or `None` when absent.
1967 pub fn try_get_content_type_parameter<K>(&self, name: K) -> Option<String>
1968 where
1969 K: AsRef<str>,
1970 {
1971 let content_type: &str = self
1972 .get_headers()
1973 .get(CONTENT_TYPE)
1974 .and_then(|values: &VecDeque<String>| values.front())
1975 .map(String::as_str)?;
1976 let name: &str = name.as_ref();
1977 let mut matched: Option<String> = None;
1978 MultipartFormData::for_each_header_parameter(
1979 content_type,
1980 |index: usize, parameter: &str| {
1981 if index == 0 {
1982 return false;
1983 }
1984 let Some((key, value)) = parameter.trim().split_once(EQUAL) else {
1985 return false;
1986 };
1987 if !key.trim().eq_ignore_ascii_case(name) {
1988 return false;
1989 }
1990 let value: &str = value.trim();
1991 let value: &str = value
1992 .strip_prefix(MULTIPART_PARAMETER_QUOTE)
1993 .and_then(|value: &str| value.strip_suffix(MULTIPART_PARAMETER_QUOTE))
1994 .unwrap_or(value);
1995 if !value.is_empty() {
1996 matched = Some(value.to_string());
1997 return true;
1998 }
1999 false
2000 },
2001 );
2002 matched
2003 }
2004
2005 /// Tries to decode a `multipart/form-data` body into its parts.
2006 ///
2007 /// The boundary is read from the request `Content-Type` header rather than
2008 /// guessed, so a body whose content type declares no boundary, a truncated
2009 /// body, and a part without a name all yield `None`.
2010 ///
2011 /// # Returns
2012 ///
2013 /// - `Option<Vec<BodyPart>>` - The decoded parts, or `None` when unavailable.
2014 pub fn try_get_body_form_data(&self) -> Option<Vec<BodyPart>> {
2015 let boundary: String = self.try_get_content_type_parameter(MULTIPART_BOUNDARY_PARAMETER)?;
2016 MultipartFormData::parse(self.get_body(), &boundary)
2017 }
2018
2019 /// Decodes an `application/x-www-form-urlencoded` body into its fields.
2020 ///
2021 /// # Returns
2022 ///
2023 /// - `HashMapXxHash3_64<String, String>` - The decoded form fields.
2024 #[inline(always)]
2025 pub fn get_body_form(&self) -> HashMapXxHash3_64<String, String> {
2026 MultipartFormData::parse_url_encoded(self.get_body())
2027 }
2028
2029 /// Tries to get a plain text field of a `multipart/form-data` body.
2030 ///
2031 /// A part that uploads a file is skipped, so a file field never silently
2032 /// decodes as text.
2033 ///
2034 /// # Arguments
2035 ///
2036 /// - `K` - The form field name, which requires the `AsRef<str>` bound.
2037 ///
2038 /// # Returns
2039 ///
2040 /// - `Option<String>` - The field value, or `None` when absent or a file.
2041 pub fn try_get_body_form_data_text<K>(&self, name: K) -> Option<String>
2042 where
2043 K: AsRef<str>,
2044 {
2045 let parts: Vec<BodyPart> = self.try_get_body_form_data()?;
2046 MultipartFormData::try_get_part_text(&parts, name)
2047 }
2048
2049 /// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
2050 ///
2051 /// # Returns
2052 ///
2053 /// - `bool` - Whether the upgrade type is h2c.
2054 #[inline(always)]
2055 pub fn is_h2c_upgrade_type(&self) -> bool {
2056 self.get_upgrade_type().is_h2c()
2057 }
2058
2059 /// Checks if the current upgrade type is TLS (any version).
2060 ///
2061 /// # Returns
2062 ///
2063 /// - `bool` - Whether the upgrade type is TLS.
2064 #[inline(always)]
2065 pub fn is_tls_upgrade_type(&self) -> bool {
2066 self.get_upgrade_type().is_tls()
2067 }
2068
2069 /// Checks whether the upgrade type is unknown.
2070 ///
2071 /// # Returns
2072 ///
2073 /// - `bool` - Whether the upgrade type is unknown.
2074 #[inline(always)]
2075 pub fn is_unknown_upgrade_type(&self) -> bool {
2076 self.get_upgrade_type().is_unknown()
2077 }
2078
2079 /// Determines if a keep-alive connection should be enabled for this request.
2080 ///
2081 /// This function checks the `Connection` header and the HTTP version to determine
2082 /// if keep-alive should be enabled. The logic is as follows:
2083 ///
2084 /// 1. If the `Connection` header exists:
2085 /// - Returns `true` if the header value is "keep-alive" (case-insensitive).
2086 /// - Returns `false` if the header value is "close" (case-insensitive).
2087 /// 2. If no `Connection` header is present:
2088 /// - Returns `true` if the HTTP version is 1.1 or higher.
2089 /// - Returns `false` otherwise.
2090 ///
2091 /// # Returns
2092 ///
2093 /// - `bool` - Whether keep-alive should be enabled.
2094 #[inline(always)]
2095 pub fn is_enable_keep_alive(&self) -> bool {
2096 if let Some(values) = self.get_headers().get(CONNECTION) {
2097 let mut has_keep_alive: bool = false;
2098 for header_value in values {
2099 if header_value == KEEP_ALIVE {
2100 has_keep_alive = true;
2101 continue;
2102 }
2103 for token in header_value.split(COMMA) {
2104 let token: &str = token.trim_matches(HTTP_HEADER_OPTIONAL_WHITESPACE);
2105 if token.eq_ignore_ascii_case(CLOSE) {
2106 return self.is_ws_upgrade_type();
2107 }
2108 if token.eq_ignore_ascii_case(KEEP_ALIVE) {
2109 has_keep_alive = true;
2110 }
2111 }
2112 }
2113 if has_keep_alive {
2114 return true;
2115 }
2116 }
2117 self.get_version().is_http1_1_or_higher() || self.is_ws_upgrade_type()
2118 }
2119
2120 /// Determines if keep-alive should be disabled for this request.
2121 ///
2122 /// # Returns
2123 ///
2124 /// - `bool` - Whether keep-alive should be disabled.
2125 #[inline(always)]
2126 pub fn is_disable_keep_alive(&self) -> bool {
2127 !self.is_enable_keep_alive()
2128 }
2129}