Skip to main content

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        let http_status: HttpStatus = HttpStatus::default();
65        Self {
66            version: HttpVersion::Http1_1,
67            status_code: http_status.code(),
68            reason_phrase: http_status.to_string(),
69            headers: hash_map_xx_hash3_64(),
70            body: Vec::new(),
71        }
72    }
73}
74
75/// Inherent implementation of [`Response`].
76impl Response {
77    /// Pushes a header with a key and value as_ref the response bytes.
78    ///
79    /// # Arguments
80    ///
81    /// - `&mut Vec<u8>` - A mutable reference to the bytes where the header will be added.
82    /// - `&str` - The header key as a string slice (`&str`).
83    /// - `&str` - The header value as a string slice (`&str`).
84    #[inline(always)]
85    fn push_header(response_bytes: &mut Vec<u8>, key: &str, value: &str) {
86        response_bytes.extend_from_slice(key.as_bytes());
87        response_bytes.extend_from_slice(COLON.as_bytes());
88        response_bytes.extend_from_slice(value.as_bytes());
89        response_bytes.extend_from_slice(HTTP_BR.as_bytes());
90    }
91
92    /// Tries to retrieve the value of a response header by its key.
93    ///
94    /// # Arguments
95    ///
96    /// - `K` - The header's key, which must implement `AsRef<str>`.
97    ///
98    /// # Returns
99    ///
100    /// - `Option<ResponseHeadersValue>` - The optional header values.
101    #[inline(always)]
102    pub fn try_get_header<K>(&self, key: K) -> Option<ResponseHeadersValue>
103    where
104        K: AsRef<str>,
105    {
106        self.headers.get(key.as_ref()).cloned()
107    }
108
109    /// Retrieves the value of a response header by its key.
110    ///
111    /// # Arguments
112    ///
113    /// - `K` - The header's key, which must implement `AsRef<str>`.
114    ///
115    /// # Returns
116    ///
117    /// - `ResponseHeadersValue` - The optional header values.
118    ///
119    /// # Panics
120    ///
121    /// This function will panic if the header key is not found.
122    #[inline(always)]
123    pub fn get_header<K>(&self, key: K) -> ResponseHeadersValue
124    where
125        K: AsRef<str>,
126    {
127        self.try_get_header(key).unwrap()
128    }
129
130    /// Tries to retrieve the first value of a response header by its key.
131    ///
132    /// # Arguments
133    ///
134    /// - `K` - The header's key, which must implement `AsRef<str>`.
135    ///
136    /// # Returns
137    ///
138    /// - `Option<ResponseHeadersValueItem>` - The first header value if exists.
139    #[inline(always)]
140    pub fn try_get_header_front<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
141    where
142        K: AsRef<str>,
143    {
144        self.headers
145            .get(key.as_ref())
146            .and_then(|data: &VecDeque<String>| data.front().cloned())
147    }
148
149    /// Retrieves the first value of a response header by its key.
150    ///
151    /// # Arguments
152    ///
153    /// - `K` - The header's key, which must implement `AsRef<str>`.
154    ///
155    /// # Returns
156    ///
157    /// - `ResponseHeadersValueItem` - The first header value if exists.
158    ///
159    /// # Panics
160    ///
161    /// This function will panic if the header key is not found.
162    #[inline(always)]
163    pub fn get_header_front<K>(&self, key: K) -> ResponseHeadersValueItem
164    where
165        K: AsRef<str>,
166    {
167        self.try_get_header_front(key).unwrap()
168    }
169
170    /// Tries to retrieve the last value of a response header by its key.
171    ///
172    /// # Arguments
173    ///
174    /// - `K` - The header's key, which must implement `AsRef<str>`.
175    ///
176    /// # Returns
177    ///
178    /// - `Option<ResponseHeadersValueItem>` - The last header value if exists.
179    #[inline(always)]
180    pub fn try_get_header_back<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
181    where
182        K: AsRef<str>,
183    {
184        self.headers
185            .get(key.as_ref())
186            .and_then(|data: &VecDeque<String>| data.back().cloned())
187    }
188
189    /// Retrieves the last value of a response header by its key.
190    ///
191    /// # Arguments
192    ///
193    /// - `K` - The header's key, which must implement `AsRef<str>`.
194    ///
195    /// # Returns
196    ///
197    /// - `ResponseHeadersValueItem` - The last header value if exists.
198    ///
199    /// # Panics
200    ///
201    /// This function will panic if the header key is not found.
202    #[inline(always)]
203    pub fn get_header_back<K>(&self, key: K) -> ResponseHeadersValueItem
204    where
205        K: AsRef<str>,
206    {
207        self.try_get_header_back(key).unwrap()
208    }
209
210    /// Checks if a header exists in the response.
211    ///
212    /// # Arguments
213    ///
214    /// - `K` - The header key to check, which must implement `AsRef<str>`.
215    ///
216    /// # Returns
217    ///
218    /// - `bool` - Whether the header exists.
219    #[inline(always)]
220    pub fn has_header<K>(&self, key: K) -> bool
221    where
222        K: AsRef<str>,
223    {
224        self.get_headers().contains_key(key.as_ref())
225    }
226
227    /// Checks if a header contains a specific value.
228    ///
229    /// # Arguments
230    ///
231    /// - `K` - The header key to check, which must implement `AsRef<str>`.
232    /// - `V` - The value to search for, which must implement `AsRef<str>`.
233    ///
234    /// # Returns
235    ///
236    /// - `bool` - Whether the header contains the value.
237    #[inline(always)]
238    pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
239    where
240        K: AsRef<str>,
241        V: AsRef<str>,
242    {
243        if let Some(values) = self.get_headers().get(key.as_ref()) {
244            values.contains(&value.as_ref().to_owned())
245        } else {
246            false
247        }
248    }
249
250    /// Gets the number of headers in the response.
251    ///
252    /// # Returns
253    ///
254    /// - `usize` - The count of unique header keys.
255    #[inline(always)]
256    pub fn get_headers_size(&self) -> usize {
257        self.headers.len()
258    }
259
260    /// Tries to get the number of values for a specific header key.
261    ///
262    /// # Arguments
263    ///
264    /// - `K` - The header key to count, which must implement `AsRef<str>`.
265    ///
266    /// # Returns
267    ///
268    /// - `Option<usize>` - The count of values for the header.
269    #[inline(always)]
270    pub fn try_get_header_size<K>(&self, key: K) -> Option<usize>
271    where
272        K: AsRef<str>,
273    {
274        self.headers
275            .get(key.as_ref())
276            .map(|data: &VecDeque<String>| data.len())
277    }
278
279    /// Gets the number of values for a specific header key.
280    ///
281    /// # Arguments
282    ///
283    /// - `K` - The header key to count, which must implement `AsRef<str>`.
284    ///
285    /// # Returns
286    ///
287    /// - `usize` - The count of values for the header.
288    ///
289    /// # Panics
290    ///
291    /// This function will panic if the header key is not found.
292    #[inline(always)]
293    pub fn get_header_size<K>(&self, key: K) -> usize
294    where
295        K: AsRef<str>,
296    {
297        self.try_get_header_size(key).unwrap()
298    }
299
300    /// Gets the total number of header values in the response.
301    ///
302    /// This counts all values across all headers, so a header with multiple values
303    /// will contribute more than one to the total count.
304    ///
305    /// # Returns
306    ///
307    /// - `usize` - The total count of all header values.
308    #[inline(always)]
309    pub fn get_headers_values_size(&self) -> usize {
310        self.headers
311            .values()
312            .map(|data: &VecDeque<String>| data.len())
313            .sum()
314    }
315
316    /// Retrieves the body content of the response as a UTF-8 encoded string.
317    ///
318    /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
319    /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
320    ///
321    /// # Returns
322    ///
323    /// - `String` - The body content as a string.
324    #[inline(always)]
325    pub fn get_body_string(&self) -> String {
326        String::from_utf8_lossy(self.get_body()).into_owned()
327    }
328
329    /// Deserializes the body content of the response as_ref a specified type `T`.
330    ///
331    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
332    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
333    ///
334    /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
335    ///
336    /// # Returns
337    ///
338    /// - `Result<T, serde_json::Error>` - The deserialization result.
339    pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
340    where
341        T: DeserializeOwned,
342    {
343        serde_json::from_slice(self.get_body())
344    }
345
346    /// Deserializes the body content of the response as_ref a specified type `T`.
347    ///
348    /// This method first retrieves the body content as a byte slice using `self.get_body()`.
349    /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
350    ///
351    /// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
352    ///
353    /// # Returns
354    ///
355    /// - `T` - The deserialized body content.
356    ///
357    /// # Panics
358    ///
359    /// This function will panic if the deserialization fails.
360    pub fn get_body_json<T>(&self) -> T
361    where
362        T: DeserializeOwned,
363    {
364        self.try_get_body_json().unwrap()
365    }
366
367    /// Determines whether the header should be skipped during setting.
368    ///
369    /// # Arguments
370    ///
371    /// - `&str` - The header key to inspect.
372    ///
373    /// # Returns
374    ///
375    /// - `bool` - `true` if the header is empty or not allowed, `false` if the header can be set.
376    #[inline(always)]
377    fn should_skip_header(&self, key: &str) -> bool {
378        key.trim().is_empty() || key == CONTENT_LENGTH
379    }
380
381    /// Sets a header in the response, replacing any existing values.
382    ///
383    /// This function replaces all existing values for a header with a single new value.
384    ///
385    /// # Arguments
386    ///
387    /// - `K` - The header key, which must implement `AsRef<str>`.
388    /// - `V` - The header value, which must implement `AsRef<String>`.
389    ///
390    /// # Returns
391    ///
392    /// - `&mut Self` - A mutable reference to self for chaining.
393    #[inline(always)]
394    fn set_header_without_check<K, V>(&mut self, key: K, value: V) -> &mut Self
395    where
396        K: AsRef<str>,
397        V: AsRef<str>,
398    {
399        let key: &str = key.as_ref();
400        let value: &str = value.as_ref();
401        if let Some(values) = self.get_mut_headers().get_mut(key) {
402            values.truncate(1);
403            if let Some(slot) = values.front_mut() {
404                slot.clear();
405                slot.push_str(value);
406            } else {
407                values.push_back(value.to_owned());
408            }
409            return self;
410        }
411        // A recycled entry carries the buffers of the name and of the value,
412        // so a response that sets the same headers over and over stops
413        // allocating for them.
414        let (mut name, mut values): (String, VecDeque<String>) =
415            take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
416        name.clear();
417        name.push_str(key);
418        // A recycled entry may carry the values of a header that was sent
419        // more than once. Those values belong to that header, so only the
420        // first one is kept and the rest are dropped.
421        while values.len() > 1 {
422            values.pop_back();
423        }
424        if values.is_empty() {
425            values.push_back(String::new());
426        }
427        if let Some(slot) = values.front_mut() {
428            slot.clear();
429            slot.push_str(value.as_ref());
430        }
431        self.get_mut_headers().insert(name, values);
432        self
433    }
434
435    /// Sets a header in the response, replacing any existing values.
436    ///
437    /// This function replaces all existing values for a header with a single new value.
438    ///
439    /// # Arguments
440    ///
441    /// - `K` - The header key, which must implement `AsRef<str>`.
442    /// - `V` - The header value, which must implement `AsRef<String>`.
443    ///
444    /// # Returns
445    ///
446    /// - `&mut Self` - A mutable reference to self for chaining.
447    #[inline(always)]
448    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
449    where
450        K: AsRef<str>,
451        V: AsRef<str>,
452    {
453        let key: &str = key.as_ref();
454        if self.should_skip_header(key) {
455            return self;
456        }
457        self.set_header_without_check(key, value)
458    }
459
460    /// Adds a header to the response.
461    ///
462    /// This function appends a value to the response headers.
463    /// If the header already exists, the new value will be added to the existing values.
464    ///
465    /// # Arguments
466    ///
467    /// - `K` - The header key, which must implement `AsRef<str>`.
468    /// - `V` - The header value, which must implement `AsRef<String>`.
469    ///
470    /// # Returns
471    ///
472    /// - `&mut Self` - A mutable reference to self for chaining.
473    #[inline(always)]
474    pub fn add_header<K, V>(&mut self, key: K, value: V) -> &mut Self
475    where
476        K: AsRef<str>,
477        V: AsRef<str>,
478    {
479        let key: ResponseHeadersKey = key.as_ref().to_owned();
480        if self.should_skip_header(&key) {
481            return self;
482        }
483        self.get_mut_headers()
484            .entry(key)
485            .or_default()
486            .push_back(value.as_ref().to_owned());
487        self
488    }
489
490    /// Removes a header from the response.
491    ///
492    /// This function removes all values for the specified header key.
493    ///
494    /// # Arguments
495    ///
496    /// - `K` - The header key to remove, which must implement `AsRef<str>`.
497    ///
498    /// # Returns
499    ///
500    /// - `&mut Self` - A mutable reference to self for chaining.
501    #[inline(always)]
502    pub fn remove_header<K>(&mut self, key: K) -> &mut Self
503    where
504        K: AsRef<str>,
505    {
506        let _: bool = self.get_mut_headers().remove(key.as_ref()).is_some();
507        self
508    }
509
510    /// Removes a specific value from a header in the response.
511    ///
512    /// This function removes only the specified value from the header.
513    /// If the header has multiple values, only the matching value is removed.
514    /// If this was the last value for the header, the entire header is removed.
515    ///
516    /// # Arguments
517    ///
518    /// - `K` - The header key, which must implement `AsRef<str>`.
519    /// - `V` - The value to remove, which must implement `AsRef<String>`.
520    ///
521    /// # Returns
522    ///
523    /// - `&mut Self` - A mutable reference to self for chaining.
524    #[inline(always)]
525    pub fn remove_header_value<K, V>(&mut self, key: K, value: V) -> &mut Self
526    where
527        K: AsRef<str>,
528        V: AsRef<str>,
529    {
530        let key: ResponseHeadersKey = key.as_ref().to_owned();
531        if let Some(values) = self.get_mut_headers().get_mut(&key) {
532            values.retain(|data: &String| data != &value.as_ref().to_owned());
533            if values.is_empty() {
534                self.get_mut_headers().remove(&key);
535            }
536        }
537        self
538    }
539
540    /// Clears all headers from the response.
541    ///
542    /// This function removes all headers, leaving the headers map empty.
543    ///
544    /// # Returns
545    ///
546    /// - `&mut Self` - A mutable reference to self for chaining.
547    #[inline(always)]
548    pub fn clear_headers(&mut self) -> &mut Self {
549        self.get_mut_headers().clear();
550        self
551    }
552
553    /// Resets the response to its default state while retaining allocated capacity.
554    ///
555    /// This keeps the header map and body allocations so persistent
556    /// (keep-alive) connections avoid repeated allocation per request.
557    ///
558    /// # Returns
559    ///
560    /// - `&mut Self` - A mutable reference to self for chaining.
561    pub fn reset(&mut self) -> &mut Self {
562        let http_status: HttpStatus = HttpStatus::default();
563        self.set_status_code(http_status.code());
564        // The phrase is written into the existing buffer rather than
565        // replaced, so a response that is reset over and over stops
566        // allocating for it.
567        let stored: &mut ResponseReasonPhrase = self.get_mut_reason_phrase();
568        stored.clear();
569        stored.push_str(HttpStatus::phrase_ref(http_status.code()));
570        self.recycle_headers();
571        self.get_mut_body().clear();
572        self
573    }
574
575    /// Hands the header entries to the pool and empties the header map.
576    ///
577    /// The map ends up empty, exactly as clearing it would, but the name and
578    /// the value buffers of every header survive in the pool. The next
579    /// response reuses them instead of allocating new ones.
580    ///
581    /// # Returns
582    ///
583    /// - `()` - The headers have been recycled.
584    fn recycle_headers(&mut self) {
585        let headers: &mut ResponseHeaders = self.get_mut_headers();
586        if headers.is_empty() {
587            return;
588        }
589        for (key, values) in headers.drain() {
590            return_header_entry((key, values));
591        }
592    }
593
594    /// Tries to parse cookies from the `Set-Cookie` header.
595    ///
596    /// This method retrieves the last `Set-Cookie` header value and parses it
597    /// into a collection of key-value pairs representing the cookies.
598    ///
599    /// # Returns
600    ///
601    /// - `Option<Cookies>` - The parsed cookies if the `Set-Cookie` header exists, otherwise `None`.
602    #[inline(always)]
603    pub fn try_get_cookies(&self) -> Option<Cookies> {
604        self.try_get_header_back(SET_COOKIE)
605            .map(|cookie_header: String| Cookie::parse(cookie_header))
606    }
607
608    /// Parses cookies from the `Set-Cookie` headers.
609    ///
610    /// This method retrieves all `Set-Cookie` header values and parses each one
611    /// into a collection of key-value pairs representing the cookies.
612    ///
613    /// # Returns
614    ///
615    /// - `Cookies` - The parsed cookies.
616    ///
617    /// # Panics
618    ///
619    /// This function will panic if the `Set-Cookie` header is not found.
620    #[inline(always)]
621    pub fn get_cookies(&self) -> Cookies {
622        self.try_get_cookies().unwrap()
623    }
624
625    /// Tries to get a cookie value by its key from `Set-Cookie` headers.
626    ///
627    /// This method parses the cookies from all `Set-Cookie` headers,
628    /// then attempts to retrieve the value for the specified key.
629    ///
630    /// # Arguments
631    ///
632    /// - `K` - The cookie key, which implements `AsRef<str>`.
633    ///
634    /// # Returns
635    ///
636    /// - `Option<CookieValue>` - The cookie value if exists.
637    #[inline(always)]
638    pub fn try_get_cookie<K>(&self, key: K) -> Option<CookieValue>
639    where
640        K: AsRef<str>,
641    {
642        self.try_get_cookies()
643            .and_then(|cookies: Cookies| cookies.get(key.as_ref()).cloned())
644    }
645
646    /// Gets a cookie value by its key from `Set-Cookie` headers.
647    ///
648    /// This method parses the cookies from all `Set-Cookie` headers,
649    /// then retrieves the value for the specified key.
650    ///
651    /// # Arguments
652    ///
653    /// - `K` - The cookie key, which implements `AsRef<str>`.
654    ///
655    /// # Returns
656    ///
657    /// - `CookieValue` - The cookie value.
658    ///
659    /// # Panics
660    ///
661    /// This function will panic if the `Set-Cookie` header is not found
662    /// or the cookie key does not exist.
663    #[inline(always)]
664    pub fn get_cookie<K>(&self, key: K) -> CookieValue
665    where
666        K: AsRef<str>,
667    {
668        self.try_get_cookie(key).unwrap()
669    }
670
671    /// Builds the full HTTP response as a byte vector.
672    ///
673    /// This method constructs the complete HTTP response, including the status line,
674    /// headers, and body. It handles content encoding, content type, connection
675    /// management, and content length.
676    ///
677    /// # Returns
678    ///
679    /// - `ResponseData` - The complete HTTP response bytes.
680    pub fn build(&mut self) -> ResponseData {
681        if self.get_reason_phrase().is_empty() || self.get_reason_phrase().as_str() == OK {
682            // The phrase is written into the existing buffer rather than
683            // replaced, so a response that announces the same status over and
684            // over stops allocating for it.
685            let phrase: &'static str = HttpStatus::phrase_ref(self.get_status_code());
686            let stored: &mut ResponseReasonPhrase = self.get_mut_reason_phrase();
687            stored.clear();
688            stored.push_str(phrase);
689        }
690        let compress_type_opt: Option<Compress> = self
691            .get_headers()
692            .get(CONTENT_ENCODING)
693            .and_then(|values: &VecDeque<String>| values.back())
694            .map(|data: &String| data.parse::<Compress>().unwrap_or_default());
695        if self
696            .get_headers()
697            .get(CONNECTION)
698            .and_then(|values: &VecDeque<String>| values.back())
699            .is_none()
700        {
701            self.set_header_without_check(CONNECTION, KEEP_ALIVE);
702        }
703        if self
704            .get_headers()
705            .get(CONTENT_TYPE)
706            .and_then(|values: &VecDeque<String>| values.back())
707            .is_none()
708        {
709            self.set_header_without_check(CONTENT_TYPE, default_content_type());
710        }
711        let is_event_stream: bool = self
712            .get_headers()
713            .get(CONTENT_TYPE)
714            .and_then(|values: &VecDeque<String>| values.back())
715            .is_some_and(|value: &String| value.eq_ignore_ascii_case(TEXT_EVENT_STREAM));
716        let compressed_body: Option<Vec<u8>> = match compress_type_opt {
717            Some(compress_type) if !compress_type.is_unknown() => Some(
718                compress_type
719                    .encode(self.get_body(), DEFAULT_BUFFER_SIZE)
720                    .into_owned(),
721            ),
722            _ => None,
723        };
724        let body_len: usize = compressed_body
725            .as_ref()
726            .map_or_else(|| self.get_body().len(), Vec::len);
727        if !is_event_stream {
728            // The length is rendered into a stack buffer and then copied into
729            // the header's own buffer, so announcing the length allocates
730            // nothing beyond what the header already holds.
731            let mut digits: [u8; B_20] = [0; B_20];
732            let rendered: &str = render_length(body_len, &mut digits);
733            self.set_header_without_check(CONTENT_LENGTH, rendered);
734        }
735        let mut head_size: usize = self.get_reason_phrase().len() + B_16 + HTTP_BR.len();
736        head_size += self
737            .get_headers()
738            .iter()
739            .map(|header_entry: (&String, &VecDeque<String>)| {
740                let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
741                header_values
742                    .iter()
743                    .map(|header_value: &String| {
744                        header_key.len() + COLON.len() + header_value.len() + HTTP_BR.len()
745                    })
746                    .sum::<usize>()
747            })
748            .sum::<usize>();
749        let mut response_bytes: Vec<u8> = Vec::with_capacity(head_size + body_len);
750        response_bytes.extend_from_slice(self.get_version().as_str().as_bytes());
751        response_bytes.push(b' ');
752        let mut code: [u8; B_20] = [0; B_20];
753        response_bytes
754            .extend_from_slice(render_length(self.get_status_code(), &mut code).as_bytes());
755        response_bytes.push(b' ');
756        response_bytes.extend_from_slice(self.get_reason_phrase().as_bytes());
757        response_bytes.extend_from_slice(HTTP_BR.as_bytes());
758        self.get_headers()
759            .iter()
760            .for_each(|header_entry: (&String, &VecDeque<String>)| {
761                let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
762                for header_value in header_values.iter() {
763                    Self::push_header(&mut response_bytes, header_key, header_value);
764                }
765            });
766        response_bytes.extend_from_slice(HTTP_BR.as_bytes());
767        match &compressed_body {
768            Some(body) => response_bytes.extend_from_slice(body),
769            None => response_bytes.extend_from_slice(self.get_body()),
770        }
771        response_bytes
772    }
773}