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 self.reason_phrase.clear();
89 self.reason_phrase.push_str(text);
90 self
91 }
92
93 /// Sets the response body while reusing the existing byte vector capacity.
94 ///
95 /// # Arguments
96 ///
97 /// - `impl AsRef<[u8]>` - The response body bytes.
98 ///
99 /// # Returns
100 ///
101 /// - `&mut Self` - A mutable reference to self for chaining.
102 #[inline(always)]
103 pub fn set_body(&mut self, val: impl AsRef<[u8]>) -> &mut Self {
104 let bytes: &[u8] = val.as_ref();
105 self.body.clear();
106 self.body.extend_from_slice(bytes);
107 self
108 }
109
110 /// Pushes a header with a key and value as_ref the response bytes.
111 ///
112 /// # Arguments
113 ///
114 /// - `&mut Vec<u8>` - A mutable reference to the bytes where the header will be added.
115 /// - `&str` - The header key as a string slice (`&str`).
116 /// - `&str` - The header value as a string slice (`&str`).
117 #[inline(always)]
118 fn push_header(response_bytes: &mut Vec<u8>, key: &str, value: &str) {
119 response_bytes.extend_from_slice(key.as_bytes());
120 response_bytes.extend_from_slice(COLON.as_bytes());
121 response_bytes.extend_from_slice(value.as_bytes());
122 response_bytes.extend_from_slice(HTTP_BR.as_bytes());
123 }
124
125 /// Tries to retrieve the value of a response header by its key.
126 ///
127 /// # Arguments
128 ///
129 /// - `K` - The header's key, which must implement `AsRef<str>`.
130 ///
131 /// # Returns
132 ///
133 /// - `Option<ResponseHeadersValue>` - The optional header values.
134 #[inline(always)]
135 pub fn try_get_header<K>(&self, key: K) -> Option<ResponseHeadersValue>
136 where
137 K: AsRef<str>,
138 {
139 self.headers.get(key.as_ref()).cloned()
140 }
141
142 /// Retrieves the value of a response header by its key.
143 ///
144 /// # Arguments
145 ///
146 /// - `K` - The header's key, which must implement `AsRef<str>`.
147 ///
148 /// # Returns
149 ///
150 /// - `ResponseHeadersValue` - The optional header values.
151 ///
152 /// # Panics
153 ///
154 /// This function will panic if the header key is not found.
155 #[inline(always)]
156 pub fn get_header<K>(&self, key: K) -> ResponseHeadersValue
157 where
158 K: AsRef<str>,
159 {
160 self.try_get_header(key).unwrap()
161 }
162
163 /// Tries to retrieve the first value of a response header by its key.
164 ///
165 /// # Arguments
166 ///
167 /// - `K` - The header's key, which must implement `AsRef<str>`.
168 ///
169 /// # Returns
170 ///
171 /// - `Option<ResponseHeadersValueItem>` - The first header value if exists.
172 #[inline(always)]
173 pub fn try_get_header_front<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
174 where
175 K: AsRef<str>,
176 {
177 self.headers
178 .get(key.as_ref())
179 .and_then(|data: &VecDeque<String>| data.front().cloned())
180 }
181
182 /// Retrieves the first value of a response header by its key.
183 ///
184 /// # Arguments
185 ///
186 /// - `K` - The header's key, which must implement `AsRef<str>`.
187 ///
188 /// # Returns
189 ///
190 /// - `ResponseHeadersValueItem` - The first header value if exists.
191 ///
192 /// # Panics
193 ///
194 /// This function will panic if the header key is not found.
195 #[inline(always)]
196 pub fn get_header_front<K>(&self, key: K) -> ResponseHeadersValueItem
197 where
198 K: AsRef<str>,
199 {
200 self.try_get_header_front(key).unwrap()
201 }
202
203 /// Tries to retrieve the last value of a response header by its key.
204 ///
205 /// # Arguments
206 ///
207 /// - `K` - The header's key, which must implement `AsRef<str>`.
208 ///
209 /// # Returns
210 ///
211 /// - `Option<ResponseHeadersValueItem>` - The last header value if exists.
212 #[inline(always)]
213 pub fn try_get_header_back<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
214 where
215 K: AsRef<str>,
216 {
217 self.headers
218 .get(key.as_ref())
219 .and_then(|data: &VecDeque<String>| data.back().cloned())
220 }
221
222 /// Retrieves the last value of a response header by its key.
223 ///
224 /// # Arguments
225 ///
226 /// - `K` - The header's key, which must implement `AsRef<str>`.
227 ///
228 /// # Returns
229 ///
230 /// - `ResponseHeadersValueItem` - The last header value if exists.
231 ///
232 /// # Panics
233 ///
234 /// This function will panic if the header key is not found.
235 #[inline(always)]
236 pub fn get_header_back<K>(&self, key: K) -> ResponseHeadersValueItem
237 where
238 K: AsRef<str>,
239 {
240 self.try_get_header_back(key).unwrap()
241 }
242
243 /// Checks if a header exists in the response.
244 ///
245 /// # Arguments
246 ///
247 /// - `K` - The header key to check, which must implement `AsRef<str>`.
248 ///
249 /// # Returns
250 ///
251 /// - `bool` - Whether the header exists.
252 #[inline(always)]
253 pub fn has_header<K>(&self, key: K) -> bool
254 where
255 K: AsRef<str>,
256 {
257 self.get_headers().contains_key(key.as_ref())
258 }
259
260 /// Checks if a header contains a specific value.
261 ///
262 /// # Arguments
263 ///
264 /// - `K` - The header key to check, which must implement `AsRef<str>`.
265 /// - `V` - The value to search for, which must implement `AsRef<str>`.
266 ///
267 /// # Returns
268 ///
269 /// - `bool` - Whether the header contains the value.
270 #[inline(always)]
271 pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
272 where
273 K: AsRef<str>,
274 V: AsRef<str>,
275 {
276 if let Some(values) = self.get_headers().get(key.as_ref()) {
277 values.contains(&value.as_ref().to_owned())
278 } else {
279 false
280 }
281 }
282
283 /// Gets the number of headers in the response.
284 ///
285 /// # Returns
286 ///
287 /// - `usize` - The count of unique header keys.
288 #[inline(always)]
289 pub fn get_headers_size(&self) -> usize {
290 self.headers.len()
291 }
292
293 /// Tries to get the number of values for a specific header key.
294 ///
295 /// # Arguments
296 ///
297 /// - `K` - The header key to count, which must implement `AsRef<str>`.
298 ///
299 /// # Returns
300 ///
301 /// - `Option<usize>` - The count of values for the header.
302 #[inline(always)]
303 pub fn try_get_header_size<K>(&self, key: K) -> Option<usize>
304 where
305 K: AsRef<str>,
306 {
307 self.headers
308 .get(key.as_ref())
309 .map(|data: &VecDeque<String>| data.len())
310 }
311
312 /// Gets the number of values for a specific header key.
313 ///
314 /// # Arguments
315 ///
316 /// - `K` - The header key to count, which must implement `AsRef<str>`.
317 ///
318 /// # Returns
319 ///
320 /// - `usize` - The count of values for the header.
321 ///
322 /// # Panics
323 ///
324 /// This function will panic if the header key is not found.
325 #[inline(always)]
326 pub fn get_header_size<K>(&self, key: K) -> usize
327 where
328 K: AsRef<str>,
329 {
330 self.try_get_header_size(key).unwrap()
331 }
332
333 /// Gets the total number of header values in the response.
334 ///
335 /// This counts all values across all headers, so a header with multiple values
336 /// will contribute more than one to the total count.
337 ///
338 /// # Returns
339 ///
340 /// - `usize` - The total count of all header values.
341 #[inline(always)]
342 pub fn get_headers_values_size(&self) -> usize {
343 self.headers
344 .values()
345 .map(|data: &VecDeque<String>| data.len())
346 .sum()
347 }
348
349 /// Retrieves the body content of the response as a UTF-8 encoded string.
350 ///
351 /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
352 /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
353 ///
354 /// # Returns
355 ///
356 /// - `String` - The body content as a string.
357 #[inline(always)]
358 pub fn get_body_string(&self) -> String {
359 String::from_utf8_lossy(self.get_body()).into_owned()
360 }
361
362 /// Deserializes the body content of the response as_ref a specified type `T`.
363 ///
364 /// This method first retrieves the body content as a byte slice using `self.get_body()`.
365 /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
366 ///
367 /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
368 ///
369 /// # Returns
370 ///
371 /// - `Result<T, serde_json::Error>` - The deserialization result.
372 pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
373 where
374 T: DeserializeOwned,
375 {
376 from_slice(self.get_body())
377 }
378
379 /// Deserializes the body content of the response as_ref a specified type `T`.
380 ///
381 /// This method first retrieves the body content as a byte slice using `self.get_body()`.
382 /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
383 ///
384 /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
385 ///
386 /// # Returns
387 ///
388 /// - `T` - The deserialized body content.
389 ///
390 /// # Panics
391 ///
392 /// This function will panic if the deserialization fails.
393 pub fn get_body_json<T>(&self) -> T
394 where
395 T: DeserializeOwned,
396 {
397 self.try_get_body_json().unwrap()
398 }
399
400 /// Determines whether the header should be skipped during setting.
401 ///
402 /// # Arguments
403 ///
404 /// - `&str` - The header key to inspect.
405 ///
406 /// # Returns
407 ///
408 /// - `bool` - `true` if the header is empty or not allowed, `false` if the header can be set.
409 #[inline(always)]
410 fn should_skip_header(&self, key: &str) -> bool {
411 key.trim().is_empty() || key == CONTENT_LENGTH
412 }
413
414 /// Sets a header in the response, replacing any existing values.
415 ///
416 /// This function replaces all existing values for a header with a single new value.
417 ///
418 /// # Arguments
419 ///
420 /// - `K` - The header key, which must implement `AsRef<str>`.
421 /// - `V` - The header value, which must implement `AsRef<String>`.
422 ///
423 /// # Returns
424 ///
425 /// - `&mut Self` - A mutable reference to self for chaining.
426 #[inline(always)]
427 fn set_header_without_check<K, V>(&mut self, key: K, value: V) -> &mut Self
428 where
429 K: AsRef<str>,
430 V: AsRef<str>,
431 {
432 let key: &str = key.as_ref();
433 let value: &str = value.as_ref();
434 if let Some(values) = self.get_mut_headers().get_mut(key) {
435 values.truncate(1);
436 if let Some(slot) = values.front_mut() {
437 slot.clear();
438 slot.push_str(value);
439 } else {
440 values.push_back(value.to_owned());
441 }
442 return self;
443 }
444 // A recycled entry carries the buffers of the name and of the value,
445 // so a response that sets the same headers over and over stops
446 // allocating for them.
447 let (mut name, mut values): (String, VecDeque<String>) =
448 take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
449 name.clear();
450 name.push_str(key);
451 // A recycled entry may carry the values of a header that was sent
452 // more than once. Those values belong to that header, so only the
453 // first one is kept and the rest are dropped.
454 while values.len() > 1 {
455 values.pop_back();
456 }
457 if values.is_empty() {
458 values.push_back(String::new());
459 }
460 if let Some(slot) = values.front_mut() {
461 slot.clear();
462 slot.push_str(value.as_ref());
463 }
464 self.get_mut_headers().insert(name, values);
465 self
466 }
467
468 /// Sets a header in the response, replacing any existing values.
469 ///
470 /// This function replaces all existing values for a header with a single new value.
471 ///
472 /// # Arguments
473 ///
474 /// - `K` - The header key, which must implement `AsRef<str>`.
475 /// - `V` - The header value, which must implement `AsRef<String>`.
476 ///
477 /// # Returns
478 ///
479 /// - `&mut Self` - A mutable reference to self for chaining.
480 #[inline(always)]
481 pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
482 where
483 K: AsRef<str>,
484 V: AsRef<str>,
485 {
486 let key: &str = key.as_ref();
487 if self.should_skip_header(key) {
488 return self;
489 }
490 self.set_header_without_check(key, value)
491 }
492
493 /// Adds a header to the response.
494 ///
495 /// This function appends a value to the response headers.
496 /// If the header already exists, the new value will be added to the existing values.
497 ///
498 /// # Arguments
499 ///
500 /// - `K` - The header key, which must implement `AsRef<str>`.
501 /// - `V` - The header value, which must implement `AsRef<String>`.
502 ///
503 /// # Returns
504 ///
505 /// - `&mut Self` - A mutable reference to self for chaining.
506 #[inline(always)]
507 pub fn add_header<K, V>(&mut self, key: K, value: V) -> &mut Self
508 where
509 K: AsRef<str>,
510 V: AsRef<str>,
511 {
512 let key: ResponseHeadersKey = key.as_ref().to_owned();
513 if self.should_skip_header(&key) {
514 return self;
515 }
516 self.get_mut_headers()
517 .entry(key)
518 .or_default()
519 .push_back(value.as_ref().to_owned());
520 self
521 }
522
523 /// Removes a header from the response.
524 ///
525 /// This function removes all values for the specified header key.
526 ///
527 /// # Arguments
528 ///
529 /// - `K` - The header key to remove, which must implement `AsRef<str>`.
530 ///
531 /// # Returns
532 ///
533 /// - `&mut Self` - A mutable reference to self for chaining.
534 #[inline(always)]
535 pub fn remove_header<K>(&mut self, key: K) -> &mut Self
536 where
537 K: AsRef<str>,
538 {
539 let _: bool = self.get_mut_headers().remove(key.as_ref()).is_some();
540 self
541 }
542
543 /// Removes a specific value from a header in the response.
544 ///
545 /// This function removes only the specified value from the header.
546 /// If the header has multiple values, only the matching value is removed.
547 /// If this was the last value for the header, the entire header is removed.
548 ///
549 /// # Arguments
550 ///
551 /// - `K` - The header key, which must implement `AsRef<str>`.
552 /// - `V` - The value to remove, which must implement `AsRef<String>`.
553 ///
554 /// # Returns
555 ///
556 /// - `&mut Self` - A mutable reference to self for chaining.
557 #[inline(always)]
558 pub fn remove_header_value<K, V>(&mut self, key: K, value: V) -> &mut Self
559 where
560 K: AsRef<str>,
561 V: AsRef<str>,
562 {
563 let key: ResponseHeadersKey = key.as_ref().to_owned();
564 if let Some(values) = self.get_mut_headers().get_mut(&key) {
565 values.retain(|data: &String| data != &value.as_ref().to_owned());
566 if values.is_empty() {
567 self.get_mut_headers().remove(&key);
568 }
569 }
570 self
571 }
572
573 /// Clears all headers from the response.
574 ///
575 /// This function removes all headers, leaving the headers map empty.
576 ///
577 /// # Returns
578 ///
579 /// - `&mut Self` - A mutable reference to self for chaining.
580 #[inline(always)]
581 pub fn clear_headers(&mut self) -> &mut Self {
582 self.get_mut_headers().clear();
583 self
584 }
585
586 /// Resets the response to its default state while retaining allocated capacity.
587 ///
588 /// This keeps the header map and body allocations so persistent
589 /// (keep-alive) connections avoid repeated allocation per request.
590 ///
591 /// # Returns
592 ///
593 /// - `&mut Self` - A mutable reference to self for chaining.
594 pub fn reset(&mut self) -> &mut Self {
595 let http_status: HttpStatus = HttpStatus::default();
596 self.set_status_code(http_status.code());
597 // The phrase is written into the existing buffer rather than
598 // replaced, so a response that is reset over and over stops
599 // allocating for it.
600 let stored: &mut ResponseReasonPhrase = self.get_mut_reason_phrase();
601 stored.clear();
602 stored.push_str(HttpStatus::phrase_ref(http_status.code()));
603 self.recycle_headers();
604 self.get_mut_body().clear();
605 self
606 }
607
608 /// Hands the header entries to the pool and empties the header map.
609 ///
610 /// The map ends up empty, exactly as clearing it would, but the name and
611 /// the value buffers of every header survive in the pool. The next
612 /// response reuses them instead of allocating new ones.
613 ///
614 /// # Returns
615 ///
616 /// - `()` - The headers have been recycled.
617 fn recycle_headers(&mut self) {
618 let headers: &mut ResponseHeaders = self.get_mut_headers();
619 if headers.is_empty() {
620 return;
621 }
622 return_header_entries(headers.drain());
623 }
624
625 /// Tries to parse cookies from the `Set-Cookie` header.
626 ///
627 /// This method retrieves the last `Set-Cookie` header value and parses it
628 /// into a collection of key-value pairs representing the cookies.
629 ///
630 /// # Returns
631 ///
632 /// - `Option<Cookies>` - The parsed cookies if the `Set-Cookie` header exists, otherwise `None`.
633 #[inline(always)]
634 pub fn try_get_cookies(&self) -> Option<Cookies> {
635 self.try_get_header_back(SET_COOKIE)
636 .map(|cookie_header: String| Cookie::parse(cookie_header))
637 }
638
639 /// Parses cookies from the `Set-Cookie` headers.
640 ///
641 /// This method retrieves all `Set-Cookie` header values and parses each one
642 /// into a collection of key-value pairs representing the cookies.
643 ///
644 /// # Returns
645 ///
646 /// - `Cookies` - The parsed cookies.
647 ///
648 /// # Panics
649 ///
650 /// This function will panic if the `Set-Cookie` header is not found.
651 #[inline(always)]
652 pub fn get_cookies(&self) -> Cookies {
653 self.try_get_cookies().unwrap()
654 }
655
656 /// Tries to get a cookie value by its key from `Set-Cookie` headers.
657 ///
658 /// This method parses the cookies from all `Set-Cookie` headers,
659 /// then attempts to retrieve the value for the specified key.
660 ///
661 /// # Arguments
662 ///
663 /// - `K` - The cookie key, which implements `AsRef<str>`.
664 ///
665 /// # Returns
666 ///
667 /// - `Option<CookieValue>` - The cookie value if exists.
668 #[inline(always)]
669 pub fn try_get_cookie<K>(&self, key: K) -> Option<CookieValue>
670 where
671 K: AsRef<str>,
672 {
673 self.try_get_cookies()
674 .and_then(|cookies: Cookies| cookies.get(key.as_ref()).cloned())
675 }
676
677 /// Gets a cookie value by its key from `Set-Cookie` headers.
678 ///
679 /// This method parses the cookies from all `Set-Cookie` headers,
680 /// then retrieves the value for the specified key.
681 ///
682 /// # Arguments
683 ///
684 /// - `K` - The cookie key, which implements `AsRef<str>`.
685 ///
686 /// # Returns
687 ///
688 /// - `CookieValue` - The cookie value.
689 ///
690 /// # Panics
691 ///
692 /// This function will panic if the `Set-Cookie` header is not found
693 /// or the cookie key does not exist.
694 #[inline(always)]
695 pub fn get_cookie<K>(&self, key: K) -> CookieValue
696 where
697 K: AsRef<str>,
698 {
699 self.try_get_cookie(key).unwrap()
700 }
701
702 /// Removes framing fields before a header-only response is serialized.
703 #[cold]
704 fn clear_framing_headers(&mut self) {
705 self.get_mut_headers()
706 .retain(|name: &String, _: &mut ResponseHeadersValue| {
707 !name.eq_ignore_ascii_case(CONTENT_LENGTH)
708 && !name.eq_ignore_ascii_case(TRANSFER_ENCODING)
709 });
710 }
711
712 /// Builds the full HTTP response as a byte vector.
713 ///
714 /// This method constructs the complete HTTP response, including the status line,
715 /// headers, and body. It handles content encoding, content type, connection
716 /// management, and content length.
717 /// Informational, 204, 205, and 304 responses never serialize the body.
718 /// A 205 response declares a zero length; the other bodyless statuses
719 /// omit framing headers. For 304, the body cannot establish the length
720 /// of the selected representation.
721 ///
722 /// # Returns
723 ///
724 /// - `ResponseData` - The complete HTTP response bytes.
725 #[inline]
726 pub fn build(&mut self) -> ResponseData {
727 Self::build_wire::<true>(self)
728 }
729
730 /// Builds an HTTP response to `HEAD` without serializing or compressing its body.
731 ///
732 /// Set the body to the matching `GET` representation if its length is known.
733 /// An empty buffer, an event stream, or a body that would be compressed does
734 /// not establish that length, so the generated response omits it.
735 ///
736 /// # Returns
737 ///
738 /// - `ResponseData` - The status line and headers ending at the header terminator.
739 #[must_use]
740 pub fn build_head(&mut self) -> ResponseData {
741 Self::build_wire::<false>(self)
742 }
743
744 /// Serializes either a full response or the header-only response to `HEAD`.
745 ///
746 /// # Returns
747 ///
748 /// - `ResponseData` - The encoded HTTP response.
749 fn build_wire<const INCLUDE_BODY: bool>(&mut self) -> ResponseData {
750 let status_code: ResponseStatusCode = self.get_status_code();
751 if self.get_reason_phrase().is_empty() || self.get_reason_phrase().as_str() == OK {
752 // The phrase is written into the existing buffer rather than
753 // replaced, so a response that announces the same status over and
754 // over stops allocating for it.
755 let phrase: &'static str = HttpStatus::phrase_ref(status_code);
756 if self.get_reason_phrase().as_str() != phrase {
757 let stored: &mut ResponseReasonPhrase = self.get_mut_reason_phrase();
758 stored.clear();
759 stored.push_str(phrase);
760 }
761 }
762 if INCLUDE_BODY
763 && self.get_headers().is_empty()
764 && status_code >= HttpStatus::Ok.code()
765 && status_code != HttpStatus::NoContent.code()
766 && status_code != HttpStatus::ResetContent.code()
767 && status_code != HttpStatus::NotModified.code()
768 {
769 let content_type: &str = default_content_type();
770 let body_len: usize = self.get_body().len();
771 let mut digits: [u8; B_20] = [0; B_20];
772 let rendered_len: &str = render_length(body_len, &mut digits);
773 let mut code_digits: [u8; B_20] = [0; B_20];
774 let rendered_code: &str = render_length(status_code, &mut code_digits);
775 let version_str: &str = self.get_version().as_str();
776 let phrase_str: &str = self.get_reason_phrase().as_str();
777 let total_size: usize = version_str.len()
778 + 1
779 + rendered_code.len()
780 + 1
781 + phrase_str.len()
782 + HTTP_BR.len()
783 + CONNECTION.len()
784 + COLON.len()
785 + KEEP_ALIVE.len()
786 + HTTP_BR.len()
787 + CONTENT_TYPE.len()
788 + COLON.len()
789 + content_type.len()
790 + HTTP_BR.len()
791 + CONTENT_LENGTH.len()
792 + COLON.len()
793 + rendered_len.len()
794 + HTTP_BR.len()
795 + HTTP_BR.len()
796 + body_len;
797 let mut response_bytes: Vec<u8> = Vec::with_capacity(total_size);
798 response_bytes.extend_from_slice(version_str.as_bytes());
799 response_bytes.push(b' ');
800 response_bytes.extend_from_slice(rendered_code.as_bytes());
801 response_bytes.push(b' ');
802 response_bytes.extend_from_slice(phrase_str.as_bytes());
803 response_bytes.extend_from_slice(HTTP_BR.as_bytes());
804 Self::push_header(&mut response_bytes, CONTENT_LENGTH, rendered_len);
805 Self::push_header(&mut response_bytes, CONNECTION, KEEP_ALIVE);
806 Self::push_header(&mut response_bytes, CONTENT_TYPE, content_type);
807 response_bytes.extend_from_slice(HTTP_BR.as_bytes());
808 response_bytes.extend_from_slice(self.get_body().as_slice());
809 self.populate_default_headers_batch(content_type, rendered_len);
810 return response_bytes;
811 }
812 if self
813 .get_headers()
814 .get(CONNECTION)
815 .and_then(|values: &VecDeque<String>| values.back())
816 .is_none()
817 {
818 self.set_header_without_check(CONNECTION, KEEP_ALIVE);
819 }
820 let compressed_body: Option<ResponseBody>;
821 let body: &[u8] = match status_code {
822 100..=199 | 204 | 205 | 304 => {
823 self.clear_framing_headers();
824 if status_code == HttpStatus::ResetContent.code() {
825 self.set_header_without_check(CONTENT_LENGTH, ZERO_STR);
826 }
827 &[]
828 }
829 _ => {
830 let content_type: Option<&String> = self
831 .get_headers()
832 .get(CONTENT_TYPE)
833 .and_then(|values: &ResponseHeadersValue| values.back());
834 let is_event_stream: bool = if let Some(value) = content_type {
835 value.eq_ignore_ascii_case(TEXT_EVENT_STREAM)
836 } else {
837 self.set_header_without_check(CONTENT_TYPE, default_content_type());
838 false
839 };
840 let compress_type: Option<Compress> = self
841 .get_headers()
842 .get(CONTENT_ENCODING)
843 .and_then(|values: &ResponseHeadersValue| values.back())
844 .map(|value: &String| value.parse::<Compress>().unwrap_or_default());
845 if INCLUDE_BODY {
846 compressed_body = match compress_type {
847 Some(encoding) if !encoding.is_unknown() => Some(
848 encoding
849 .encode(self.get_body(), DEFAULT_BUFFER_SIZE)
850 .into_owned(),
851 ),
852 _ => None,
853 };
854 if !is_event_stream {
855 let body_len: usize = compressed_body
856 .as_ref()
857 .map_or_else(|| self.get_body().len(), Vec::len);
858 self.set_wire_content_length(body_len);
859 }
860 compressed_body
861 .as_deref()
862 .unwrap_or_else(|| self.get_body().as_slice())
863 } else {
864 self.clear_framing_headers();
865 let body_len: usize = self.get_body().len();
866 if body_len != 0
867 && !is_event_stream
868 && !compress_type.is_some_and(|encoding: Compress| !encoding.is_unknown())
869 {
870 self.set_wire_content_length(body_len);
871 }
872 &[]
873 }
874 }
875 };
876 let mut head_size: usize = self.get_reason_phrase().len() + B_16 + HTTP_BR.len();
877 head_size += self
878 .get_headers()
879 .iter()
880 .map(|header_entry: (&String, &VecDeque<String>)| {
881 let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
882 header_values
883 .iter()
884 .map(|header_value: &String| {
885 header_key.len() + COLON.len() + header_value.len() + HTTP_BR.len()
886 })
887 .sum::<usize>()
888 })
889 .sum::<usize>();
890 let mut response_bytes: Vec<u8> = Vec::with_capacity(head_size + body.len());
891 response_bytes.extend_from_slice(self.get_version().as_str().as_bytes());
892 response_bytes.push(b' ');
893 let mut code: [u8; B_20] = [0; B_20];
894 response_bytes.extend_from_slice(render_length(status_code, &mut code).as_bytes());
895 response_bytes.push(b' ');
896 response_bytes.extend_from_slice(self.get_reason_phrase().as_bytes());
897 response_bytes.extend_from_slice(HTTP_BR.as_bytes());
898 self.get_headers()
899 .iter()
900 .for_each(|header_entry: (&String, &VecDeque<String>)| {
901 let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
902 for header_value in header_values.iter() {
903 Self::push_header(&mut response_bytes, header_key, header_value);
904 }
905 });
906 response_bytes.extend_from_slice(HTTP_BR.as_bytes());
907 response_bytes.extend_from_slice(body);
908 response_bytes
909 }
910
911 /// Populates the three default wire headers using one thread-local pool lookup.
912 ///
913 /// # Arguments
914 ///
915 /// - `&str` - The default content type value.
916 /// - `&str` - The decimal body length string.
917 fn populate_default_headers_batch(&mut self, content_type: &str, rendered_len: &str) {
918 let headers: &mut ResponseHeaders = self.get_mut_headers();
919 let pairs: [(&str, &str); 3] = [
920 (CONNECTION, KEEP_ALIVE),
921 (CONTENT_TYPE, content_type),
922 (CONTENT_LENGTH, rendered_len),
923 ];
924 HEADER_ENTRY_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
925 let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
926 for (key, value) in pairs {
927 let (mut name, mut values): (String, VecDeque<String>) = pool
928 .pop()
929 .unwrap_or_else(|| (String::new(), VecDeque::new()));
930 name.clear();
931 name.push_str(key);
932 while values.len() > 1 {
933 values.pop_back();
934 }
935 if let Some(slot) = values.front_mut() {
936 slot.clear();
937 slot.push_str(value);
938 } else {
939 values.push_back(value.to_owned());
940 }
941 headers.insert(name, values);
942 }
943 });
944 }
945
946 /// Sets the generated content length using a stack buffer.
947 ///
948 /// # Arguments
949 ///
950 /// - `usize` - The selected representation's length in bytes.
951 #[inline(always)]
952 fn set_wire_content_length(&mut self, body_len: usize) {
953 let mut digits: [u8; B_20] = [0; B_20];
954 let rendered: &str = render_length(body_len, &mut digits);
955 self.set_header_without_check(CONTENT_LENGTH, rendered);
956 }
957}