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