http_type/response/impl.rs
1use super::*;
2
3/// Implements the `std::error::Error` trait for `ResponseError`.
4/// This allows `ResponseError` to be treated as a standard Rust error type.
5impl Error for ResponseError {}
6
7/// Converts an I/O error to a `ResponseError`.
8///
9/// Maps I/O errors to `Send` variant with the error message.
10impl From<io::Error> for ResponseError {
11 /// Converts an I/O error to a `ResponseError`.
12 ///
13 /// # Arguments
14 ///
15 /// - `io::Error` - The I/O error to convert.
16 ///
17 /// # Returns
18 ///
19 /// - `ResponseError` - The corresponding response error as `Send`.
20 #[inline(always)]
21 fn from(error: io::Error) -> Self {
22 ResponseError::Send(error.to_string())
23 }
24}
25
26/// Implements the `Display` trait for `ResponseError`.
27/// This allows `ResponseError` variants to be formatted into human-readable strings.
28impl Display for ResponseError {
29 /// Formats the `ResponseError` variant into a human-readable string.
30 ///
31 /// # Arguments
32 ///
33 /// - `&mut Formatter<'_>` - The formatter used for writing the formatted string.
34 ///
35 /// # Returns
36 ///
37 /// A `fmt::Result` indicating whether the formatting was successful.
38 #[inline(always)]
39 fn fmt(&self, data: &mut Formatter<'_>) -> fmt::Result {
40 match self {
41 Self::NotFoundStream => {
42 write!(data, "Not found stream")
43 }
44 Self::ConnectionClosed => {
45 write!(data, "Connection has been closed")
46 }
47 Self::Terminated => {
48 write!(data, "Current processing has been terminated")
49 }
50 Self::Send(error) => write!(data, "Send error{COLON_SPACE}{error}"),
51 Self::FlushError(error) => write!(data, "Flush error{COLON_SPACE}{error}"),
52 Self::Unknown => write!(data, "Unknown error"),
53 }
54 }
55}
56
57/// Provides a default value for `Response`.
58///
59/// Returns a new `Response` instance with all fields initialized to their default values.
60impl Default for Response {
61 /// Builds the default `Response` with all fields set to their defaults.
62 #[inline(always)]
63 fn default() -> Self {
64 Self {
65 version: HttpVersion::Http1_1,
66 status_code: HttpStatus::Ok.code(),
67 reason_phrase: OK.to_owned(),
68 headers: hash_map_xx_hash3_64(),
69 body: Vec::new(),
70 }
71 }
72}
73
74/// Inherent implementation of [`Response`].
75impl Response {
76 /// Sets the response reason phrase while reusing the existing string capacity.
77 ///
78 /// # Arguments
79 ///
80 /// - `impl AsRef<str>` - The reason phrase text.
81 ///
82 /// # Returns
83 ///
84 /// - `&mut Self` - A mutable reference to self for chaining.
85 #[inline(always)]
86 pub fn set_reason_phrase(&mut self, val: impl AsRef<str>) -> &mut Self {
87 let text: &str = val.as_ref();
88 if !Self::is_valid_header_value(text) {
89 return self;
90 }
91 self.reason_phrase.clear();
92 self.reason_phrase.push_str(text);
93 self
94 }
95
96 /// Sets the response body while reusing the existing byte vector capacity.
97 ///
98 /// # Arguments
99 ///
100 /// - `impl AsRef<[u8]>` - The response body bytes.
101 ///
102 /// # Returns
103 ///
104 /// - `&mut Self` - A mutable reference to self for chaining.
105 #[inline(always)]
106 pub fn set_body(&mut self, val: impl AsRef<[u8]>) -> &mut Self {
107 let bytes: &[u8] = val.as_ref();
108 self.body.clear();
109 self.body.extend_from_slice(bytes);
110 self
111 }
112
113 /// Pushes a header with a key and value as_ref the response bytes.
114 ///
115 /// # Arguments
116 ///
117 /// - `&mut Vec<u8>` - A mutable reference to the bytes where the header will be added.
118 /// - `&str` - The header key as a string slice (`&str`).
119 /// - `&str` - The header value as a string slice (`&str`).
120 #[inline(always)]
121 fn push_header(response_bytes: &mut Vec<u8>, key: &str, value: &str) {
122 response_bytes.extend_from_slice(key.as_bytes());
123 response_bytes.extend_from_slice(COLON.as_bytes());
124 response_bytes.extend_from_slice(value.as_bytes());
125 response_bytes.extend_from_slice(HTTP_BR.as_bytes());
126 }
127
128 /// Tries to retrieve the value of a response header by its key.
129 ///
130 /// # Arguments
131 ///
132 /// - `K` - The header's key, which must implement `AsRef<str>`.
133 ///
134 /// # Returns
135 ///
136 /// - `Option<ResponseHeadersValue>` - The optional header values.
137 #[inline(always)]
138 pub fn try_get_header<K>(&self, key: K) -> Option<ResponseHeadersValue>
139 where
140 K: AsRef<str>,
141 {
142 self.headers.get(key.as_ref()).cloned()
143 }
144
145 /// Retrieves the value of a response header by its key.
146 ///
147 /// # Arguments
148 ///
149 /// - `K` - The header's key, which must implement `AsRef<str>`.
150 ///
151 /// # Returns
152 ///
153 /// - `ResponseHeadersValue` - The optional header values.
154 ///
155 /// # Panics
156 ///
157 /// This function will panic if the header key is not found.
158 #[inline(always)]
159 pub fn get_header<K>(&self, key: K) -> ResponseHeadersValue
160 where
161 K: AsRef<str>,
162 {
163 self.try_get_header(key).unwrap()
164 }
165
166 /// Tries to retrieve the first value of a response header by its key.
167 ///
168 /// # Arguments
169 ///
170 /// - `K` - The header's key, which must implement `AsRef<str>`.
171 ///
172 /// # Returns
173 ///
174 /// - `Option<ResponseHeadersValueItem>` - The first header value if exists.
175 #[inline(always)]
176 pub fn try_get_header_front<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
177 where
178 K: AsRef<str>,
179 {
180 self.headers
181 .get(key.as_ref())
182 .and_then(|data: &VecDeque<String>| data.front().cloned())
183 }
184
185 /// Retrieves the first value of a response header by its key.
186 ///
187 /// # Arguments
188 ///
189 /// - `K` - The header's key, which must implement `AsRef<str>`.
190 ///
191 /// # Returns
192 ///
193 /// - `ResponseHeadersValueItem` - The first header value if exists.
194 ///
195 /// # Panics
196 ///
197 /// This function will panic if the header key is not found.
198 #[inline(always)]
199 pub fn get_header_front<K>(&self, key: K) -> ResponseHeadersValueItem
200 where
201 K: AsRef<str>,
202 {
203 self.try_get_header_front(key).unwrap()
204 }
205
206 /// Tries to retrieve the last value of a response header by its key.
207 ///
208 /// # Arguments
209 ///
210 /// - `K` - The header's key, which must implement `AsRef<str>`.
211 ///
212 /// # Returns
213 ///
214 /// - `Option<ResponseHeadersValueItem>` - The last header value if exists.
215 #[inline(always)]
216 pub fn try_get_header_back<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
217 where
218 K: AsRef<str>,
219 {
220 self.headers
221 .get(key.as_ref())
222 .and_then(|data: &VecDeque<String>| data.back().cloned())
223 }
224
225 /// Retrieves the last value of a response header by its key.
226 ///
227 /// # Arguments
228 ///
229 /// - `K` - The header's key, which must implement `AsRef<str>`.
230 ///
231 /// # Returns
232 ///
233 /// - `ResponseHeadersValueItem` - The last header value if exists.
234 ///
235 /// # Panics
236 ///
237 /// This function will panic if the header key is not found.
238 #[inline(always)]
239 pub fn get_header_back<K>(&self, key: K) -> ResponseHeadersValueItem
240 where
241 K: AsRef<str>,
242 {
243 self.try_get_header_back(key).unwrap()
244 }
245
246 /// Checks if a header exists in the response.
247 ///
248 /// # Arguments
249 ///
250 /// - `K` - The header key to check, which must implement `AsRef<str>`.
251 ///
252 /// # Returns
253 ///
254 /// - `bool` - Whether the header exists.
255 #[inline(always)]
256 pub fn has_header<K>(&self, key: K) -> bool
257 where
258 K: AsRef<str>,
259 {
260 self.get_headers().contains_key(key.as_ref())
261 }
262
263 /// Checks if a header contains a specific value.
264 ///
265 /// # Arguments
266 ///
267 /// - `K` - The header key to check, which must implement `AsRef<str>`.
268 /// - `V` - The value to search for, which must implement `AsRef<str>`.
269 ///
270 /// # Returns
271 ///
272 /// - `bool` - Whether the header contains the value.
273 #[inline(always)]
274 pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
275 where
276 K: AsRef<str>,
277 V: AsRef<str>,
278 {
279 if let Some(values) = self.get_headers().get(key.as_ref()) {
280 let target: &str = value.as_ref();
281 values.iter().any(|data: &String| data == target)
282 } else {
283 false
284 }
285 }
286
287 /// Gets the number of headers in the response.
288 ///
289 /// # Returns
290 ///
291 /// - `usize` - The count of unique header keys.
292 #[inline(always)]
293 pub fn get_headers_size(&self) -> usize {
294 self.headers.len()
295 }
296
297 /// Tries to get the number of values for a specific header key.
298 ///
299 /// # Arguments
300 ///
301 /// - `K` - The header key to count, which must implement `AsRef<str>`.
302 ///
303 /// # Returns
304 ///
305 /// - `Option<usize>` - The count of values for the header.
306 #[inline(always)]
307 pub fn try_get_header_size<K>(&self, key: K) -> Option<usize>
308 where
309 K: AsRef<str>,
310 {
311 self.headers
312 .get(key.as_ref())
313 .map(|data: &VecDeque<String>| data.len())
314 }
315
316 /// Gets the number of values for a specific header key.
317 ///
318 /// # Arguments
319 ///
320 /// - `K` - The header key to count, which must implement `AsRef<str>`.
321 ///
322 /// # Returns
323 ///
324 /// - `usize` - The count of values for the header.
325 ///
326 /// # Panics
327 ///
328 /// This function will panic if the header key is not found.
329 #[inline(always)]
330 pub fn get_header_size<K>(&self, key: K) -> usize
331 where
332 K: AsRef<str>,
333 {
334 self.try_get_header_size(key).unwrap()
335 }
336
337 /// Gets the total number of header values in the response.
338 ///
339 /// This counts all values across all headers, so a header with multiple values
340 /// will contribute more than one to the total count.
341 ///
342 /// # Returns
343 ///
344 /// - `usize` - The total count of all header values.
345 #[inline(always)]
346 pub fn get_headers_values_size(&self) -> usize {
347 self.headers
348 .values()
349 .map(|data: &VecDeque<String>| data.len())
350 .sum()
351 }
352
353 /// Retrieves the body content of the response as a UTF-8 encoded string.
354 ///
355 /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
356 /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
357 ///
358 /// # Returns
359 ///
360 /// - `String` - The body content as a string.
361 #[inline(always)]
362 pub fn get_body_string(&self) -> String {
363 String::from_utf8_lossy(self.get_body()).into_owned()
364 }
365
366 /// Deserializes the body content of the response as_ref a specified type `T`.
367 ///
368 /// This method first retrieves the body content as a byte slice using `self.get_body()`.
369 /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
370 ///
371 /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
372 ///
373 /// # Returns
374 ///
375 /// - `Result<T, serde_json::Error>` - The deserialization result.
376 pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
377 where
378 T: DeserializeOwned,
379 {
380 from_slice(self.get_body())
381 }
382
383 /// Deserializes the body content of the response as_ref a specified type `T`.
384 ///
385 /// This method first retrieves the body content as a byte slice using `self.get_body()`.
386 /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
387 ///
388 /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
389 ///
390 /// # Returns
391 ///
392 /// - `T` - The deserialized body content.
393 ///
394 /// # Panics
395 ///
396 /// This function will panic if the deserialization fails.
397 pub fn get_body_json<T>(&self) -> T
398 where
399 T: DeserializeOwned,
400 {
401 self.try_get_body_json().unwrap()
402 }
403
404 /// Validates whether a response header name is a non-empty RFC 9110 token.
405 ///
406 /// # Arguments
407 ///
408 /// - `&str` - The header key to inspect.
409 ///
410 /// # Returns
411 ///
412 /// - `bool` - `true` if every byte is a valid HTTP token character.
413 #[inline(always)]
414 fn is_valid_header_name(key: &str) -> bool {
415 !key.is_empty()
416 && key
417 .bytes()
418 .all(|byte: u8| HTTP_HEADER_TOKEN_TABLE[byte as usize])
419 }
420
421 /// Validates whether a response header value or reason phrase contains no control bytes.
422 ///
423 /// # Arguments
424 ///
425 /// - `&str` - The header value or reason phrase to inspect.
426 ///
427 /// # Returns
428 ///
429 /// - `bool` - `true` if every byte is allowed inside an HTTP field value.
430 #[inline(always)]
431 fn is_valid_header_value(value: &str) -> bool {
432 value
433 .bytes()
434 .all(|byte: u8| HTTP_HEADER_VALUE_VALID_TABLE[byte as usize])
435 }
436
437 /// Validates whether an HTTP version token contains no whitespace or control bytes.
438 ///
439 /// # Arguments
440 ///
441 /// - `&str` - The HTTP version text to inspect.
442 ///
443 /// # Returns
444 ///
445 /// - `bool` - `true` if the version token is safe to emit on the status line.
446 #[inline(always)]
447 fn is_valid_http_version(version: &str) -> bool {
448 !version.is_empty()
449 && version
450 .bytes()
451 .all(|byte: u8| byte > SPACE_U8 && byte < HTTP_HEADER_DELETE)
452 }
453
454 /// Looks up the last value of a response header case-insensitively.
455 ///
456 /// # Arguments
457 ///
458 /// - `&'a ResponseHeaders` - The header map to search.
459 /// - `&str` - The lowercase canonical header name.
460 ///
461 /// # Returns
462 ///
463 /// - `Option<&'a String>` - The last header value if present.
464 #[inline(always)]
465 fn find_header_back_ci<'a>(headers: &'a ResponseHeaders, target: &str) -> Option<&'a String> {
466 if let Some(values) = headers.get(target) {
467 return values.back();
468 }
469 headers
470 .iter()
471 .find(|(name, _): &(&String, &ResponseHeadersValue)| name.eq_ignore_ascii_case(target))
472 .and_then(|(_, values): (&String, &ResponseHeadersValue)| values.back())
473 }
474
475 /// Checks whether a response header exists case-insensitively with at least one value.
476 ///
477 /// # Arguments
478 ///
479 /// - `&ResponseHeaders` - The header map to search.
480 /// - `&str` - The lowercase canonical header name.
481 ///
482 /// # Returns
483 ///
484 /// - `bool` - `true` if any matching header has at least one value.
485 #[inline(always)]
486 fn has_header_ci(headers: &ResponseHeaders, target: &str) -> bool {
487 Self::find_header_back_ci(headers, target).is_some()
488 }
489
490 /// Determines whether the header should be skipped during setting.
491 ///
492 /// # Arguments
493 ///
494 /// - `&str` - The header key to inspect.
495 ///
496 /// # Returns
497 ///
498 /// - `bool` - `true` if the header is invalid or framing-controlled, `false` otherwise.
499 #[inline(always)]
500 fn should_skip_header(&self, key: &str) -> bool {
501 !Self::is_valid_header_name(key) || key.eq_ignore_ascii_case(CONTENT_LENGTH)
502 }
503
504 /// Sets a header in the response, replacing any existing values.
505 ///
506 /// This function replaces all existing values for a header with a single new value.
507 ///
508 /// # Arguments
509 ///
510 /// - `K` - The header key, which must implement `AsRef<str>`.
511 /// - `V` - The header value, which must implement `AsRef<String>`.
512 ///
513 /// # Returns
514 ///
515 /// - `&mut Self` - A mutable reference to self for chaining.
516 #[inline(always)]
517 fn set_header_without_check<K, V>(&mut self, key: K, value: V) -> &mut Self
518 where
519 K: AsRef<str>,
520 V: AsRef<str>,
521 {
522 let key: &str = key.as_ref();
523 let value: &str = value.as_ref();
524 if let Some(values) = self.get_mut_headers().get_mut(key) {
525 values.truncate(1);
526 if let Some(slot) = values.front_mut() {
527 slot.clear();
528 slot.push_str(value);
529 } else {
530 values.push_back(value.to_owned());
531 }
532 return self;
533 }
534 // A recycled entry carries the buffers of the name and of the value,
535 // so a response that sets the same headers over and over stops
536 // allocating for them.
537 let (mut name, mut values): (String, VecDeque<String>) =
538 take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
539 name.clear();
540 name.push_str(key);
541 // A recycled entry may carry the values of a header that was sent
542 // more than once. Those values belong to that header, so only the
543 // first one is kept and the rest are dropped.
544 while values.len() > 1 {
545 values.pop_back();
546 }
547 if values.is_empty() {
548 values.push_back(String::new());
549 }
550 if let Some(slot) = values.front_mut() {
551 slot.clear();
552 slot.push_str(value.as_ref());
553 }
554 self.get_mut_headers().insert(name, values);
555 self
556 }
557
558 /// Sets a header in the response, replacing any existing values.
559 ///
560 /// This function replaces all existing values for a header with a single new value.
561 ///
562 /// # Arguments
563 ///
564 /// - `K` - The header key, which must implement `AsRef<str>`.
565 /// - `V` - The header value, which must implement `AsRef<String>`.
566 ///
567 /// # Returns
568 ///
569 /// - `&mut Self` - A mutable reference to self for chaining.
570 #[inline(always)]
571 pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
572 where
573 K: AsRef<str>,
574 V: AsRef<str>,
575 {
576 let key: &str = key.as_ref();
577 let value: &str = value.as_ref();
578 if self.should_skip_header(key) || !Self::is_valid_header_value(value) {
579 return self;
580 }
581 self.set_header_without_check(key, value)
582 }
583
584 /// Adds a header to the response.
585 ///
586 /// This function appends a value to the response headers.
587 /// If the header already exists, the new value will be added to the existing values.
588 ///
589 /// # Arguments
590 ///
591 /// - `K` - The header key, which must implement `AsRef<str>`.
592 /// - `V` - The header value, which must implement `AsRef<String>`.
593 ///
594 /// # Returns
595 ///
596 /// - `&mut Self` - A mutable reference to self for chaining.
597 #[inline(always)]
598 pub fn add_header<K, V>(&mut self, key: K, value: V) -> &mut Self
599 where
600 K: AsRef<str>,
601 V: AsRef<str>,
602 {
603 let key_ref: &str = key.as_ref();
604 let value_ref: &str = value.as_ref();
605 if self.should_skip_header(key_ref) || !Self::is_valid_header_value(value_ref) {
606 return self;
607 }
608 if let Some(existing) = self.get_mut_headers().get_mut(key_ref) {
609 existing.push_back(value_ref.to_owned());
610 return self;
611 }
612 let (mut name, mut values): (String, VecDeque<String>) =
613 take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
614 name.clear();
615 name.push_str(key_ref);
616 while values.len() > 1 {
617 values.pop_back();
618 }
619 if let Some(slot) = values.front_mut() {
620 slot.clear();
621 slot.push_str(value_ref);
622 } else {
623 values.push_back(value_ref.to_owned());
624 }
625 self.get_mut_headers().insert(name, values);
626 self
627 }
628
629 /// Removes a header from the response.
630 ///
631 /// This function removes all values for the specified header key.
632 ///
633 /// # Arguments
634 ///
635 /// - `K` - The header key to remove, which must implement `AsRef<str>`.
636 ///
637 /// # Returns
638 ///
639 /// - `&mut Self` - A mutable reference to self for chaining.
640 #[inline(always)]
641 pub fn remove_header<K>(&mut self, key: K) -> &mut Self
642 where
643 K: AsRef<str>,
644 {
645 let _: bool = self.get_mut_headers().remove(key.as_ref()).is_some();
646 self
647 }
648
649 /// Removes a specific value from a header in the response.
650 ///
651 /// This function removes only the specified value from the header.
652 /// If the header has multiple values, only the matching value is removed.
653 /// If this was the last value for the header, the entire header is removed.
654 ///
655 /// # Arguments
656 ///
657 /// - `K` - The header key, which must implement `AsRef<str>`.
658 /// - `V` - The value to remove, which must implement `AsRef<String>`.
659 ///
660 /// # Returns
661 ///
662 /// - `&mut Self` - A mutable reference to self for chaining.
663 #[inline(always)]
664 pub fn remove_header_value<K, V>(&mut self, key: K, value: V) -> &mut Self
665 where
666 K: AsRef<str>,
667 V: AsRef<str>,
668 {
669 let key_ref: &str = key.as_ref();
670 let value_ref: &str = value.as_ref();
671 let should_remove: bool = if let Some(values) = self.get_mut_headers().get_mut(key_ref) {
672 values.retain(|data: &String| data != value_ref);
673 values.is_empty()
674 } else {
675 false
676 };
677 if should_remove {
678 self.get_mut_headers().remove(key_ref);
679 }
680 self
681 }
682
683 /// Clears all headers from the response.
684 ///
685 /// This function removes all headers, leaving the headers map empty.
686 ///
687 /// # Returns
688 ///
689 /// - `&mut Self` - A mutable reference to self for chaining.
690 #[inline(always)]
691 pub fn clear_headers(&mut self) -> &mut Self {
692 self.recycle_headers();
693 self
694 }
695
696 /// Resets the response to its default state while retaining allocated capacity.
697 ///
698 /// This keeps the header map and body allocations so persistent
699 /// (keep-alive) connections avoid repeated allocation per request.
700 ///
701 /// # Returns
702 ///
703 /// - `&mut Self` - A mutable reference to self for chaining.
704 pub fn reset(&mut self) -> &mut Self {
705 let http_status: HttpStatus = HttpStatus::default();
706 self.set_version(HttpVersion::Http1_1);
707 self.set_status_code(http_status.code());
708 let phrase: &'static str = HttpStatus::phrase_ref(http_status.code());
709 let stored: &mut ResponseReasonPhrase = self.get_mut_reason_phrase();
710 if stored.as_str() != phrase {
711 stored.clear();
712 stored.push_str(phrase);
713 }
714 self.recycle_headers();
715 self.get_mut_body().clear();
716 self
717 }
718
719 /// Hands the header entries to the pool and empties the header map.
720 ///
721 /// The map ends up empty, exactly as clearing it would, but the name and
722 /// the value buffers of every header survive in the pool. The next
723 /// response reuses them instead of allocating new ones.
724 ///
725 /// # Returns
726 ///
727 /// - `()` - The headers have been recycled.
728 fn recycle_headers(&mut self) {
729 let headers: &mut ResponseHeaders = self.get_mut_headers();
730 if headers.is_empty() {
731 return;
732 }
733 return_header_entries(headers.drain());
734 }
735
736 /// Tries to parse cookies from the `Set-Cookie` header.
737 ///
738 /// This method retrieves the last `Set-Cookie` header value and parses it
739 /// into a collection of key-value pairs representing the cookies.
740 ///
741 /// # Returns
742 ///
743 /// - `Option<Cookies>` - The parsed cookies if the `Set-Cookie` header exists, otherwise `None`.
744 #[inline(always)]
745 pub fn try_get_cookies(&self) -> Option<Cookies> {
746 let mut cookies: Cookies = hash_map_xx_hash3_64();
747 let mut found_header: bool = false;
748 for (name, values) in self.get_headers() {
749 if !name.eq_ignore_ascii_case(SET_COOKIE) {
750 continue;
751 }
752 for header_value in values {
753 found_header = true;
754 let parsed: CookieBuilder = CookieBuilder::parse(header_value);
755 if !parsed.get_name().is_empty() {
756 cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
757 }
758 }
759 }
760 found_header.then_some(cookies)
761 }
762
763 /// Parses cookies from the `Set-Cookie` headers.
764 ///
765 /// This method retrieves all `Set-Cookie` header values and parses each one
766 /// into a collection of key-value pairs representing the cookies.
767 ///
768 /// # Returns
769 ///
770 /// - `Cookies` - The parsed cookies.
771 ///
772 /// # Panics
773 ///
774 /// This function will panic if the `Set-Cookie` header is not found.
775 #[inline(always)]
776 pub fn get_cookies(&self) -> Cookies {
777 self.try_get_cookies().unwrap()
778 }
779
780 /// Tries to get a cookie value by its key from `Set-Cookie` headers.
781 ///
782 /// This method parses the cookies from all `Set-Cookie` headers,
783 /// then attempts to retrieve the value for the specified key.
784 ///
785 /// # Arguments
786 ///
787 /// - `K` - The cookie key, which implements `AsRef<str>`.
788 ///
789 /// # Returns
790 ///
791 /// - `Option<CookieValue>` - The cookie value if exists.
792 #[inline(always)]
793 pub fn try_get_cookie<K>(&self, key: K) -> Option<CookieValue>
794 where
795 K: AsRef<str>,
796 {
797 self.try_get_cookies()
798 .and_then(|cookies: Cookies| cookies.get(key.as_ref()).cloned())
799 }
800
801 /// Gets a cookie value by its key from `Set-Cookie` headers.
802 ///
803 /// This method parses the cookies from all `Set-Cookie` headers,
804 /// then retrieves the value for the specified key.
805 ///
806 /// # Arguments
807 ///
808 /// - `K` - The cookie key, which implements `AsRef<str>`.
809 ///
810 /// # Returns
811 ///
812 /// - `CookieValue` - The cookie value.
813 ///
814 /// # Panics
815 ///
816 /// This function will panic if the `Set-Cookie` header is not found
817 /// or the cookie key does not exist.
818 #[inline(always)]
819 pub fn get_cookie<K>(&self, key: K) -> CookieValue
820 where
821 K: AsRef<str>,
822 {
823 self.try_get_cookie(key).unwrap()
824 }
825
826 /// Removes framing fields before a header-only response is serialized.
827 #[cold]
828 fn clear_framing_headers(&mut self) {
829 self.get_mut_headers()
830 .retain(|name: &String, _: &mut ResponseHeadersValue| {
831 !name.eq_ignore_ascii_case(CONTENT_LENGTH)
832 && !name.eq_ignore_ascii_case(TRANSFER_ENCODING)
833 });
834 }
835
836 /// Builds the full HTTP response as a byte vector.
837 ///
838 /// This method constructs the complete HTTP response, including the status line,
839 /// headers, and body. It handles content encoding, content type, connection
840 /// management, and content length.
841 /// Informational, 204, 205, and 304 responses never serialize the body.
842 /// A 205 response declares a zero length; the other bodyless statuses
843 /// omit framing headers. For 304, the body cannot establish the length
844 /// of the selected representation.
845 ///
846 /// # Returns
847 ///
848 /// - `ResponseData` - The complete HTTP response bytes.
849 #[inline]
850 pub fn build(&mut self) -> ResponseData {
851 Self::build_wire::<true>(self)
852 }
853
854 /// Builds an HTTP response to `HEAD` without serializing or compressing its body.
855 ///
856 /// Set the body to the matching `GET` representation if its length is known.
857 /// An empty buffer, an event stream, or a body that would be compressed does
858 /// not establish that length, so the generated response omits it.
859 ///
860 /// # Returns
861 ///
862 /// - `ResponseData` - The status line and headers ending at the header terminator.
863 #[must_use]
864 pub fn build_head(&mut self) -> ResponseData {
865 Self::build_wire::<false>(self)
866 }
867
868 /// Serializes either a full response or the header-only response to `HEAD`.
869 ///
870 /// # Returns
871 ///
872 /// - `ResponseData` - The encoded HTTP response.
873 fn build_wire<const INCLUDE_BODY: bool>(&mut self) -> ResponseData {
874 let status_code: ResponseStatusCode = self.get_status_code();
875 if self.get_reason_phrase().is_empty()
876 || self.get_reason_phrase().as_str() == OK
877 || !Self::is_valid_header_value(self.get_reason_phrase())
878 {
879 // The phrase is written into the existing buffer rather than
880 // replaced, so a response that announces the same status over and
881 // over stops allocating for it.
882 let phrase: &'static str = HttpStatus::phrase_ref(status_code);
883 if self.get_reason_phrase().as_str() != phrase {
884 let stored: &mut ResponseReasonPhrase = self.get_mut_reason_phrase();
885 stored.clear();
886 stored.push_str(phrase);
887 }
888 }
889 if INCLUDE_BODY
890 && self.get_headers().is_empty()
891 && status_code >= HttpStatus::Ok.code()
892 && status_code != HttpStatus::NoContent.code()
893 && status_code != HttpStatus::ResetContent.code()
894 && status_code != HttpStatus::NotModified.code()
895 {
896 let raw_version: &str = self.get_version().as_str();
897 let version_str: &str = if Self::is_valid_http_version(raw_version) {
898 raw_version
899 } else {
900 HTTP_VERSION_1_1
901 };
902 let content_type: &str = default_content_type();
903 let body_len: usize = self.get_body().len();
904 let mut digits: [u8; B_20] = [0; B_20];
905 let rendered_len: &str = render_length(body_len, &mut digits);
906 let phrase_str: &str = self.get_reason_phrase().as_str();
907 let fast_prefix: Option<&[u8]> =
908 if status_code == HttpStatus::Ok.code() && phrase_str == OK {
909 match version_str {
910 HTTP_VERSION_1_1 => Some(FAST_HTTP11_200_CL_PREFIX),
911 HTTP_VERSION_2 => Some(FAST_HTTP2_200_CL_PREFIX),
912 HTTP_VERSION_3 => Some(FAST_HTTP3_200_CL_PREFIX),
913 _ => None,
914 }
915 } else {
916 None
917 };
918 let mut response_bytes: Vec<u8> = if let Some(prefix) = fast_prefix {
919 let total_size: usize = prefix.len()
920 + rendered_len.len()
921 + FAST_DEFAULT_HEADERS_SUFFIX.len()
922 + body_len;
923 let mut out: Vec<u8> = Vec::with_capacity(total_size);
924 out.extend_from_slice(prefix);
925 out.extend_from_slice(rendered_len.as_bytes());
926 out.extend_from_slice(FAST_DEFAULT_HEADERS_SUFFIX);
927 out
928 } else {
929 let mut code_digits: [u8; B_20] = [0; B_20];
930 let rendered_code: &str = render_length(status_code, &mut code_digits);
931 let total_size: usize = version_str.len()
932 + 1
933 + rendered_code.len()
934 + 1
935 + phrase_str.len()
936 + FAST_CL_PREFIX.len()
937 + rendered_len.len()
938 + FAST_DEFAULT_HEADERS_SUFFIX.len()
939 + body_len;
940 let mut out: Vec<u8> = Vec::with_capacity(total_size);
941 out.extend_from_slice(version_str.as_bytes());
942 out.push(b' ');
943 out.extend_from_slice(rendered_code.as_bytes());
944 out.push(b' ');
945 out.extend_from_slice(phrase_str.as_bytes());
946 out.extend_from_slice(FAST_CL_PREFIX);
947 out.extend_from_slice(rendered_len.as_bytes());
948 out.extend_from_slice(FAST_DEFAULT_HEADERS_SUFFIX);
949 out
950 };
951 response_bytes.extend_from_slice(self.get_body().as_slice());
952 self.populate_default_headers_batch(content_type, rendered_len);
953 return response_bytes;
954 }
955 if !Self::has_header_ci(self.get_headers(), CONNECTION) {
956 self.set_header_without_check(CONNECTION, KEEP_ALIVE);
957 }
958 let compressed_body: Option<ResponseBody>;
959 let body: &[u8] = match status_code {
960 100..=199 | 204 | 205 | 304 => {
961 self.clear_framing_headers();
962 if status_code == HttpStatus::ResetContent.code() {
963 self.set_header_without_check(CONTENT_LENGTH, ZERO_STR);
964 }
965 &[]
966 }
967 _ => {
968 let is_event_stream: bool = if let Some(value) =
969 Self::find_header_back_ci(self.get_headers(), CONTENT_TYPE)
970 {
971 value
972 .split(SEMICOLON)
973 .next()
974 .unwrap_or(EMPTY_STR)
975 .trim()
976 .eq_ignore_ascii_case(TEXT_EVENT_STREAM)
977 } else {
978 self.set_header_without_check(CONTENT_TYPE, default_content_type());
979 false
980 };
981 let has_transfer_encoding: bool =
982 Self::has_header_ci(self.get_headers(), TRANSFER_ENCODING);
983 let compress_type: Option<Compress> =
984 Self::find_header_back_ci(self.get_headers(), CONTENT_ENCODING)
985 .map(|value: &String| value.parse::<Compress>().unwrap_or_default());
986 if INCLUDE_BODY {
987 compressed_body = match compress_type {
988 Some(encoding) if !encoding.is_unknown() => Some(
989 encoding
990 .encode(self.get_body(), DEFAULT_BUFFER_SIZE)
991 .into_owned(),
992 ),
993 _ => None,
994 };
995 if has_transfer_encoding {
996 self.get_mut_headers().retain(
997 |name: &String, _: &mut ResponseHeadersValue| {
998 !name.eq_ignore_ascii_case(CONTENT_LENGTH)
999 },
1000 );
1001 } else if !is_event_stream {
1002 self.get_mut_headers().retain(
1003 |name: &String, _: &mut ResponseHeadersValue| {
1004 name == CONTENT_LENGTH || !name.eq_ignore_ascii_case(CONTENT_LENGTH)
1005 },
1006 );
1007 let body_len: usize = compressed_body
1008 .as_ref()
1009 .map_or_else(|| self.get_body().len(), Vec::len);
1010 self.set_wire_content_length(body_len);
1011 }
1012 compressed_body
1013 .as_deref()
1014 .unwrap_or_else(|| self.get_body().as_slice())
1015 } else {
1016 self.clear_framing_headers();
1017 let body_len: usize = self.get_body().len();
1018 if body_len != 0
1019 && !is_event_stream
1020 && !compress_type.is_some_and(|encoding: Compress| !encoding.is_unknown())
1021 {
1022 self.set_wire_content_length(body_len);
1023 }
1024 &[]
1025 }
1026 }
1027 };
1028 let mut head_size: usize = self.get_reason_phrase().len() + B_16 + HTTP_BR.len();
1029 head_size += self
1030 .get_headers()
1031 .iter()
1032 .map(|header_entry: (&String, &VecDeque<String>)| {
1033 let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
1034 header_values
1035 .iter()
1036 .map(|header_value: &String| {
1037 header_key.len() + COLON.len() + header_value.len() + HTTP_BR.len()
1038 })
1039 .sum::<usize>()
1040 })
1041 .sum::<usize>();
1042 let raw_version: &str = self.get_version().as_str();
1043 let version_str: &str = if Self::is_valid_http_version(raw_version) {
1044 raw_version
1045 } else {
1046 HTTP_VERSION_1_1
1047 };
1048 let mut response_bytes: Vec<u8> = Vec::with_capacity(head_size + body.len());
1049 response_bytes.extend_from_slice(version_str.as_bytes());
1050 response_bytes.push(b' ');
1051 let mut code: [u8; B_20] = [0; B_20];
1052 response_bytes.extend_from_slice(render_length(status_code, &mut code).as_bytes());
1053 response_bytes.push(b' ');
1054 response_bytes.extend_from_slice(self.get_reason_phrase().as_bytes());
1055 response_bytes.extend_from_slice(HTTP_BR.as_bytes());
1056 self.get_headers()
1057 .iter()
1058 .for_each(|header_entry: (&String, &VecDeque<String>)| {
1059 let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
1060 if !Self::is_valid_header_name(header_key) {
1061 return;
1062 }
1063 for header_value in header_values.iter() {
1064 if Self::is_valid_header_value(header_value) {
1065 Self::push_header(&mut response_bytes, header_key, header_value);
1066 }
1067 }
1068 });
1069 response_bytes.extend_from_slice(HTTP_BR.as_bytes());
1070 response_bytes.extend_from_slice(body);
1071 response_bytes
1072 }
1073
1074 /// Populates the three default wire headers using one thread-local pool lookup.
1075 ///
1076 /// # Arguments
1077 ///
1078 /// - `&str` - The default content type value.
1079 /// - `&str` - The decimal body length string.
1080 fn populate_default_headers_batch(&mut self, content_type: &str, rendered_len: &str) {
1081 let headers: &mut ResponseHeaders = self.get_mut_headers();
1082 let pairs: [(&str, &str); 3] = [
1083 (CONNECTION, KEEP_ALIVE),
1084 (CONTENT_TYPE, content_type),
1085 (CONTENT_LENGTH, rendered_len),
1086 ];
1087 HEADER_ENTRY_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
1088 let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
1089 for (key, value) in pairs {
1090 let (mut name, mut values): (String, VecDeque<String>) = pool
1091 .pop()
1092 .unwrap_or_else(|| (String::new(), VecDeque::new()));
1093 name.clear();
1094 name.push_str(key);
1095 while values.len() > 1 {
1096 values.pop_back();
1097 }
1098 if let Some(slot) = values.front_mut() {
1099 slot.clear();
1100 slot.push_str(value);
1101 } else {
1102 values.push_back(value.to_owned());
1103 }
1104 headers.insert(name, values);
1105 }
1106 });
1107 }
1108
1109 /// Sets the generated content length using a stack buffer.
1110 ///
1111 /// # Arguments
1112 ///
1113 /// - `usize` - The selected representation's length in bytes.
1114 #[inline(always)]
1115 fn set_wire_content_length(&mut self, body_len: usize) {
1116 let mut digits: [u8; B_20] = [0; B_20];
1117 let rendered: &str = render_length(body_len, &mut digits);
1118 self.set_header_without_check(CONTENT_LENGTH, rendered);
1119 }
1120}