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