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