Skip to main content

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)>, RequestError>` - The framing and
750    ///   number of bytes consumed 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)>, 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 max_path_size: usize = config.get_max_path_size();
782        Self::check_http_path_size(full_path, max_path_size)?;
783        let query: &str = Self::get_http_query(full_path, query_index, hash_index);
784        let max_query_count: usize = if max_path_size == DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
785            usize::MAX
786        } else {
787            HTTP_MAX_QUERY_PARAM_COUNT
788        };
789        Self::fill_http_querys(query, self.get_mut_querys(), max_query_count)?;
790        let path_slice: &str = Self::get_http_path(full_path, query_index, hash_index);
791        self.get_mut_path().push_str(path_slice);
792        self.set_version(version);
793        self.set_method(method);
794        let Request {
795            headers,
796            host,
797            version,
798            ..
799        } = self;
800        let max_header_count: usize = config.get_max_header_count();
801        let max_header_key_size: usize = config.get_max_header_key_size();
802        let max_header_value_size: usize = config.get_max_header_value_size();
803        let max_body_size: usize = config.get_max_body_size();
804        let mut content_size: usize = 0;
805        let mut header_count: usize = 0;
806        let mut content_length_seen: bool = false;
807        let mut transfer_encoding_seen: bool = false;
808        let mut host_seen: bool = false;
809        let mut pos: usize = first_line_end;
810        let mut incomplete_head: bool = false;
811        let header_result: Result<(), RequestError> = HEADER_ENTRY_POOL.with(
812            |pool: &RefCell<Vec<(String, VecDeque<String>)>>| -> Result<(), RequestError> {
813                let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
814                loop {
815                    let rest: &[u8] = &buffer[pos..];
816                    let Some(rel_lf) = r#fn::find_byte_swar(rest, BR_U8) else {
817                        incomplete_head = true;
818                        return Ok(());
819                    };
820                    let line_end: usize = pos + rel_lf;
821                    let raw_line: &[u8] = if line_end > pos && buffer[line_end - 1] == b'\r' {
822                        &buffer[pos..line_end - 1]
823                    } else {
824                        &buffer[pos..line_end]
825                    };
826                    pos = line_end + 1;
827                    if raw_line.is_empty() {
828                        break;
829                    }
830                    let first_byte: u8 = raw_line[0];
831                    if first_byte == SPACE_U8 || first_byte == TAB_U8 {
832                        return Err(RequestError::HttpRead(HttpStatus::BadRequest));
833                    }
834                    header_count += 1;
835                    Self::check_http_header_count(header_count, max_header_count)?;
836                    let mut colon_pos: usize = raw_line.len();
837                    let mut has_upper: bool = false;
838                    for (scan_idx, &byte) in raw_line.iter().enumerate() {
839                        if byte == COLON_U8 {
840                            colon_pos = scan_idx;
841                            break;
842                        }
843                        if !HTTP_HEADER_TOKEN_TABLE[byte as usize] {
844                            return Err(RequestError::HttpRead(HttpStatus::BadRequest));
845                        }
846                        if byte.is_ascii_uppercase() {
847                            has_upper = true;
848                        }
849                    }
850                    if colon_pos == 0 || colon_pos == raw_line.len() {
851                        return Err(RequestError::HttpRead(HttpStatus::BadRequest));
852                    }
853                    let key_bytes: &[u8] = &raw_line[..colon_pos];
854                    // SAFETY: Every byte passed `HTTP_HEADER_TOKEN_TABLE`, which only accepts ASCII (< 0x80).
855                    let key: &str = unsafe { from_utf8_unchecked(key_bytes) };
856                    Self::check_http_header_key_size(key, max_header_key_size)?;
857                    let raw_val: &[u8] = &raw_line[colon_pos + 1..];
858                    let Some(is_ascii_val) = r#fn::validate_header_value_swar(raw_val) else {
859                        return Err(RequestError::HttpRead(HttpStatus::BadRequest));
860                    };
861                    let mut val_start: usize = 0;
862                    let mut val_end: usize = raw_val.len();
863                    while val_start < val_end
864                        && (raw_val[val_start] == SPACE_U8 || raw_val[val_start] == TAB_U8)
865                    {
866                        val_start += 1;
867                    }
868                    while val_end > val_start
869                        && (raw_val[val_end - 1] == SPACE_U8 || raw_val[val_end - 1] == TAB_U8)
870                    {
871                        val_end -= 1;
872                    }
873                    let value: &str = if is_ascii_val {
874                        // SAFETY: `is_ascii_val` guarantees every byte in `raw_val` is ASCII (< 0x80).
875                        unsafe { from_utf8_unchecked(&raw_val[val_start..val_end]) }
876                    } else {
877                        match from_utf8(&raw_val[val_start..val_end]) {
878                            Ok(text) => text,
879                            Err(_) => {
880                                return Err(RequestError::ReadConnection(HttpStatus::BadRequest));
881                            }
882                        }
883                    };
884                    Self::check_http_header_value_size(value, max_header_value_size)?;
885                    match key.len() {
886                        4 if key.eq_ignore_ascii_case(HOST) => {
887                            if host_seen || !is_valid_http_host(value) {
888                                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
889                            }
890                            host_seen = true;
891                            host.clear();
892                            host.push_str(value);
893                        }
894                        14 if key.eq_ignore_ascii_case(CONTENT_LENGTH) => {
895                            if transfer_encoding_seen {
896                                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
897                            }
898                            if content_length_seen {
899                                return Err(RequestError::InvalidContentLength(
900                                    HttpStatus::BadRequest,
901                                ));
902                            }
903                            content_length_seen = true;
904                            content_size = Self::check_http_body_size(value, max_body_size)?;
905                        }
906                        17 if key.eq_ignore_ascii_case(HTTP_HEADER_TRANSFER_ENCODING) => {
907                            if *version != HTTP_HOST_REQUIRED_VERSION || content_length_seen {
908                                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
909                            }
910                            transfer_encoding_seen = true;
911                        }
912                        _ => {}
913                    }
914                    Self::insert_http_header_from_pool(headers, &mut pool, key, has_upper, value);
915                }
916                Ok(())
917            },
918        );
919        header_result?;
920        if incomplete_head {
921            self.reset();
922            line_buffer.clear();
923            return Ok(None);
924        }
925        if *version == HTTP_HOST_REQUIRED_VERSION && !host_seen {
926            return Err(RequestError::HttpRead(HttpStatus::BadRequest));
927        }
928        if transfer_encoding_seen {
929            let values: &VecDeque<String> = headers
930                .get(HTTP_HEADER_TRANSFER_ENCODING)
931                .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
932            return Ok(Some((r#fn::parse_transfer_encoding(values)?, pos)));
933        }
934        Ok(Some((RequestFraming::Fixed(content_size), pos)))
935    }
936
937    /// Parses HTTP headers from a buffered reader into this request.
938    ///
939    /// This method reads header lines from the provided buffered reader until an empty line
940    /// is encountered, which indicates the end of headers. It checks header count, length,
941    /// and content according to the provided configuration. The request's headers map and
942    /// host string are expected to be empty; they are filled without reallocating when they
943    /// already have sufficient capacity.
944    ///
945    /// The line buffer belongs to the caller so that a keep-alive connection
946    /// reads every header line of every request into the same allocation.
947    ///
948    /// # Arguments
949    ///
950    /// - `&mut R` - A mutable reference to a buffered reader, which requires the
951    ///   `AsyncBufReadExt + Unpin` bound.
952    /// - `&RequestConfig` - Configuration for security limits and buffer settings.
953    /// - `&mut String` - The buffer the header lines are read into.
954    ///
955    /// # Returns
956    ///
957    /// - `Result<RequestFraming, RequestError>` - The body framing, or an error if parsing fails.
958    pub(crate) async fn get_http_headers<R>(
959        &mut self,
960        reader: &mut R,
961        config: &RequestConfig,
962        header_line_buffer: &mut String,
963    ) -> Result<RequestFraming, RequestError>
964    where
965        R: AsyncBufReadExt + Unpin,
966    {
967        let Request {
968            headers,
969            host,
970            version,
971            ..
972        } = self;
973        let max_header_count: usize = config.get_max_header_count();
974        let max_header_key_size: usize = config.get_max_header_key_size();
975        let max_header_value_size: usize = config.get_max_header_value_size();
976        let max_body_size: usize = config.get_max_body_size();
977        let mut content_size: usize = 0;
978        let mut header_count: usize = 0;
979        let mut content_length_seen: bool = false;
980        let mut transfer_encoding_seen: bool = false;
981        let mut host_seen: bool = false;
982        let max_header_line: usize = if max_header_key_size
983            == DEFAULT_LOW_SECURITY_MAX_HEADER_KEY_SIZE
984            || max_header_value_size == DEFAULT_LOW_SECURITY_MAX_HEADER_VALUE_SIZE
985        {
986            usize::MAX
987        } else {
988            max_header_key_size
989                .saturating_add(max_header_value_size)
990                .saturating_add(HTTP_HEADER_LINE_OVERHEAD)
991        };
992        loop {
993            let line_len: usize = read_http_line_bounded(
994                reader,
995                header_line_buffer,
996                max_header_line,
997                RequestError::HeaderLineTooLong(HttpStatus::RequestHeaderFieldsTooLarge),
998            )
999            .await?;
1000            if line_len == 0 {
1001                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1002            }
1003            let header_line: &str = header_line_buffer
1004                .strip_suffix(HTTP_HEADER_LINE_FEED)
1005                .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
1006            let header_line: &str = header_line
1007                .strip_suffix(HTTP_HEADER_CARRIAGE_RETURN)
1008                .unwrap_or(header_line);
1009            if header_line.is_empty() {
1010                break;
1011            }
1012            if header_line.starts_with(HTTP_HEADER_OPTIONAL_WHITESPACE) {
1013                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1014            }
1015            header_count += 1;
1016            Self::check_http_header_count(header_count, max_header_count)?;
1017            let (key, value_part): (&str, &str) = header_line
1018                .split_once(COLON)
1019                .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
1020            let valid_key: bool = key.bytes().all(|byte: u8| {
1021                byte.is_ascii_alphanumeric() || HTTP_HEADER_TOKEN_PUNCTUATION.contains(&byte)
1022            });
1023            if key.is_empty() || !valid_key {
1024                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1025            }
1026            Self::check_http_header_key_size(key, max_header_key_size)?;
1027            if value_part.bytes().any(|byte: u8| {
1028                (byte < HTTP_HEADER_CONTROL_LIMIT && byte != HTTP_HEADER_TAB)
1029                    || byte == HTTP_HEADER_DELETE
1030            }) {
1031                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1032            }
1033            let value: &str = value_part.trim_matches(HTTP_HEADER_OPTIONAL_WHITESPACE);
1034            Self::check_http_header_value_size(value, max_header_value_size)?;
1035            match key {
1036                key if key.eq_ignore_ascii_case(HTTP_HEADER_TRANSFER_ENCODING) => {
1037                    if *version != HTTP_HOST_REQUIRED_VERSION || content_length_seen {
1038                        return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1039                    }
1040                    transfer_encoding_seen = true;
1041                }
1042                key if key.eq_ignore_ascii_case(HOST) => {
1043                    if host_seen || !is_valid_http_host(value) {
1044                        return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1045                    }
1046                    host_seen = true;
1047                    host.clear();
1048                    host.push_str(value);
1049                }
1050                key if key.eq_ignore_ascii_case(CONTENT_LENGTH) => {
1051                    if transfer_encoding_seen {
1052                        return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1053                    }
1054                    if content_length_seen {
1055                        return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
1056                    }
1057                    content_length_seen = true;
1058                    content_size = Self::check_http_body_size(value, max_body_size)?;
1059                }
1060                _ => {}
1061            }
1062            Self::insert_http_header(headers, key, value);
1063        }
1064        if *version == HTTP_HOST_REQUIRED_VERSION && !host_seen {
1065            return Err(RequestError::HttpRead(HttpStatus::BadRequest));
1066        }
1067        if transfer_encoding_seen {
1068            let values: &VecDeque<String> = headers
1069                .get(HTTP_HEADER_TRANSFER_ENCODING)
1070                .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
1071            return r#fn::parse_transfer_encoding(values);
1072        }
1073        Ok(RequestFraming::Fixed(content_size))
1074    }
1075
1076    /// Replaces wire chunk framing with the decoded content length.
1077    #[cold]
1078    pub(crate) fn normalize_chunked_headers(&mut self) {
1079        let mut digits: [u8; B_20] = [0; B_20];
1080        let length: &str = render_length(self.get_body().len(), &mut digits);
1081        let headers: &mut RequestHeaders = self.get_mut_headers();
1082        headers.remove(HTTP_HEADER_TRANSFER_ENCODING);
1083        headers.remove(HTTP_HEADER_TRAILER);
1084        Self::insert_http_header(headers, CONTENT_LENGTH, length);
1085    }
1086
1087    /// Stores one ASCII header using an already-borrowed worker-local entry pool.
1088    ///
1089    /// # Arguments
1090    ///
1091    /// - `&mut RequestHeaders` - The header map to store the header in.
1092    /// - `&mut Vec<(String, VecDeque<String>)>` - Borrowed worker-local header entry pool.
1093    /// - `&str` - The validated ASCII header name, as it arrived.
1094    /// - `bool` - Whether `key` contains any ASCII uppercase character.
1095    /// - `&str` - The header value.
1096    #[inline(always)]
1097    fn insert_http_header_from_pool(
1098        headers: &mut RequestHeaders,
1099        pool: &mut Vec<(String, VecDeque<String>)>,
1100        key: &str,
1101        has_upper: bool,
1102        value: &str,
1103    ) {
1104        let (mut name, mut values): (String, VecDeque<String>) = pool
1105            .pop()
1106            .unwrap_or_else(|| (String::new(), VecDeque::new()));
1107        name.clear();
1108        if has_upper {
1109            // SAFETY: `key` passed `HTTP_HEADER_TOKEN_TABLE`, so every byte is ASCII (< 0x80)
1110            // and `to_ascii_lowercase()` keeps every byte ASCII, preserving valid UTF-8.
1111            let dst: &mut Vec<u8> = unsafe { name.as_mut_vec() };
1112            dst.reserve(key.len());
1113            for &byte in key.as_bytes() {
1114                dst.push(byte.to_ascii_lowercase());
1115            }
1116        } else {
1117            name.push_str(key);
1118        }
1119        match headers.entry(name) {
1120            Entry::Occupied(mut occupied) => {
1121                occupied.get_mut().push_back(value.to_owned());
1122                if values.capacity() <= MAX_POOLED_HEADER_VALUE_CAPACITY
1123                    && pool.len() < MAX_POOLED_HEADER_ENTRIES
1124                {
1125                    pool.push((String::new(), values));
1126                }
1127            }
1128            Entry::Vacant(vacant) => {
1129                if values.len() == 1 {
1130                    values[0].clear();
1131                    values[0].push_str(value);
1132                } else {
1133                    while values.len() > 1 {
1134                        values.pop_back();
1135                    }
1136                    if let Some(slot) = values.front_mut() {
1137                        slot.clear();
1138                        slot.push_str(value);
1139                    } else {
1140                        values.push_back(value.to_owned());
1141                    }
1142                }
1143                vacant.insert(values);
1144            }
1145        }
1146    }
1147
1148    /// Stores one header, reusing a pooled name and value where possible.
1149    ///
1150    /// The name is lowercased into the buffer of a recycled entry and the
1151    /// value is written into that entry's value buffer, so a header that was
1152    /// already seen on this connection costs no allocation at all.
1153    ///
1154    /// # Arguments
1155    ///
1156    /// - `&mut RequestHeaders` - The header map to store the header in.
1157    /// - `&str` - The header name, as it arrived.
1158    /// - `&str` - The header value.
1159    fn insert_http_header(headers: &mut RequestHeaders, key: &str, value: &str) {
1160        let (mut name, mut values): (String, VecDeque<String>) =
1161            take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
1162        name.clear();
1163        name.push_str(key);
1164        name.make_ascii_lowercase();
1165        match headers.entry(name) {
1166            Entry::Occupied(mut occupied) => {
1167                // The header repeats: it keeps every value it was given.
1168                occupied.get_mut().push_back(value.to_string());
1169                return_header_entry((String::new(), values));
1170            }
1171            Entry::Vacant(vacant) => {
1172                // A recycled entry may carry the values of a header that was
1173                // sent more than once. Those values belong to that header, so
1174                // only the first one is kept and the rest are dropped.
1175                while values.len() > 1 {
1176                    values.pop_back();
1177                }
1178                if values.is_empty() {
1179                    values.push_back(String::new());
1180                }
1181                if let Some(slot) = values.front_mut() {
1182                    slot.clear();
1183                    slot.push_str(value);
1184                }
1185                vacant.insert(values);
1186            }
1187        }
1188    }
1189
1190    /// Reads the request body from the buffered reader into the given buffer.
1191    ///
1192    /// The target buffer is cleared and resized to the expected content size,
1193    /// retaining its allocation when it already has sufficient capacity.
1194    ///
1195    /// # Arguments
1196    ///
1197    /// - `&mut R` - The buffered reader to read from, which requires the `AsyncRead + Unpin` bound.
1198    /// - `&mut Vec<u8>` - The buffer to read the body bytes into.
1199    /// - `usize` - The expected content size.
1200    ///
1201    /// # Returns
1202    ///
1203    /// - `Result<(), RequestError>` - Ok on success, or an error if reading fails.
1204    #[inline(always)]
1205    pub(crate) async fn fill_http_body<R>(
1206        reader: &mut R,
1207        body: &mut Vec<u8>,
1208        content_size: usize,
1209    ) -> Result<(), RequestError>
1210    where
1211        R: AsyncRead + Unpin,
1212    {
1213        body.clear();
1214        let mut remaining: usize = content_size;
1215        while remaining > 0 {
1216            let step: usize = remaining.min(HTTP_BODY_READ_CHUNK_SIZE);
1217            let start: usize = body.len();
1218            body.try_reserve(step)
1219                .map_err(|_| RequestError::ContentLengthTooLarge(HttpStatus::PayloadTooLarge))?;
1220            body.resize(start + step, 0);
1221            let mut filled: usize = 0;
1222            while filled < step {
1223                let read_len: usize =
1224                    AsyncReadExt::read(reader, &mut body[start + filled..]).await?;
1225                if read_len == 0 {
1226                    body.truncate(start + filled);
1227                    return Err(RequestError::ReadConnection(HttpStatus::BadRequest));
1228                }
1229                filled += read_len;
1230            }
1231            remaining -= step;
1232        }
1233        Ok(())
1234    }
1235
1236    /// Tries to get a query parameter by key.
1237    ///
1238    /// The key type must implement `AsRef<str>` conversion. A key that repeats in
1239    /// the query carries every one of its values.
1240    ///
1241    /// # Arguments
1242    ///
1243    /// - `K` - The query parameter key, which implements `AsRef<str>`.
1244    ///
1245    /// # Returns
1246    ///
1247    /// - `Option<VecDeque<String>>` - Every value of the parameter if it exists.
1248    #[inline(always)]
1249    pub fn try_get_query<K>(&self, key: K) -> Option<VecDeque<String>>
1250    where
1251        K: AsRef<str>,
1252    {
1253        self.get_querys().get(key.as_ref()).cloned()
1254    }
1255
1256    /// Tries to get the first query parameter value by key.
1257    ///
1258    /// Use this when the parameter is expected to appear once; use
1259    /// `try_get_query` when every value matters.
1260    ///
1261    /// # Arguments
1262    ///
1263    /// - `K` - The query parameter key, which implements `AsRef<str>`.
1264    ///
1265    /// # Returns
1266    ///
1267    /// - `Option<String>` - The first parameter value if it exists.
1268    #[inline(always)]
1269    pub fn try_get_query_front<K>(&self, key: K) -> Option<String>
1270    where
1271        K: AsRef<str>,
1272    {
1273        self.get_querys()
1274            .get(key.as_ref())
1275            .and_then(|values: &VecDeque<String>| values.front().cloned())
1276    }
1277
1278    /// Tries to get the last query parameter value by key.
1279    ///
1280    /// # Arguments
1281    ///
1282    /// - `K` - The query parameter key, which implements `AsRef<str>`.
1283    ///
1284    /// # Returns
1285    ///
1286    /// - `Option<String>` - The last parameter value if it exists.
1287    #[inline(always)]
1288    pub fn try_get_query_back<K>(&self, key: K) -> Option<String>
1289    where
1290        K: AsRef<str>,
1291    {
1292        self.get_querys()
1293            .get(key.as_ref())
1294            .and_then(|values: &VecDeque<String>| values.back().cloned())
1295    }
1296
1297    /// Tries to get the number of values of a query parameter.
1298    ///
1299    /// # Arguments
1300    ///
1301    /// - `K` - The query parameter key, which implements `AsRef<str>`.
1302    ///
1303    /// # Returns
1304    ///
1305    /// - `Option<usize>` - The number of values if the parameter exists.
1306    #[inline(always)]
1307    pub fn try_get_query_size<K>(&self, key: K) -> Option<usize>
1308    where
1309        K: AsRef<str>,
1310    {
1311        self.get_querys()
1312            .get(key.as_ref())
1313            .map(|values: &VecDeque<String>| values.len())
1314    }
1315
1316    /// Checks whether a query parameter exists.
1317    ///
1318    /// # Arguments
1319    ///
1320    /// - `K` - The query parameter key, which implements `AsRef<str>`.
1321    ///
1322    /// # Returns
1323    ///
1324    /// - `bool` - Whether the parameter exists.
1325    #[inline(always)]
1326    pub fn has_query<K>(&self, key: K) -> bool
1327    where
1328        K: AsRef<str>,
1329    {
1330        self.get_querys().contains_key(key.as_ref())
1331    }
1332
1333    /// Gets a query parameter by key.
1334    ///
1335    /// # Arguments
1336    ///
1337    /// - `K` - The query parameter key, which implements `AsRef<str>`.
1338    ///
1339    /// # Returns
1340    ///
1341    /// - `VecDeque<String>` - Every value of the parameter.
1342    ///
1343    /// # Panics
1344    ///
1345    /// This function will panic if the query parameter key is not found.
1346    #[inline(always)]
1347    pub fn get_query<K>(&self, key: K) -> VecDeque<String>
1348    where
1349        K: AsRef<str>,
1350    {
1351        self.try_get_query(key).unwrap()
1352    }
1353
1354    /// Gets the first query parameter value by key.
1355    ///
1356    /// # Arguments
1357    ///
1358    /// - `K` - The query parameter key, which implements `AsRef<str>`.
1359    ///
1360    /// # Returns
1361    ///
1362    /// - `String` - The first parameter value.
1363    ///
1364    /// # Panics
1365    ///
1366    /// This function will panic if the query parameter key is not found.
1367    #[inline(always)]
1368    pub fn get_query_front<K>(&self, key: K) -> String
1369    where
1370        K: AsRef<str>,
1371    {
1372        self.try_get_query_front(key).unwrap()
1373    }
1374
1375    /// Retrieves the number of query parameters.
1376    ///
1377    /// # Returns
1378    ///
1379    /// - `usize` - The count of distinct query parameter keys.
1380    #[inline(always)]
1381    pub fn get_querys_size(&self) -> usize {
1382        self.get_querys().len()
1383    }
1384
1385    /// Looks up a header value list case-insensitively without allocating when
1386    /// the key is already lowercase or fits in the stack buffer.
1387    ///
1388    /// # Arguments
1389    ///
1390    /// - `&str` - The header name to look up.
1391    ///
1392    /// # Returns
1393    ///
1394    /// - `Option<&VecDeque<String>>` - Reference to the stored values, if present.
1395    #[inline(always)]
1396    fn get_header_ref(&self, key: &str) -> Option<&VecDeque<String>> {
1397        let bytes: &[u8] = key.as_bytes();
1398        if !bytes.iter().any(|byte: &u8| byte.is_ascii_uppercase()) {
1399            return self.get_headers().get(key);
1400        }
1401        if bytes.len() <= STACK_HEADER_KEY_LIMIT {
1402            let mut stack_buf: [u8; STACK_HEADER_KEY_LIMIT] = [0; STACK_HEADER_KEY_LIMIT];
1403            let mut idx: usize = 0;
1404            while idx < bytes.len() {
1405                stack_buf[idx] = bytes[idx].to_ascii_lowercase();
1406                idx += 1;
1407            }
1408            if let Ok(lower) = from_utf8(&stack_buf[..bytes.len()]) {
1409                return self.get_headers().get(lower);
1410            }
1411        }
1412        self.get_headers().get(&key.to_ascii_lowercase())
1413    }
1414
1415    /// Tries to retrieve the value of a request header by its key.
1416    ///
1417    /// The key is matched case-insensitively, because the parser stores every
1418    /// header name lowercased and an HTTP header name is case-insensitive by
1419    /// specification. Looking a header up with `Content-Type` and with
1420    /// `content-type` therefore find the same value.
1421    ///
1422    /// # Arguments
1423    ///
1424    /// - `K` - The header's key, which must implement `AsRef<str>`.
1425    ///
1426    /// # Returns
1427    ///
1428    /// - `Option<VecDeque<String>>` - The optional header values.
1429    #[inline(always)]
1430    pub fn try_get_header<K>(&self, key: K) -> Option<VecDeque<String>>
1431    where
1432        K: AsRef<str>,
1433    {
1434        self.get_header_ref(key.as_ref()).cloned()
1435    }
1436
1437    /// Retrieves the value of a request header by its key.
1438    ///
1439    /// # Arguments
1440    ///
1441    /// - `K` - The header's key, which must implement `AsRef<str>`.
1442    ///
1443    /// # Returns
1444    ///
1445    /// - `VecDeque<String>` - The optional header values.
1446    ///
1447    /// # Panics
1448    ///
1449    /// This function will panic if the header key is not found.
1450    #[inline(always)]
1451    pub fn get_header<K>(&self, key: K) -> VecDeque<String>
1452    where
1453        K: AsRef<str>,
1454    {
1455        self.try_get_header(key).unwrap()
1456    }
1457
1458    /// Tries to retrieve the first value of a request header by its key.
1459    ///
1460    /// # Arguments
1461    ///
1462    /// - `K` - The header's key, which must implement `AsRef<str>`.
1463    ///
1464    /// # Returns
1465    ///
1466    /// - `Option<String>` - The first header value if exists.
1467    #[inline(always)]
1468    pub fn try_get_header_front<K>(&self, key: K) -> Option<String>
1469    where
1470        K: AsRef<str>,
1471    {
1472        self.get_header_ref(key.as_ref())
1473            .and_then(|header_values: &VecDeque<String>| header_values.front().cloned())
1474    }
1475
1476    /// Retrieves the first value of a request header by its key.
1477    ///
1478    /// # Arguments
1479    ///
1480    /// - `K` - The header's key, which must implement `AsRef<str>`.
1481    ///
1482    /// # Returns
1483    ///
1484    /// - `String` - The first header value if exists.
1485    ///
1486    /// # Panics
1487    ///
1488    /// This function will panic if the header key is not found.
1489    #[inline(always)]
1490    pub fn get_header_front<K>(&self, key: K) -> String
1491    where
1492        K: AsRef<str>,
1493    {
1494        self.try_get_header_front(key).unwrap()
1495    }
1496
1497    /// Tries to retrieve the last value of a request header by its key.
1498    ///
1499    /// # Arguments
1500    ///
1501    /// - `K` - The header's key, which must implement `AsRef<str>`.
1502    ///
1503    /// # Returns
1504    ///
1505    /// - `Option<String>` - The last header value if exists.
1506    #[inline(always)]
1507    pub fn try_get_header_back<K>(&self, key: K) -> Option<String>
1508    where
1509        K: AsRef<str>,
1510    {
1511        self.get_header_ref(key.as_ref())
1512            .and_then(|header_values: &VecDeque<String>| header_values.back().cloned())
1513    }
1514
1515    /// Retrieves the last value of a request header by its key.
1516    ///
1517    /// # Arguments
1518    ///
1519    /// - `K` - The header's key, which must implement `AsRef<str>`.
1520    ///
1521    /// # Returns
1522    ///
1523    /// - `String` - The last header value if exists.
1524    ///
1525    /// # Panics
1526    ///
1527    /// This function will panic if the header key is not found.
1528    #[inline(always)]
1529    pub fn get_header_back<K>(&self, key: K) -> String
1530    where
1531        K: AsRef<str>,
1532    {
1533        self.try_get_header_back(key).unwrap()
1534    }
1535
1536    /// Tries to retrieve the number of values for a specific header.
1537    ///
1538    /// # Arguments
1539    ///
1540    /// - `K` - The header's key, which must implement `AsRef<str>`.
1541    ///
1542    /// # Returns
1543    ///
1544    /// - `Option<usize>` - The count of values for the header if exists.
1545    #[inline(always)]
1546    pub fn try_get_header_size<K>(&self, key: K) -> Option<usize>
1547    where
1548        K: AsRef<str>,
1549    {
1550        self.get_header_ref(key.as_ref())
1551            .map(|header_values: &VecDeque<String>| header_values.len())
1552    }
1553
1554    /// Retrieves the number of values for a specific header.
1555    ///
1556    /// # Arguments
1557    ///
1558    /// - `K` - The header's key, which must implement `AsRef<str>`.
1559    ///
1560    /// # Returns
1561    ///
1562    /// - `usize` - The count of values for the header.
1563    ///
1564    /// # Panics
1565    ///
1566    /// This function will panic if the header key is not found.
1567    #[inline(always)]
1568    pub fn get_header_size<K>(&self, key: K) -> usize
1569    where
1570        K: AsRef<str>,
1571    {
1572        self.try_get_header_size(key).unwrap()
1573    }
1574
1575    /// Retrieves the total number of header values across all headers.
1576    ///
1577    /// # Returns
1578    ///
1579    /// - `usize` - The total count of all header values.
1580    #[inline(always)]
1581    pub fn get_headers_values_size(&self) -> usize {
1582        self.get_headers()
1583            .values()
1584            .map(|header_values: &VecDeque<String>| header_values.len())
1585            .sum()
1586    }
1587
1588    /// Retrieves the number of unique headers.
1589    ///
1590    /// # Returns
1591    ///
1592    /// - `usize` - The count of unique header keys.
1593    #[inline(always)]
1594    pub fn get_headers_size(&self) -> usize {
1595        self.get_headers().len()
1596    }
1597
1598    /// Checks if a specific header exists.
1599    ///
1600    /// # Arguments
1601    ///
1602    /// - `K` - The header key to check, which must implement `AsRef<str>`.
1603    ///
1604    /// # Returns
1605    ///
1606    /// - `bool` - Whether the header exists.
1607    #[inline(always)]
1608    pub fn has_header<K>(&self, key: K) -> bool
1609    where
1610        K: AsRef<str>,
1611    {
1612        self.get_header_ref(key.as_ref()).is_some()
1613    }
1614
1615    /// Checks if a header contains a specific value.
1616    ///
1617    /// # Arguments
1618    ///
1619    /// - `K` - The header key to check, which must implement `AsRef<str>`.
1620    /// - `V` - The value to search for, which must implement `AsRef<str>`.
1621    ///
1622    /// # Returns
1623    ///
1624    /// - `bool` - Whether the header contains the value.
1625    #[inline(always)]
1626    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
1627    where
1628        K: AsRef<str>,
1629        V: AsRef<str>,
1630    {
1631        if let Some(values) = self.get_header_ref(key.as_ref()) {
1632            values.iter().any(|data: &String| data == value.as_ref())
1633        } else {
1634            false
1635        }
1636    }
1637
1638    /// Checks `If-None-Match` against the entity-tag of an existing representation.
1639    ///
1640    /// This explicitly invoked helper borrows normalized request headers and allocates nothing.
1641    /// Strong and weak tags use case-sensitive weak comparison of their opaque values.
1642    /// Repeated fields form one list; optional spaces, tabs, and empty list members are ignored.
1643    /// A wildcard matches only when the entire field combination is a standalone `*`.
1644    /// Missing headers, empty lists, invalid tags, or any malformed suffix return `false`,
1645    /// even if an earlier tag matched. The current tag must be exactly one valid entity-tag,
1646    /// without surrounding whitespace. Quoted commas and empty opaque values are valid;
1647    /// backslashes are literal bytes, not escape characters.
1648    ///
1649    /// Call only for a representation that already exists. This does not send a response,
1650    /// automatically generate a 304, or implement complete HTTP precondition evaluation.
1651    /// Callers decide whether to send 304 for GET/HEAD or 412 for other methods and must
1652    /// handle precondition ordering themselves. Do not use this for `If-Match`, which
1653    /// requires strong comparison.
1654    ///
1655    /// # Arguments
1656    ///
1657    /// - `&str` - The current representation's complete strong or weak entity-tag.
1658    ///
1659    /// # Returns
1660    ///
1661    /// - `bool` - Whether a completely valid `If-None-Match` matches the existing representation.
1662    #[must_use]
1663    pub fn matches_if_none_match(&self, current_etag: &str) -> bool {
1664        let current: &[u8] = match r#fn::parse_entity_tag(current_etag.as_bytes()) {
1665            Some((opaque, [])) => opaque,
1666            _ => return false,
1667        };
1668        let values: &VecDeque<String> = match self.get_headers().get(IF_NONE_MATCH) {
1669            Some(values) => values,
1670            None => return false,
1671        };
1672        if values.len() == 1
1673            && values.front().is_some_and(|value: &String| {
1674                value
1675                    .trim_matches(&HTTP_HEADER_OPTIONAL_WHITESPACE[..])
1676                    .as_bytes()
1677                    == ENTITY_TAG_WILDCARD
1678            })
1679        {
1680            return true;
1681        }
1682        let mut matched: bool = false;
1683        for value in values {
1684            let mut remaining: &[u8] = value.as_bytes();
1685            while !remaining.is_empty() {
1686                while remaining
1687                    .first()
1688                    .is_some_and(|byte: &u8| ENTITY_TAG_LIST_PADDING.contains(byte))
1689                {
1690                    remaining = &remaining[1..];
1691                }
1692                if remaining.is_empty() {
1693                    break;
1694                }
1695                let (candidate, suffix): (&[u8], &[u8]) = match r#fn::parse_entity_tag(remaining) {
1696                    Some(parsed) => parsed,
1697                    None => return false,
1698                };
1699                matched |= candidate == current;
1700                remaining = suffix;
1701                while remaining
1702                    .first()
1703                    .is_some_and(|byte: &u8| ENTITY_TAG_OPTIONAL_WHITESPACE.contains(byte))
1704                {
1705                    remaining = &remaining[1..];
1706                }
1707                if remaining.is_empty() {
1708                    break;
1709                }
1710                if remaining.first() != Some(&ENTITY_TAG_SEPARATOR) {
1711                    return false;
1712                }
1713                remaining = &remaining[1..];
1714            }
1715        }
1716        matched
1717    }
1718
1719    /// Tries to parse cookies from the `Cookie` header.
1720    ///
1721    /// This method retrieves the `Cookie` header value and parses it into
1722    /// a collection of key-value pairs representing the cookies.
1723    ///
1724    /// # Returns
1725    ///
1726    /// - `Option<HashMapXxHash3_64<String, String>>` - The parsed cookies if the header exists, otherwise `None`.
1727    #[inline(always)]
1728    pub fn try_get_cookies(&self) -> Option<HashMapXxHash3_64<String, String>> {
1729        let values: &VecDeque<String> = self.get_header_ref(COOKIE)?;
1730        if values.is_empty() {
1731            return None;
1732        }
1733        let mut merged: HashMapXxHash3_64<String, String> = hash_map_xx_hash3_64();
1734        for header_value in values {
1735            let parsed: HashMapXxHash3_64<String, String> = Cookie::parse(header_value);
1736            for (name, value) in parsed {
1737                merged.entry(name).or_insert(value);
1738            }
1739        }
1740        Some(merged)
1741    }
1742
1743    /// Parses cookies from the `Cookie` header.
1744    ///
1745    /// This method retrieves the `Cookie` header value and parses it into
1746    /// a collection of key-value pairs representing the cookies.
1747    ///
1748    /// # Returns
1749    ///
1750    /// - `HashMapXxHash3_64<String, String>` - The parsed cookies.
1751    ///
1752    /// # Panics
1753    ///
1754    /// This function will panic if the `Cookie` header is not found.
1755    #[inline(always)]
1756    pub fn get_cookies(&self) -> HashMapXxHash3_64<String, String> {
1757        self.try_get_cookies().unwrap()
1758    }
1759
1760    /// Tries to get a cookie value by its key.
1761    ///
1762    /// This method first parses the cookies from the `Cookie` header,
1763    /// then attempts to retrieve the value for the specified key.
1764    ///
1765    /// # Arguments
1766    ///
1767    /// - `K` - The cookie key, which implements `AsRef<str>`.
1768    ///
1769    /// # Returns
1770    ///
1771    /// - `Option<String>` - The cookie value if exists.
1772    #[inline(always)]
1773    pub fn try_get_cookie<K>(&self, key: K) -> Option<String>
1774    where
1775        K: AsRef<str>,
1776    {
1777        self.try_get_cookies()
1778            .and_then(|cookies: HashMapXxHash3_64<String, String>| {
1779                cookies.get(key.as_ref()).cloned()
1780            })
1781    }
1782
1783    /// Gets a cookie value by its key.
1784    ///
1785    /// This method first parses the cookies from the `Cookie` header,
1786    /// then retrieves the value for the specified key.
1787    ///
1788    /// # Arguments
1789    ///
1790    /// - `K` - The cookie key, which implements `AsRef<str>`.
1791    ///
1792    /// # Returns
1793    ///
1794    /// - `String` - The cookie value.
1795    ///
1796    /// # Panics
1797    ///
1798    /// This function will panic if the `Cookie` header is not found
1799    /// or the cookie key does not exist.
1800    #[inline(always)]
1801    pub fn get_cookie<K>(&self, key: K) -> String
1802    where
1803        K: AsRef<str>,
1804    {
1805        self.try_get_cookie(key).unwrap()
1806    }
1807
1808    /// Retrieves the upgrade type from the request headers.
1809    ///
1810    /// This method looks for the `UPGRADE` header and attempts to parse its value
1811    /// as_ref an `UpgradeType`. If the header is missing or the value is invalid,
1812    /// it returns the default `UpgradeType`.
1813    ///
1814    /// # Returns
1815    ///
1816    /// - `UpgradeType` - The parsed upgrade type.
1817    #[inline(always)]
1818    pub fn get_upgrade_type(&self) -> UpgradeType {
1819        self.get_headers()
1820            .get(UPGRADE)
1821            .and_then(|values: &VecDeque<String>| values.back())
1822            .and_then(|data: &String| data.parse::<UpgradeType>().ok())
1823            .unwrap_or_default()
1824    }
1825
1826    /// Retrieves the body content of the request as a UTF-8 encoded string.
1827    ///
1828    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as a string.
1829    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
1830    ///
1831    /// # Returns
1832    ///
1833    /// - `String` - The body content as a string.
1834    #[inline(always)]
1835    pub fn get_body_string(&self) -> String {
1836        String::from_utf8_lossy(self.get_body()).into_owned()
1837    }
1838
1839    /// Deserializes the body content of the request as_ref a specified type `T`.
1840    ///
1841    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
1842    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
1843    ///
1844    /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
1845    ///
1846    /// # Returns
1847    ///
1848    /// - `Result<T, serde_json::Error>` - The deserialization result.
1849    #[inline(always)]
1850    pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
1851    where
1852        T: DeserializeOwned,
1853    {
1854        from_slice(self.get_body())
1855    }
1856
1857    /// Deserializes the body content of the request as_ref a specified type `T`.
1858    ///
1859    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
1860    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
1861    ///
1862    /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
1863    ///
1864    /// # Returns
1865    ///
1866    /// - `T` - The deserialized body content.
1867    ///
1868    /// # Panics
1869    ///
1870    /// This function will panic if the deserialization fails.
1871    #[inline(always)]
1872    pub fn get_body_json<T>(&self) -> T
1873    where
1874        T: DeserializeOwned,
1875    {
1876        self.try_get_body_json().unwrap()
1877    }
1878
1879    /// Checks whether the WebSocket upgrade is enabled for this request.
1880    ///
1881    /// This method determines if the `UPGRADE` header indicates a WebSocket connection.
1882    ///
1883    /// # Returns
1884    ///
1885    /// - `bool` - Whether WebSocket upgrade is enabled.
1886    #[inline(always)]
1887    pub fn is_ws_upgrade_type(&self) -> bool {
1888        self.get_upgrade_type().is_ws()
1889    }
1890
1891    /// Checks whether the request declares a `multipart/form-data` body.
1892    ///
1893    /// # Returns
1894    ///
1895    /// - `bool` - Whether the request content type is `multipart/form-data`.
1896    #[inline(always)]
1897    pub fn is_multipart_form_data(&self) -> bool {
1898        self.try_get_content_type()
1899            .map(|content_type: String| MultipartFormData::is_form_data(content_type))
1900            .unwrap_or(false)
1901    }
1902
1903    /// Tries to get the request content type with its parameters stripped.
1904    ///
1905    /// A `Content-Type` header such as `text/html; charset=utf-8` yields the
1906    /// media type alone, so a caller comparing against a media type does not
1907    /// have to know that parameters may follow it.
1908    ///
1909    /// # Returns
1910    ///
1911    /// - `Option<String>` - The media type, or `None` when the header is absent.
1912    #[inline(always)]
1913    pub fn try_get_content_type(&self) -> Option<String> {
1914        self.try_get_header_front(CONTENT_TYPE)
1915            .map(|value: String| {
1916                value
1917                    .split(SEMICOLON)
1918                    .next()
1919                    .unwrap_or(EMPTY_STR)
1920                    .trim()
1921                    .to_ascii_lowercase()
1922            })
1923    }
1924
1925    /// Tries to get one parameter of the request `Content-Type` header.
1926    ///
1927    /// The name is matched case-insensitively and a quoted value is unquoted,
1928    /// so both `boundary=abc` and `boundary="abc"` yield `abc`.
1929    ///
1930    /// # Arguments
1931    ///
1932    /// - `K` - The parameter name, which requires the `AsRef<str>` bound.
1933    ///
1934    /// # Returns
1935    ///
1936    /// - `Option<String>` - The parameter value, or `None` when absent.
1937    pub fn try_get_content_type_parameter<K>(&self, name: K) -> Option<String>
1938    where
1939        K: AsRef<str>,
1940    {
1941        let content_type: &str = self
1942            .get_headers()
1943            .get(CONTENT_TYPE)
1944            .and_then(|values: &VecDeque<String>| values.front())
1945            .map(String::as_str)?;
1946        let name: &str = name.as_ref();
1947        let mut matched: Option<String> = None;
1948        MultipartFormData::for_each_header_parameter(
1949            content_type,
1950            |index: usize, parameter: &str| {
1951                if index == 0 {
1952                    return false;
1953                }
1954                let Some((key, value)) = parameter.trim().split_once(EQUAL) else {
1955                    return false;
1956                };
1957                if !key.trim().eq_ignore_ascii_case(name) {
1958                    return false;
1959                }
1960                let value: &str = value.trim();
1961                let value: &str = value
1962                    .strip_prefix(MULTIPART_PARAMETER_QUOTE)
1963                    .and_then(|value: &str| value.strip_suffix(MULTIPART_PARAMETER_QUOTE))
1964                    .unwrap_or(value);
1965                if !value.is_empty() {
1966                    matched = Some(value.to_string());
1967                    return true;
1968                }
1969                false
1970            },
1971        );
1972        matched
1973    }
1974
1975    /// Tries to decode a `multipart/form-data` body into its parts.
1976    ///
1977    /// The boundary is read from the request `Content-Type` header rather than
1978    /// guessed, so a body whose content type declares no boundary, a truncated
1979    /// body, and a part without a name all yield `None`.
1980    ///
1981    /// # Returns
1982    ///
1983    /// - `Option<Vec<BodyPart>>` - The decoded parts, or `None` when unavailable.
1984    pub fn try_get_body_form_data(&self) -> Option<Vec<BodyPart>> {
1985        let boundary: String = self.try_get_content_type_parameter(MULTIPART_BOUNDARY_PARAMETER)?;
1986        MultipartFormData::parse(self.get_body(), &boundary)
1987    }
1988
1989    /// Decodes an `application/x-www-form-urlencoded` body into its fields.
1990    ///
1991    /// # Returns
1992    ///
1993    /// - `HashMapXxHash3_64<String, String>` - The decoded form fields.
1994    #[inline(always)]
1995    pub fn get_body_form(&self) -> HashMapXxHash3_64<String, String> {
1996        MultipartFormData::parse_url_encoded(self.get_body())
1997    }
1998
1999    /// Tries to get a plain text field of a `multipart/form-data` body.
2000    ///
2001    /// A part that uploads a file is skipped, so a file field never silently
2002    /// decodes as text.
2003    ///
2004    /// # Arguments
2005    ///
2006    /// - `K` - The form field name, which requires the `AsRef<str>` bound.
2007    ///
2008    /// # Returns
2009    ///
2010    /// - `Option<String>` - The field value, or `None` when absent or a file.
2011    pub fn try_get_body_form_data_text<K>(&self, name: K) -> Option<String>
2012    where
2013        K: AsRef<str>,
2014    {
2015        let parts: Vec<BodyPart> = self.try_get_body_form_data()?;
2016        MultipartFormData::try_get_part_text(&parts, name)
2017    }
2018
2019    /// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
2020    ///
2021    /// # Returns
2022    ///
2023    /// - `bool` - Whether the upgrade type is h2c.
2024    #[inline(always)]
2025    pub fn is_h2c_upgrade_type(&self) -> bool {
2026        self.get_upgrade_type().is_h2c()
2027    }
2028
2029    /// Checks if the current upgrade type is TLS (any version).
2030    ///
2031    /// # Returns
2032    ///
2033    /// - `bool` - Whether the upgrade type is TLS.
2034    #[inline(always)]
2035    pub fn is_tls_upgrade_type(&self) -> bool {
2036        self.get_upgrade_type().is_tls()
2037    }
2038
2039    /// Checks whether the upgrade type is unknown.
2040    ///
2041    /// # Returns
2042    ///
2043    /// - `bool` - Whether the upgrade type is unknown.
2044    #[inline(always)]
2045    pub fn is_unknown_upgrade_type(&self) -> bool {
2046        self.get_upgrade_type().is_unknown()
2047    }
2048
2049    /// Determines if a keep-alive connection should be enabled for this request.
2050    ///
2051    /// This function checks the `Connection` header and the HTTP version to determine
2052    /// if keep-alive should be enabled. The logic is as follows:
2053    ///
2054    /// 1. If the `Connection` header exists:
2055    ///    - Returns `true` if the header value is "keep-alive" (case-insensitive).
2056    ///    - Returns `false` if the header value is "close" (case-insensitive).
2057    /// 2. If no `Connection` header is present:
2058    ///    - Returns `true` if the HTTP version is 1.1 or higher.
2059    ///    - Returns `false` otherwise.
2060    ///
2061    /// # Returns
2062    ///
2063    /// - `bool` - Whether keep-alive should be enabled.
2064    #[inline(always)]
2065    pub fn is_enable_keep_alive(&self) -> bool {
2066        if let Some(values) = self.get_headers().get(CONNECTION) {
2067            let mut has_keep_alive: bool = false;
2068            for header_value in values {
2069                if header_value == KEEP_ALIVE {
2070                    has_keep_alive = true;
2071                    continue;
2072                }
2073                for token in header_value.split(COMMA) {
2074                    let token: &str = token.trim_matches(HTTP_HEADER_OPTIONAL_WHITESPACE);
2075                    if token.eq_ignore_ascii_case(CLOSE) {
2076                        return self.is_ws_upgrade_type();
2077                    }
2078                    if token.eq_ignore_ascii_case(KEEP_ALIVE) {
2079                        has_keep_alive = true;
2080                    }
2081                }
2082            }
2083            if has_keep_alive {
2084                return true;
2085            }
2086        }
2087        self.get_version().is_http1_1_or_higher() || self.is_ws_upgrade_type()
2088    }
2089
2090    /// Determines if keep-alive should be disabled for this request.
2091    ///
2092    /// # Returns
2093    ///
2094    /// - `bool` - Whether keep-alive should be disabled.
2095    #[inline(always)]
2096    pub fn is_disable_keep_alive(&self) -> bool {
2097        !self.is_enable_keep_alive()
2098    }
2099}