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        serde_json::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.get_mut_querys().clear();
295        self.recycle_headers();
296        self.get_mut_body().clear();
297        self
298    }
299
300    /// Hands the header entries to the pool and empties the header map.
301    ///
302    /// The map ends up empty, exactly as clearing it would, but the name and
303    /// the value buffers of every header survive in the pool. The next
304    /// request on the same connection takes them back and overwrites them,
305    /// so a connection that keeps its headers stops allocating for them.
306    ///
307    /// # Returns
308    ///
309    /// - `()` - The headers have been recycled.
310    fn recycle_headers(&mut self) {
311        let headers: &mut RequestHeaders = self.get_mut_headers();
312        if headers.is_empty() {
313            return;
314        }
315        for (key, values) in headers.drain() {
316            return_header_entry((key, values));
317        }
318    }
319
320    /// Parses the first line of HTTP request into method, path, and version components.
321    ///
322    /// # Arguments
323    ///
324    /// - `&str` - The first line string of HTTP request to parse.
325    ///
326    /// # Returns
327    ///
328    /// - `Result<(RequestMethod, &str, RequestVersion), RequestError>` - A tuple containing:
329    ///   - The parsed HTTP method
330    ///   - The full path string
331    ///   - The parsed HTTP version
332    ///   - Or an error if parsing fails
333    #[inline(always)]
334    pub(crate) fn get_http_first_line(
335        line: &str,
336    ) -> Result<(RequestMethod, &str, RequestVersion), RequestError> {
337        let mut parts: SplitWhitespace<'_> = line.split_whitespace();
338        let method_str: &str = parts
339            .next()
340            .ok_or(RequestError::HttpRequestPartsInsufficient(
341                HttpStatus::BadRequest,
342            ))?;
343        let full_path: &str = parts
344            .next()
345            .ok_or(RequestError::HttpRequestPartsInsufficient(
346                HttpStatus::BadRequest,
347            ))?;
348        let version_str: &str = parts
349            .next()
350            .ok_or(RequestError::HttpRequestPartsInsufficient(
351                HttpStatus::BadRequest,
352            ))?;
353        if parts.next().is_some() {
354            return Err(RequestError::HttpRequestPartsInsufficient(
355                HttpStatus::BadRequest,
356            ));
357        }
358        let method: RequestMethod = method_str
359            .parse::<RequestMethod>()
360            .unwrap_or_else(|_: ()| Method::Unknown(method_str.to_owned()));
361        let version: RequestVersion = match version_str.parse::<RequestVersion>() {
362            Ok(RequestVersion::Unknown(_)) | Err(_) => {
363                return Err(RequestError::HttpRequestPartsInsufficient(
364                    HttpStatus::BadRequest,
365                ));
366            }
367            Ok(version) => version,
368        };
369        Ok((method, full_path, version))
370    }
371
372    /// Validates the path length against the maximum allowed size.
373    ///
374    /// # Arguments
375    ///
376    /// - `&str` - The path string to check.
377    /// - `usize` - The maximum allowed path size.
378    ///
379    /// # Returns
380    ///
381    /// - `Result<(), RequestError>` - Ok if valid, or an error if the path is too long.
382    #[inline(always)]
383    pub(crate) fn check_http_path_size(path: &str, max_size: usize) -> Result<(), RequestError> {
384        if path.len() > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
385            return Err(RequestError::PathTooLong(HttpStatus::URITooLong));
386        }
387        Ok(())
388    }
389
390    /// Parses the query string from the full path.
391    ///
392    /// Handles both query parameters (after `?`) and hash fragments (after `#`),
393    /// ensuring proper parsing when both are present.
394    ///
395    /// # Arguments
396    ///
397    /// - `&str` - The full path string containing the query.
398    /// - `Option<usize>` - The index of the query separator (`?`), if present.
399    /// - `Option<usize>` - The index of the hash separator (`#`), if present.
400    ///
401    /// # Returns
402    ///
403    /// - `&str` - The parsed query string slice, or empty string if no query.
404    #[inline(always)]
405    pub(crate) fn get_http_query(
406        path: &str,
407        query_index: Option<usize>,
408        hash_index: Option<usize>,
409    ) -> &str {
410        query_index.map_or(EMPTY_STR, |query_index: usize| {
411            let temp: &str = &path[query_index + 1..];
412            match hash_index {
413                None => temp,
414                Some(hash_index) if hash_index <= query_index => temp,
415                Some(hash_index) => &temp[..hash_index - query_index - 1],
416            }
417        })
418    }
419
420    /// Parses the request path without query string or hash fragment.
421    ///
422    /// # Arguments
423    ///
424    /// - `&str` - The full path string.
425    /// - `Option<usize>` - The index of the query separator (`?`), if present.
426    /// - `Option<usize>` - The index of the hash separator (`#`), if present.
427    ///
428    /// # Returns
429    ///
430    /// - `&str` - The request path slice without query or hash.
431    #[inline(always)]
432    pub(crate) fn get_http_path(
433        path: &str,
434        query_index: Option<usize>,
435        hash_index: Option<usize>,
436    ) -> &str {
437        match query_index.or(hash_index) {
438            Some(separator_index) => &path[..separator_index],
439            None => path,
440        }
441    }
442
443    /// Parses a query string as_ref key-value pairs into the given map.
444    ///
445    /// Expects format "key1=value1&key2=value2". Empty values are allowed, and a
446    /// key that repeats keeps every value instead of letting the last one win.
447    /// The target map is expected to be empty; entries are inserted without
448    /// reallocating the map when it already has sufficient capacity.
449    ///
450    /// # Arguments
451    ///
452    /// - `&str` - The query string to parse.
453    /// - `&mut RequestQuerys` - The map to insert parsed parameters into.
454    #[inline(always)]
455    pub(crate) fn fill_http_querys(query: &str, querys: &mut RequestQuerys) {
456        if query.is_empty() {
457            return;
458        }
459        for pair in query.split(AND) {
460            if let Some((key, value)) = pair.split_once(EQUAL) {
461                if !key.is_empty() {
462                    querys
463                        .entry(key.to_string())
464                        .or_default()
465                        .push_back(value.to_string());
466                }
467            } else if !pair.is_empty() {
468                querys.entry(pair.to_string()).or_default();
469            }
470        }
471    }
472
473    /// Checks if the header count exceeds the maximum allowed.
474    ///
475    /// # Arguments
476    ///
477    /// - `usize` - The current number of headers parsed.
478    /// - `usize` - The maximum allowed number of headers.
479    ///
480    /// # Returns
481    ///
482    /// - `Result<(), RequestError>` - Returns an error if the limit is exceeded and not in low security mode.
483    #[inline(always)]
484    pub(crate) fn check_http_header_count(
485        count: usize,
486        max_count: usize,
487    ) -> Result<(), RequestError> {
488        if count > max_count && max_count != DEFAULT_LOW_SECURITY_MAX_HEADER_COUNT {
489            return Err(RequestError::TooManyHeaders(
490                HttpStatus::RequestHeaderFieldsTooLarge,
491            ));
492        }
493        Ok(())
494    }
495
496    /// Checks if a header key exceeds the maximum allowed length.
497    ///
498    /// # Arguments
499    ///
500    /// - `&str` - The header key to check.
501    /// - `usize` - The maximum allowed length for a header key.
502    ///
503    /// # Returns
504    ///
505    /// - `Result<(), RequestError>` - Returns an error if the limit is exceeded and not in low security mode.
506    #[inline(always)]
507    pub(crate) fn check_http_header_key_size(
508        key: &str,
509        max_size: usize,
510    ) -> Result<(), RequestError> {
511        if key.len() > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_HEADER_KEY_SIZE {
512            return Err(RequestError::HeaderKeyTooLong(
513                HttpStatus::RequestHeaderFieldsTooLarge,
514            ));
515        }
516        Ok(())
517    }
518
519    /// Checks if a header value exceeds the maximum allowed length.
520    ///
521    /// # Arguments
522    ///
523    /// - `&str` - The header value to check.
524    /// - `usize` - The maximum allowed length for a header value.
525    ///
526    /// # Returns
527    ///
528    /// - `Result<(), RequestError>` - Returns an error if the limit is exceeded and not in low security mode.
529    #[inline(always)]
530    pub(crate) fn check_http_header_value_size(
531        value: &str,
532        max_size: usize,
533    ) -> Result<(), RequestError> {
534        if value.len() > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_HEADER_VALUE_SIZE {
535            return Err(RequestError::HeaderValueTooLong(
536                HttpStatus::RequestHeaderFieldsTooLarge,
537            ));
538        }
539        Ok(())
540    }
541
542    /// Parses the Content-Length header value and checks it against max body size.
543    ///
544    /// # Arguments
545    ///
546    /// - `&str` - The Content-Length header value string.
547    /// - `usize` - The maximum allowed body size.
548    ///
549    /// # Returns
550    ///
551    /// - `Result<usize, RequestError>` - The parsed content length or an error.
552    #[inline(always)]
553    pub(crate) fn check_http_body_size(
554        value: &str,
555        max_size: usize,
556    ) -> Result<usize, RequestError> {
557        if value.is_empty() || !value.bytes().all(|byte: u8| byte.is_ascii_digit()) {
558            return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
559        }
560        let length: usize = value.parse::<usize>()?;
561        if length > max_size && max_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE {
562            return Err(RequestError::ContentLengthTooLarge(
563                HttpStatus::PayloadTooLarge,
564            ));
565        }
566        Ok(length)
567    }
568
569    /// Parses HTTP headers from a buffered reader into this request.
570    ///
571    /// This method reads header lines from the provided buffered reader until an empty line
572    /// is encountered, which indicates the end of headers. It checks header count, length,
573    /// and content according to the provided configuration. The request's headers map and
574    /// host string are expected to be empty; they are filled without reallocating when they
575    /// already have sufficient capacity.
576    ///
577    /// The line buffer belongs to the caller so that a keep-alive connection
578    /// reads every header line of every request into the same allocation.
579    ///
580    /// # Arguments
581    ///
582    /// - `&mut R` - A mutable reference to a buffered reader, which requires the
583    ///   `AsyncBufReadExt + Unpin` bound.
584    /// - `&RequestConfig` - Configuration for security limits and buffer settings.
585    /// - `&mut String` - The buffer the header lines are read into.
586    ///
587    /// # Returns
588    ///
589    /// - `Result<RequestFraming, RequestError>` - The body framing, or an error if parsing fails.
590    pub(crate) async fn get_http_headers<R>(
591        &mut self,
592        reader: &mut R,
593        config: &RequestConfig,
594        header_line_buffer: &mut String,
595    ) -> Result<RequestFraming, RequestError>
596    where
597        R: AsyncBufReadExt + Unpin,
598    {
599        let Request {
600            headers,
601            host,
602            version,
603            ..
604        } = self;
605        let max_header_count: usize = config.get_max_header_count();
606        let max_header_key_size: usize = config.get_max_header_key_size();
607        let max_header_value_size: usize = config.get_max_header_value_size();
608        let max_body_size: usize = config.get_max_body_size();
609        let mut content_size: usize = 0;
610        let mut header_count: usize = 0;
611        let mut content_length_seen: bool = false;
612        let mut transfer_encoding_seen: bool = false;
613        let mut host_seen: bool = false;
614        loop {
615            header_line_buffer.clear();
616            AsyncBufReadExt::read_line(reader, header_line_buffer).await?;
617            let header_line: &str = header_line_buffer
618                .strip_suffix(HTTP_HEADER_LINE_FEED)
619                .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
620            let header_line: &str = header_line
621                .strip_suffix(HTTP_HEADER_CARRIAGE_RETURN)
622                .unwrap_or(header_line);
623            if header_line.is_empty() {
624                break;
625            }
626            if header_line.starts_with(HTTP_HEADER_OPTIONAL_WHITESPACE) {
627                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
628            }
629            header_count += 1;
630            Self::check_http_header_count(header_count, max_header_count)?;
631            let (key, value_part): (&str, &str) = header_line
632                .split_once(COLON)
633                .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
634            let valid_key: bool = key.bytes().all(|byte: u8| {
635                byte.is_ascii_alphanumeric() || HTTP_HEADER_TOKEN_PUNCTUATION.contains(&byte)
636            });
637            if key.is_empty() || !valid_key {
638                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
639            }
640            Self::check_http_header_key_size(key, max_header_key_size)?;
641            if value_part.bytes().any(|byte: u8| {
642                (byte < HTTP_HEADER_CONTROL_LIMIT && byte != HTTP_HEADER_TAB)
643                    || byte == HTTP_HEADER_DELETE
644            }) {
645                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
646            }
647            let value: &str = value_part.trim_matches(HTTP_HEADER_OPTIONAL_WHITESPACE);
648            Self::check_http_header_value_size(value, max_header_value_size)?;
649            match key {
650                key if key.eq_ignore_ascii_case(HTTP_HEADER_TRANSFER_ENCODING) => {
651                    if *version != HTTP_HOST_REQUIRED_VERSION || content_length_seen {
652                        return Err(RequestError::HttpRead(HttpStatus::BadRequest));
653                    }
654                    transfer_encoding_seen = true;
655                }
656                key if key.eq_ignore_ascii_case(HOST) => {
657                    if host_seen {
658                        return Err(RequestError::HttpRead(HttpStatus::BadRequest));
659                    }
660                    host_seen = true;
661                    host.clear();
662                    host.push_str(value);
663                }
664                key if key.eq_ignore_ascii_case(CONTENT_LENGTH) => {
665                    if transfer_encoding_seen {
666                        return Err(RequestError::HttpRead(HttpStatus::BadRequest));
667                    }
668                    if content_length_seen {
669                        return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
670                    }
671                    content_length_seen = true;
672                    content_size = Self::check_http_body_size(value, max_body_size)?;
673                }
674                _ => {}
675            }
676            Self::insert_http_header(headers, key, value);
677        }
678        if *version == HTTP_HOST_REQUIRED_VERSION && !host_seen {
679            return Err(RequestError::HttpRead(HttpStatus::BadRequest));
680        }
681        if transfer_encoding_seen {
682            let values: &RequestHeadersValue = headers
683                .get(HTTP_HEADER_TRANSFER_ENCODING)
684                .ok_or(RequestError::HttpRead(HttpStatus::BadRequest))?;
685            return r#fn::parse_transfer_encoding(values);
686        }
687        Ok(RequestFraming::Fixed(content_size))
688    }
689
690    /// Replaces wire chunk framing with the decoded content length.
691    #[cold]
692    pub(crate) fn normalize_chunked_headers(&mut self) {
693        let mut digits: [u8; B_20] = [0; B_20];
694        let length: &str = render_length(self.get_body().len(), &mut digits);
695        let headers: &mut RequestHeaders = self.get_mut_headers();
696        headers.remove(HTTP_HEADER_TRANSFER_ENCODING);
697        headers.remove(HTTP_HEADER_TRAILER);
698        Self::insert_http_header(headers, CONTENT_LENGTH, length);
699    }
700
701    /// Stores one header, reusing a pooled name and value where possible.
702    ///
703    /// The name is lowercased into the buffer of a recycled entry and the
704    /// value is written into that entry's value buffer, so a header that was
705    /// already seen on this connection costs no allocation at all.
706    ///
707    /// # Arguments
708    ///
709    /// - `&mut RequestHeaders` - The header map to store the header in.
710    /// - `&str` - The header name, as it arrived.
711    /// - `&str` - The header value.
712    fn insert_http_header(headers: &mut RequestHeaders, key: &str, value: &str) {
713        let (mut name, mut values): (String, VecDeque<String>) =
714            take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
715        name.clear();
716        name.push_str(key);
717        name.make_ascii_lowercase();
718        match headers.entry(name) {
719            Entry::Occupied(mut occupied) => {
720                // The header repeats: it keeps every value it was given.
721                occupied.get_mut().push_back(value.to_string());
722                return_header_entry((String::new(), values));
723            }
724            Entry::Vacant(vacant) => {
725                // A recycled entry may carry the values of a header that was
726                // sent more than once. Those values belong to that header, so
727                // only the first one is kept and the rest are dropped.
728                while values.len() > 1 {
729                    values.pop_back();
730                }
731                if values.is_empty() {
732                    values.push_back(String::new());
733                }
734                if let Some(slot) = values.front_mut() {
735                    slot.clear();
736                    slot.push_str(value);
737                }
738                vacant.insert(values);
739            }
740        }
741    }
742
743    /// Reads the request body from the buffered reader into the given buffer.
744    ///
745    /// The target buffer is cleared and resized to the expected content size,
746    /// retaining its allocation when it already has sufficient capacity.
747    ///
748    /// # Arguments
749    ///
750    /// - `&mut R` - The buffered reader to read from, which requires the `AsyncRead + Unpin` bound.
751    /// - `&mut RequestBody` - The buffer to read the body bytes into.
752    /// - `usize` - The expected content size.
753    ///
754    /// # Returns
755    ///
756    /// - `Result<(), RequestError>` - Ok on success, or an error if reading fails.
757    #[inline(always)]
758    pub(crate) async fn fill_http_body<R>(
759        reader: &mut R,
760        body: &mut RequestBody,
761        content_size: usize,
762    ) -> Result<(), RequestError>
763    where
764        R: AsyncRead + Unpin,
765    {
766        body.clear();
767        if content_size > 0 {
768            body.resize(content_size, 0);
769            AsyncReadExt::read_exact(reader, body).await?;
770        }
771        Ok(())
772    }
773
774    /// Tries to get a query parameter by key.
775    ///
776    /// The key type must implement AsRef<str> conversion. A key that repeats in
777    /// the query carries every one of its values.
778    ///
779    /// # Arguments
780    ///
781    /// - `K` - The query parameter key, which implements `AsRef<str>`.
782    ///
783    /// # Returns
784    ///
785    /// - `Option<RequestQuerysValue>` - Every value of the parameter if it exists.
786    #[inline(always)]
787    pub fn try_get_query<K>(&self, key: K) -> Option<RequestQuerysValue>
788    where
789        K: AsRef<str>,
790    {
791        self.get_querys().get(key.as_ref()).cloned()
792    }
793
794    /// Tries to get the first query parameter value by key.
795    ///
796    /// Use this when the parameter is expected to appear once; use
797    /// `try_get_query` when every value matters.
798    ///
799    /// # Arguments
800    ///
801    /// - `K` - The query parameter key, which implements `AsRef<str>`.
802    ///
803    /// # Returns
804    ///
805    /// - `Option<RequestQuerysValueItem>` - The first parameter value if it exists.
806    #[inline(always)]
807    pub fn try_get_query_front<K>(&self, key: K) -> Option<RequestQuerysValueItem>
808    where
809        K: AsRef<str>,
810    {
811        self.get_querys()
812            .get(key.as_ref())
813            .and_then(|values: &VecDeque<String>| values.front().cloned())
814    }
815
816    /// Tries to get the last query parameter value by key.
817    ///
818    /// # Arguments
819    ///
820    /// - `K` - The query parameter key, which implements `AsRef<str>`.
821    ///
822    /// # Returns
823    ///
824    /// - `Option<RequestQuerysValueItem>` - The last parameter value if it exists.
825    #[inline(always)]
826    pub fn try_get_query_back<K>(&self, key: K) -> Option<RequestQuerysValueItem>
827    where
828        K: AsRef<str>,
829    {
830        self.get_querys()
831            .get(key.as_ref())
832            .and_then(|values: &VecDeque<String>| values.back().cloned())
833    }
834
835    /// Tries to get the number of values of a query parameter.
836    ///
837    /// # Arguments
838    ///
839    /// - `K` - The query parameter key, which implements `AsRef<str>`.
840    ///
841    /// # Returns
842    ///
843    /// - `Option<usize>` - The number of values if the parameter exists.
844    #[inline(always)]
845    pub fn try_get_query_size<K>(&self, key: K) -> Option<usize>
846    where
847        K: AsRef<str>,
848    {
849        self.get_querys()
850            .get(key.as_ref())
851            .map(|values: &VecDeque<String>| values.len())
852    }
853
854    /// Checks whether a query parameter exists.
855    ///
856    /// # Arguments
857    ///
858    /// - `K` - The query parameter key, which implements `AsRef<str>`.
859    ///
860    /// # Returns
861    ///
862    /// - `bool` - Whether the parameter exists.
863    #[inline(always)]
864    pub fn has_query<K>(&self, key: K) -> bool
865    where
866        K: AsRef<str>,
867    {
868        self.get_querys().contains_key(key.as_ref())
869    }
870
871    /// Gets a query parameter by key.
872    ///
873    /// # Arguments
874    ///
875    /// - `K` - The query parameter key, which implements `AsRef<str>`.
876    ///
877    /// # Returns
878    ///
879    /// - `RequestQuerysValue` - Every value of the parameter.
880    ///
881    /// # Panics
882    ///
883    /// This function will panic if the query parameter key is not found.
884    #[inline(always)]
885    pub fn get_query<K>(&self, key: K) -> RequestQuerysValue
886    where
887        K: AsRef<str>,
888    {
889        self.try_get_query(key).unwrap()
890    }
891
892    /// Gets the first query parameter value by key.
893    ///
894    /// # Arguments
895    ///
896    /// - `K` - The query parameter key, which implements `AsRef<str>`.
897    ///
898    /// # Returns
899    ///
900    /// - `RequestQuerysValueItem` - The first parameter value.
901    ///
902    /// # Panics
903    ///
904    /// This function will panic if the query parameter key is not found.
905    #[inline(always)]
906    pub fn get_query_front<K>(&self, key: K) -> RequestQuerysValueItem
907    where
908        K: AsRef<str>,
909    {
910        self.try_get_query_front(key).unwrap()
911    }
912
913    /// Retrieves the number of query parameters.
914    ///
915    /// # Returns
916    ///
917    /// - `usize` - The count of distinct query parameter keys.
918    #[inline(always)]
919    pub fn get_querys_size(&self) -> usize {
920        self.get_querys().len()
921    }
922
923    /// Tries to retrieve the value of a request header by its key.
924    ///
925    /// The key is matched case-insensitively, because the parser stores every
926    /// header name lowercased and an HTTP header name is case-insensitive by
927    /// specification. Looking a header up with `Content-Type` and with
928    /// `content-type` therefore find the same value.
929    ///
930    /// # Arguments
931    ///
932    /// - `K` - The header's key, which must implement `AsRef<str>`.
933    ///
934    /// # Returns
935    ///
936    /// - `Option<RequestHeadersValue>` - The optional header values.
937    #[inline(always)]
938    pub fn try_get_header<K>(&self, key: K) -> Option<RequestHeadersValue>
939    where
940        K: AsRef<str>,
941    {
942        self.get_headers()
943            .get(&key.as_ref().to_ascii_lowercase())
944            .cloned()
945    }
946
947    /// Retrieves the value of a request header by its key.
948    ///
949    /// # Arguments
950    ///
951    /// - `K` - The header's key, which must implement `AsRef<str>`.
952    ///
953    /// # Returns
954    ///
955    /// - `RequestHeadersValue` - The optional header values.
956    ///
957    /// # Panics
958    ///
959    /// This function will panic if the header key is not found.
960    #[inline(always)]
961    pub fn get_header<K>(&self, key: K) -> RequestHeadersValue
962    where
963        K: AsRef<str>,
964    {
965        self.try_get_header(key).unwrap()
966    }
967
968    /// Tries to retrieve the first value of a request header by its key.
969    ///
970    /// # Arguments
971    ///
972    /// - `K` - The header's key, which must implement `AsRef<str>`.
973    ///
974    /// # Returns
975    ///
976    /// - `Option<RequestHeadersValueItem>` - The first header value if exists.
977    #[inline(always)]
978    pub fn try_get_header_front<K>(&self, key: K) -> Option<RequestHeadersValueItem>
979    where
980        K: AsRef<str>,
981    {
982        self.get_headers()
983            .get(&key.as_ref().to_ascii_lowercase())
984            .and_then(|header_values: &VecDeque<String>| header_values.front().cloned())
985    }
986
987    /// Retrieves the first value of a request header by its key.
988    ///
989    /// # Arguments
990    ///
991    /// - `K` - The header's key, which must implement `AsRef<str>`.
992    ///
993    /// # Returns
994    ///
995    /// - `RequestHeadersValueItem` - The first header value if exists.
996    ///
997    /// # Panics
998    ///
999    /// This function will panic if the header key is not found.
1000    #[inline(always)]
1001    pub fn get_header_front<K>(&self, key: K) -> RequestHeadersValueItem
1002    where
1003        K: AsRef<str>,
1004    {
1005        self.try_get_header_front(key).unwrap()
1006    }
1007
1008    /// Tries to retrieve the last value of a request header by its key.
1009    ///
1010    /// # Arguments
1011    ///
1012    /// - `K` - The header's key, which must implement `AsRef<str>`.
1013    ///
1014    /// # Returns
1015    ///
1016    /// - `Option<RequestHeadersValueItem>` - The last header value if exists.
1017    #[inline(always)]
1018    pub fn try_get_header_back<K>(&self, key: K) -> Option<RequestHeadersValueItem>
1019    where
1020        K: AsRef<str>,
1021    {
1022        self.get_headers()
1023            .get(&key.as_ref().to_ascii_lowercase())
1024            .and_then(|header_values: &VecDeque<String>| header_values.back().cloned())
1025    }
1026
1027    /// Retrieves the last value of a request header by its key.
1028    ///
1029    /// # Arguments
1030    ///
1031    /// - `K` - The header's key, which must implement `AsRef<str>`.
1032    ///
1033    /// # Returns
1034    ///
1035    /// - `RequestHeadersValueItem` - The last header value if exists.
1036    ///
1037    /// # Panics
1038    ///
1039    /// This function will panic if the header key is not found.
1040    #[inline(always)]
1041    pub fn get_header_back<K>(&self, key: K) -> RequestHeadersValueItem
1042    where
1043        K: AsRef<str>,
1044    {
1045        self.try_get_header_back(key).unwrap()
1046    }
1047
1048    /// Tries to retrieve the number of values for a specific header.
1049    ///
1050    /// # Arguments
1051    ///
1052    /// - `K` - The header's key, which must implement `AsRef<str>`.
1053    ///
1054    /// # Returns
1055    ///
1056    /// - `Option<usize>` - The count of values for the header if exists.
1057    #[inline(always)]
1058    pub fn try_get_header_size<K>(&self, key: K) -> Option<usize>
1059    where
1060        K: AsRef<str>,
1061    {
1062        self.get_headers()
1063            .get(&key.as_ref().to_ascii_lowercase())
1064            .map(|header_values: &VecDeque<String>| header_values.len())
1065    }
1066
1067    /// Retrieves the number of values for a specific header.
1068    ///
1069    /// # Arguments
1070    ///
1071    /// - `K` - The header's key, which must implement `AsRef<str>`.
1072    ///
1073    /// # Returns
1074    ///
1075    /// - `usize` - The count of values for the header.
1076    ///
1077    /// # Panics
1078    ///
1079    /// This function will panic if the header key is not found.
1080    #[inline(always)]
1081    pub fn get_header_size<K>(&self, key: K) -> usize
1082    where
1083        K: AsRef<str>,
1084    {
1085        self.try_get_header_size(key).unwrap()
1086    }
1087
1088    /// Retrieves the total number of header values across all headers.
1089    ///
1090    /// # Returns
1091    ///
1092    /// - `usize` - The total count of all header values.
1093    #[inline(always)]
1094    pub fn get_headers_values_size(&self) -> usize {
1095        self.get_headers()
1096            .values()
1097            .map(|header_values: &VecDeque<String>| header_values.len())
1098            .sum()
1099    }
1100
1101    /// Retrieves the number of unique headers.
1102    ///
1103    /// # Returns
1104    ///
1105    /// - `usize` - The count of unique header keys.
1106    #[inline(always)]
1107    pub fn get_headers_size(&self) -> usize {
1108        self.get_headers().len()
1109    }
1110
1111    /// Checks if a specific header exists.
1112    ///
1113    /// # Arguments
1114    ///
1115    /// - `K` - The header key to check, which must implement `AsRef<str>`.
1116    ///
1117    /// # Returns
1118    ///
1119    /// - `bool` - Whether the header exists.
1120    #[inline(always)]
1121    pub fn has_header<K>(&self, key: K) -> bool
1122    where
1123        K: AsRef<str>,
1124    {
1125        self.get_headers()
1126            .contains_key(&key.as_ref().to_ascii_lowercase())
1127    }
1128
1129    /// Checks if a header contains a specific value.
1130    ///
1131    /// # Arguments
1132    ///
1133    /// - `K` - The header key to check, which must implement `AsRef<str>`.
1134    /// - `V` - The value to search for, which must implement `AsRef<str>`.
1135    ///
1136    /// # Returns
1137    ///
1138    /// - `bool` - Whether the header contains the value.
1139    #[inline(always)]
1140    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
1141    where
1142        K: AsRef<str>,
1143        V: AsRef<str>,
1144    {
1145        if let Some(values) = self.get_headers().get(&key.as_ref().to_ascii_lowercase()) {
1146            values.iter().any(|data: &String| data == value.as_ref())
1147        } else {
1148            false
1149        }
1150    }
1151
1152    /// Checks `If-None-Match` against the entity-tag of an existing representation.
1153    ///
1154    /// This explicitly invoked helper borrows normalized request headers and allocates nothing.
1155    /// Strong and weak tags use case-sensitive weak comparison of their opaque values.
1156    /// Repeated fields form one list; optional spaces, tabs, and empty list members are ignored.
1157    /// A wildcard matches only when the entire field combination is a standalone `*`.
1158    /// Missing headers, empty lists, invalid tags, or any malformed suffix return `false`,
1159    /// even if an earlier tag matched. The current tag must be exactly one valid entity-tag,
1160    /// without surrounding whitespace. Quoted commas and empty opaque values are valid;
1161    /// backslashes are literal bytes, not escape characters.
1162    ///
1163    /// Call only for a representation that already exists. This does not send a response,
1164    /// automatically generate a 304, or implement complete HTTP precondition evaluation.
1165    /// Callers decide whether to send 304 for GET/HEAD or 412 for other methods and must
1166    /// handle precondition ordering themselves. Do not use this for `If-Match`, which
1167    /// requires strong comparison.
1168    ///
1169    /// # Arguments
1170    ///
1171    /// - `&str` - The current representation's complete strong or weak entity-tag.
1172    ///
1173    /// # Returns
1174    ///
1175    /// - `bool` - Whether a completely valid `If-None-Match` matches the existing representation.
1176    #[must_use]
1177    pub fn matches_if_none_match(&self, current_etag: &str) -> bool {
1178        let current: &[u8] = match r#fn::parse_entity_tag(current_etag.as_bytes()) {
1179            Some((opaque, [])) => opaque,
1180            _ => return false,
1181        };
1182        let values: &RequestHeadersValue = match self.get_headers().get(IF_NONE_MATCH) {
1183            Some(values) => values,
1184            None => return false,
1185        };
1186        if values.len() == 1
1187            && values.front().is_some_and(|value: &String| {
1188                value
1189                    .trim_matches(&HTTP_HEADER_OPTIONAL_WHITESPACE[..])
1190                    .as_bytes()
1191                    == ENTITY_TAG_WILDCARD
1192            })
1193        {
1194            return true;
1195        }
1196        let mut matched: bool = false;
1197        for value in values {
1198            let mut remaining: &[u8] = value.as_bytes();
1199            while !remaining.is_empty() {
1200                while remaining
1201                    .first()
1202                    .is_some_and(|byte: &u8| ENTITY_TAG_LIST_PADDING.contains(byte))
1203                {
1204                    remaining = &remaining[1..];
1205                }
1206                if remaining.is_empty() {
1207                    break;
1208                }
1209                let (candidate, suffix): (&[u8], &[u8]) = match r#fn::parse_entity_tag(remaining) {
1210                    Some(parsed) => parsed,
1211                    None => return false,
1212                };
1213                matched |= candidate == current;
1214                remaining = suffix;
1215                while remaining
1216                    .first()
1217                    .is_some_and(|byte: &u8| ENTITY_TAG_OPTIONAL_WHITESPACE.contains(byte))
1218                {
1219                    remaining = &remaining[1..];
1220                }
1221                if remaining.is_empty() {
1222                    break;
1223                }
1224                if remaining.first() != Some(&ENTITY_TAG_SEPARATOR) {
1225                    return false;
1226                }
1227                remaining = &remaining[1..];
1228            }
1229        }
1230        matched
1231    }
1232
1233    /// Tries to parse cookies from the `Cookie` header.
1234    ///
1235    /// This method retrieves the `Cookie` header value and parses it into
1236    /// a collection of key-value pairs representing the cookies.
1237    ///
1238    /// # Returns
1239    ///
1240    /// - `Option<Cookies>` - The parsed cookies if the header exists, otherwise `None`.
1241    #[inline(always)]
1242    pub fn try_get_cookies(&self) -> Option<Cookies> {
1243        self.try_get_header_back(COOKIE)
1244            .map(|cookie_header: String| Cookie::parse(cookie_header))
1245    }
1246
1247    /// Parses cookies from the `Cookie` header.
1248    ///
1249    /// This method retrieves the `Cookie` header value and parses it into
1250    /// a collection of key-value pairs representing the cookies.
1251    ///
1252    /// # Returns
1253    ///
1254    /// - `Cookies` - The parsed cookies.
1255    ///
1256    /// # Panics
1257    ///
1258    /// This function will panic if the `Cookie` header is not found.
1259    #[inline(always)]
1260    pub fn get_cookies(&self) -> Cookies {
1261        self.try_get_cookies().unwrap()
1262    }
1263
1264    /// Tries to get a cookie value by its key.
1265    ///
1266    /// This method first parses the cookies from the `Cookie` header,
1267    /// then attempts to retrieve the value for the specified key.
1268    ///
1269    /// # Arguments
1270    ///
1271    /// - `K` - The cookie key, which implements `AsRef<str>`.
1272    ///
1273    /// # Returns
1274    ///
1275    /// - `Option<CookieValue>` - The cookie value if exists.
1276    #[inline(always)]
1277    pub fn try_get_cookie<K>(&self, key: K) -> Option<CookieValue>
1278    where
1279        K: AsRef<str>,
1280    {
1281        self.try_get_cookies()
1282            .and_then(|cookies: Cookies| cookies.get(key.as_ref()).cloned())
1283    }
1284
1285    /// Gets a cookie value by its key.
1286    ///
1287    /// This method first parses the cookies from the `Cookie` header,
1288    /// then retrieves the value for the specified key.
1289    ///
1290    /// # Arguments
1291    ///
1292    /// - `K` - The cookie key, which implements `AsRef<str>`.
1293    ///
1294    /// # Returns
1295    ///
1296    /// - `CookieValue` - The cookie value.
1297    ///
1298    /// # Panics
1299    ///
1300    /// This function will panic if the `Cookie` header is not found
1301    /// or the cookie key does not exist.
1302    #[inline(always)]
1303    pub fn get_cookie<K>(&self, key: K) -> CookieValue
1304    where
1305        K: AsRef<str>,
1306    {
1307        self.try_get_cookie(key).unwrap()
1308    }
1309
1310    /// Retrieves the upgrade type from the request headers.
1311    ///
1312    /// This method looks for the `UPGRADE` header and attempts to parse its value
1313    /// as_ref an `UpgradeType`. If the header is missing or the value is invalid,
1314    /// it returns the default `UpgradeType`.
1315    ///
1316    /// # Returns
1317    ///
1318    /// - `UpgradeType` - The parsed upgrade type.
1319    #[inline(always)]
1320    pub fn get_upgrade_type(&self) -> UpgradeType {
1321        self.get_headers()
1322            .get(UPGRADE)
1323            .and_then(|values: &VecDeque<String>| values.back())
1324            .and_then(|data: &String| data.parse::<UpgradeType>().ok())
1325            .unwrap_or_default()
1326    }
1327
1328    /// Retrieves the body content of the request as a UTF-8 encoded string.
1329    ///
1330    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as a string.
1331    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
1332    ///
1333    /// # Returns
1334    ///
1335    /// - `String` - The body content as a string.
1336    #[inline(always)]
1337    pub fn get_body_string(&self) -> String {
1338        String::from_utf8_lossy(self.get_body()).into_owned()
1339    }
1340
1341    /// Deserializes the body content of the request as_ref a specified type `T`.
1342    ///
1343    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
1344    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
1345    ///
1346    /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
1347    ///
1348    /// # Returns
1349    ///
1350    /// - `Result<T, serde_json::Error>` - The deserialization result.
1351    #[inline(always)]
1352    pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
1353    where
1354        T: DeserializeOwned,
1355    {
1356        serde_json::from_slice(self.get_body())
1357    }
1358
1359    /// Deserializes the body content of the request as_ref a specified type `T`.
1360    ///
1361    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
1362    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
1363    ///
1364    /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
1365    ///
1366    /// # Returns
1367    ///
1368    /// - `T` - The deserialized body content.
1369    ///
1370    /// # Panics
1371    ///
1372    /// This function will panic if the deserialization fails.
1373    #[inline(always)]
1374    pub fn get_body_json<T>(&self) -> T
1375    where
1376        T: DeserializeOwned,
1377    {
1378        self.try_get_body_json().unwrap()
1379    }
1380
1381    /// Checks whether the WebSocket upgrade is enabled for this request.
1382    ///
1383    /// This method determines if the `UPGRADE` header indicates a WebSocket connection.
1384    ///
1385    /// # Returns
1386    ///
1387    /// - `bool` - Whether WebSocket upgrade is enabled.
1388    #[inline(always)]
1389    pub fn is_ws_upgrade_type(&self) -> bool {
1390        self.get_upgrade_type().is_ws()
1391    }
1392
1393    /// Checks whether the request declares a `multipart/form-data` body.
1394    ///
1395    /// # Returns
1396    ///
1397    /// - `bool` - Whether the request content type is `multipart/form-data`.
1398    #[inline(always)]
1399    pub fn is_multipart_form_data(&self) -> bool {
1400        self.try_get_content_type()
1401            .map(|content_type: String| MultipartFormData::is_form_data(content_type))
1402            .unwrap_or(false)
1403    }
1404
1405    /// Tries to get the request content type with its parameters stripped.
1406    ///
1407    /// A `Content-Type` header such as `text/html; charset=utf-8` yields the
1408    /// media type alone, so a caller comparing against a media type does not
1409    /// have to know that parameters may follow it.
1410    ///
1411    /// # Returns
1412    ///
1413    /// - `Option<RequestContentType>` - The media type, or `None` when the header is absent.
1414    #[inline(always)]
1415    pub fn try_get_content_type(&self) -> Option<RequestContentType> {
1416        self.try_get_header_front(CONTENT_TYPE)
1417            .map(|value: String| {
1418                value
1419                    .split(SEMICOLON)
1420                    .next()
1421                    .unwrap_or(EMPTY_STR)
1422                    .trim()
1423                    .to_ascii_lowercase()
1424            })
1425    }
1426
1427    /// Tries to get one parameter of the request `Content-Type` header.
1428    ///
1429    /// The name is matched case-insensitively and a quoted value is unquoted,
1430    /// so both `boundary=abc` and `boundary="abc"` yield `abc`.
1431    ///
1432    /// # Arguments
1433    ///
1434    /// - `K` - The parameter name, which requires the `AsRef<str>` bound.
1435    ///
1436    /// # Returns
1437    ///
1438    /// - `Option<RequestContentTypeParameter>` - The parameter value, or `None` when absent.
1439    pub fn try_get_content_type_parameter<K>(&self, name: K) -> Option<RequestContentTypeParameter>
1440    where
1441        K: AsRef<str>,
1442    {
1443        let content_type: String = self.try_get_header_front(CONTENT_TYPE)?;
1444        let name: &str = name.as_ref();
1445        for parameter in content_type.split(SEMICOLON).skip(1) {
1446            let (key, value) = parameter.trim().split_once(EQUAL)?;
1447            if !key.trim().eq_ignore_ascii_case(name) {
1448                continue;
1449            }
1450            let value: &str = value.trim();
1451            let value: &str = value
1452                .strip_prefix(MULTIPART_PARAMETER_QUOTE)
1453                .and_then(|value: &str| value.strip_suffix(MULTIPART_PARAMETER_QUOTE))
1454                .unwrap_or(value);
1455            if !value.is_empty() {
1456                return Some(value.to_string());
1457            }
1458        }
1459        None
1460    }
1461
1462    /// Tries to decode a `multipart/form-data` body into its parts.
1463    ///
1464    /// The boundary is read from the request `Content-Type` header rather than
1465    /// guessed, so a body whose content type declares no boundary, a truncated
1466    /// body, and a part without a name all yield `None`.
1467    ///
1468    /// # Returns
1469    ///
1470    /// - `Option<MultipartFormDataParts>` - The decoded parts, or `None` when unavailable.
1471    pub fn try_get_body_form_data(&self) -> Option<MultipartFormDataParts> {
1472        let boundary: MultipartFormDataBoundary =
1473            self.try_get_content_type_parameter(MULTIPART_BOUNDARY_PARAMETER)?;
1474        MultipartFormData::parse(self.get_body(), &boundary)
1475    }
1476
1477    /// Decodes an `application/x-www-form-urlencoded` body into its fields.
1478    ///
1479    /// # Returns
1480    ///
1481    /// - `BodyForm` - The decoded form fields.
1482    #[inline(always)]
1483    pub fn get_body_form(&self) -> BodyForm {
1484        MultipartFormData::parse_url_encoded(self.get_body())
1485    }
1486
1487    /// Tries to get a plain text field of a `multipart/form-data` body.
1488    ///
1489    /// A part that uploads a file is skipped, so a file field never silently
1490    /// decodes as text.
1491    ///
1492    /// # Arguments
1493    ///
1494    /// - `K` - The form field name, which requires the `AsRef<str>` bound.
1495    ///
1496    /// # Returns
1497    ///
1498    /// - `Option<BodyFormValue>` - The field value, or `None` when absent or a file.
1499    pub fn try_get_body_form_data_text<K>(&self, name: K) -> Option<BodyFormValue>
1500    where
1501        K: AsRef<str>,
1502    {
1503        let parts: MultipartFormDataParts = self.try_get_body_form_data()?;
1504        MultipartFormData::try_get_part_text(&parts, name)
1505    }
1506
1507    /// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
1508    ///
1509    /// # Returns
1510    ///
1511    /// - `bool` - Whether the upgrade type is h2c.
1512    #[inline(always)]
1513    pub fn is_h2c_upgrade_type(&self) -> bool {
1514        self.get_upgrade_type().is_h2c()
1515    }
1516
1517    /// Checks if the current upgrade type is TLS (any version).
1518    ///
1519    /// # Returns
1520    ///
1521    /// - `bool` - Whether the upgrade type is TLS.
1522    #[inline(always)]
1523    pub fn is_tls_upgrade_type(&self) -> bool {
1524        self.get_upgrade_type().is_tls()
1525    }
1526
1527    /// Checks whether the upgrade type is unknown.
1528    ///
1529    /// # Returns
1530    ///
1531    /// - `bool` - Whether the upgrade type is unknown.
1532    #[inline(always)]
1533    pub fn is_unknown_upgrade_type(&self) -> bool {
1534        self.get_upgrade_type().is_unknown()
1535    }
1536
1537    /// Determines if a keep-alive connection should be enabled for this request.
1538    ///
1539    /// This function checks the `Connection` header and the HTTP version to determine
1540    /// if keep-alive should be enabled. The logic is as follows:
1541    ///
1542    /// 1. If the `Connection` header exists:
1543    ///    - Returns `true` if the header value is "keep-alive" (case-insensitive).
1544    ///    - Returns `false` if the header value is "close" (case-insensitive).
1545    /// 2. If no `Connection` header is present:
1546    ///    - Returns `true` if the HTTP version is 1.1 or higher.
1547    ///    - Returns `false` otherwise.
1548    ///
1549    /// # Returns
1550    ///
1551    /// - `bool` - Whether keep-alive should be enabled.
1552    #[inline(always)]
1553    pub fn is_enable_keep_alive(&self) -> bool {
1554        if let Some(connection_value) = self
1555            .get_headers()
1556            .get(CONNECTION)
1557            .and_then(|values: &VecDeque<String>| values.back())
1558        {
1559            if connection_value.eq_ignore_ascii_case(KEEP_ALIVE) {
1560                return true;
1561            } else if connection_value.eq_ignore_ascii_case(CLOSE) {
1562                return self.is_ws_upgrade_type();
1563            }
1564        }
1565        self.get_version().is_http1_1_or_higher() || self.is_ws_upgrade_type()
1566    }
1567
1568    /// Determines if keep-alive should be disabled for this request.
1569    ///
1570    /// # Returns
1571    ///
1572    /// - `bool` - Whether keep-alive should be disabled.
1573    #[inline(always)]
1574    pub fn is_disable_keep_alive(&self) -> bool {
1575        !self.is_enable_keep_alive()
1576    }
1577}