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        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<VecDeque<String>>` - The optional header values.
137    #[inline(always)]
138    pub fn try_get_header<K>(&self, key: K) -> Option<VecDeque<String>>
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    /// - `VecDeque<String>` - 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) -> VecDeque<String>
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<String>` - The first header value if exists.
175    #[inline(always)]
176    pub fn try_get_header_front<K>(&self, key: K) -> Option<String>
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    /// - `String` - 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) -> String
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<String>` - The last header value if exists.
215    #[inline(always)]
216    pub fn try_get_header_back<K>(&self, key: K) -> Option<String>
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    /// - `String` - 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) -> String
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        let bytes: &[u8] = value.as_bytes();
433        let len: usize = bytes.len();
434        if len < 8 {
435            return bytes
436                .iter()
437                .all(|byte: &u8| HTTP_HEADER_VALUE_VALID_TABLE[*byte as usize]);
438        }
439        validate_header_value_swar(bytes).is_some()
440    }
441
442    /// Validates whether an HTTP version token contains no whitespace or control bytes.
443    ///
444    /// # Arguments
445    ///
446    /// - `&str` - The HTTP version text to inspect.
447    ///
448    /// # Returns
449    ///
450    /// - `bool` - `true` if the version token is safe to emit on the status line.
451    #[inline(always)]
452    fn is_valid_http_version(version: &str) -> bool {
453        !version.is_empty()
454            && version
455                .bytes()
456                .all(|byte: u8| byte > SPACE_U8 && byte < HTTP_HEADER_DELETE)
457    }
458
459    /// Determines whether the header should be skipped during setting.
460    ///
461    /// # Arguments
462    ///
463    /// - `&str` - The header key to inspect.
464    ///
465    /// # Returns
466    ///
467    /// - `bool` - `true` if the header is invalid or framing-controlled, `false` otherwise.
468    #[inline(always)]
469    fn should_skip_header(&self, key: &str) -> bool {
470        !Self::is_valid_header_name(key) || key.eq_ignore_ascii_case(CONTENT_LENGTH)
471    }
472
473    /// Sets a header in the response, replacing any existing values.
474    ///
475    /// This function replaces all existing values for a header with a single new value.
476    ///
477    /// # Arguments
478    ///
479    /// - `K` - The header key, which must implement `AsRef<str>`.
480    /// - `V` - The header value, which must implement `AsRef<String>`.
481    ///
482    /// # Returns
483    ///
484    /// - `&mut Self` - A mutable reference to self for chaining.
485    #[inline(always)]
486    fn set_header_without_check<K, V>(&mut self, key: K, value: V) -> &mut Self
487    where
488        K: AsRef<str>,
489        V: AsRef<str>,
490    {
491        let key: &str = key.as_ref();
492        let value: &str = value.as_ref();
493        if !self.get_headers().is_empty()
494            && let Some(values) = self.get_mut_headers().get_mut(key)
495        {
496            values.truncate(1);
497            if let Some(slot) = values.front_mut() {
498                slot.clear();
499                slot.push_str(value);
500            } else {
501                values.push_back(value.to_owned());
502            }
503            return self;
504        }
505        // A recycled entry carries the buffers of the name and of the value,
506        // so a response that sets the same headers over and over stops
507        // allocating for them.
508        let (mut name, mut values): (String, VecDeque<String>) =
509            take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
510        name.clear();
511        name.push_str(key);
512        // A recycled entry may carry the values of a header that was sent
513        // more than once. Those values belong to that header, so only the
514        // first one is kept and the rest are dropped.
515        while values.len() > 1 {
516            values.pop_back();
517        }
518        if values.is_empty() {
519            values.push_back(String::new());
520        }
521        if let Some(slot) = values.front_mut() {
522            slot.clear();
523            slot.push_str(value.as_ref());
524        }
525        self.get_mut_headers().insert(name, values);
526        self
527    }
528
529    /// Sets a header in the response, replacing any existing values.
530    ///
531    /// This function replaces all existing values for a header with a single new value.
532    ///
533    /// # Arguments
534    ///
535    /// - `K` - The header key, which must implement `AsRef<str>`.
536    /// - `V` - The header value, which must implement `AsRef<String>`.
537    ///
538    /// # Returns
539    ///
540    /// - `&mut Self` - A mutable reference to self for chaining.
541    #[inline(always)]
542    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
543    where
544        K: AsRef<str>,
545        V: AsRef<str>,
546    {
547        let key: &str = key.as_ref();
548        let value: &str = value.as_ref();
549        if self.should_skip_header(key) || !Self::is_valid_header_value(value) {
550            return self;
551        }
552        self.set_header_without_check(key, value)
553    }
554
555    /// Sets multiple response headers in one batched thread-local pool borrow.
556    ///
557    /// Applies the exact same validation as [`Response::set_header`] while amortizing
558    /// pool access and skipping duplicate probes when `self.headers` starts empty.
559    ///
560    /// # Arguments
561    ///
562    /// - `&[(K, V)]` - Slice of `(key, value)` header pairs to set.
563    ///
564    /// # Returns
565    ///
566    /// - `&mut Self` - A mutable reference to self for chaining.
567    #[inline]
568    pub fn set_headers_batch<K, V>(&mut self, pairs: &[(K, V)]) -> &mut Self
569    where
570        K: AsRef<str>,
571        V: AsRef<str>,
572    {
573        if pairs.is_empty() {
574            return self;
575        }
576        let headers: &mut ResponseHeaders = self.get_mut_headers();
577        let was_empty: bool = headers.is_empty();
578        if was_empty {
579            headers.reserve(pairs.len());
580        }
581        HEADER_ENTRY_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
582            let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
583            for (raw_key, raw_value) in pairs {
584                let key: &str = raw_key.as_ref();
585                let value: &str = raw_value.as_ref();
586                if !Self::is_valid_header_name(key)
587                    || key.eq_ignore_ascii_case(CONTENT_LENGTH)
588                    || !Self::is_valid_header_value(value)
589                {
590                    continue;
591                }
592                if !was_empty && let Some(values) = headers.get_mut(key) {
593                    values.truncate(1);
594                    if let Some(slot) = values.front_mut() {
595                        slot.clear();
596                        slot.push_str(value);
597                    } else {
598                        values.push_back(value.to_owned());
599                    }
600                    continue;
601                }
602                let (mut name, mut values): (String, VecDeque<String>) = pool
603                    .pop()
604                    .unwrap_or_else(|| (String::new(), VecDeque::new()));
605                name.clear();
606                name.push_str(key);
607                if values.len() == 1 {
608                    values[0].clear();
609                    values[0].push_str(value);
610                } else {
611                    while values.len() > 1 {
612                        values.pop_back();
613                    }
614                    if let Some(slot) = values.front_mut() {
615                        slot.clear();
616                        slot.push_str(value);
617                    } else {
618                        values.push_back(value.to_owned());
619                    }
620                }
621                headers.insert(name, values);
622            }
623        });
624        self
625    }
626
627    /// Adds a header to the response.
628    ///
629    /// This function appends a value to the response headers.
630    /// If the header already exists, the new value will be added to the existing values.
631    ///
632    /// # Arguments
633    ///
634    /// - `K` - The header key, which must implement `AsRef<str>`.
635    /// - `V` - The header value, which must implement `AsRef<String>`.
636    ///
637    /// # Returns
638    ///
639    /// - `&mut Self` - A mutable reference to self for chaining.
640    #[inline(always)]
641    pub fn add_header<K, V>(&mut self, key: K, value: V) -> &mut Self
642    where
643        K: AsRef<str>,
644        V: AsRef<str>,
645    {
646        let key_ref: &str = key.as_ref();
647        let value_ref: &str = value.as_ref();
648        if self.should_skip_header(key_ref) || !Self::is_valid_header_value(value_ref) {
649            return self;
650        }
651        if let Some(existing) = self.get_mut_headers().get_mut(key_ref) {
652            existing.push_back(value_ref.to_owned());
653            return self;
654        }
655        let (mut name, mut values): (String, VecDeque<String>) =
656            take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
657        name.clear();
658        name.push_str(key_ref);
659        while values.len() > 1 {
660            values.pop_back();
661        }
662        if let Some(slot) = values.front_mut() {
663            slot.clear();
664            slot.push_str(value_ref);
665        } else {
666            values.push_back(value_ref.to_owned());
667        }
668        self.get_mut_headers().insert(name, values);
669        self
670    }
671
672    /// Removes a header from the response.
673    ///
674    /// This function removes all values for the specified header key.
675    ///
676    /// # Arguments
677    ///
678    /// - `K` - The header key to remove, which must implement `AsRef<str>`.
679    ///
680    /// # Returns
681    ///
682    /// - `&mut Self` - A mutable reference to self for chaining.
683    #[inline(always)]
684    pub fn remove_header<K>(&mut self, key: K) -> &mut Self
685    where
686        K: AsRef<str>,
687    {
688        let _: bool = self.get_mut_headers().remove(key.as_ref()).is_some();
689        self
690    }
691
692    /// Removes a specific value from a header in the response.
693    ///
694    /// This function removes only the specified value from the header.
695    /// If the header has multiple values, only the matching value is removed.
696    /// If this was the last value for the header, the entire header is removed.
697    ///
698    /// # Arguments
699    ///
700    /// - `K` - The header key, which must implement `AsRef<str>`.
701    /// - `V` - The value to remove, which must implement `AsRef<String>`.
702    ///
703    /// # Returns
704    ///
705    /// - `&mut Self` - A mutable reference to self for chaining.
706    #[inline(always)]
707    pub fn remove_header_value<K, V>(&mut self, key: K, value: V) -> &mut Self
708    where
709        K: AsRef<str>,
710        V: AsRef<str>,
711    {
712        let key_ref: &str = key.as_ref();
713        let value_ref: &str = value.as_ref();
714        let should_remove: bool = if let Some(values) = self.get_mut_headers().get_mut(key_ref) {
715            values.retain(|data: &String| data != value_ref);
716            values.is_empty()
717        } else {
718            false
719        };
720        if should_remove {
721            self.get_mut_headers().remove(key_ref);
722        }
723        self
724    }
725
726    /// Clears all headers from the response.
727    ///
728    /// This function removes all headers, leaving the headers map empty.
729    ///
730    /// # Returns
731    ///
732    /// - `&mut Self` - A mutable reference to self for chaining.
733    #[inline(always)]
734    pub fn clear_headers(&mut self) -> &mut Self {
735        self.recycle_headers();
736        self
737    }
738
739    /// Resets the response to its default state while retaining allocated capacity.
740    ///
741    /// This keeps the header map and body allocations so persistent
742    /// (keep-alive) connections avoid repeated allocation per request.
743    ///
744    /// # Returns
745    ///
746    /// - `&mut Self` - A mutable reference to self for chaining.
747    #[inline(always)]
748    pub fn reset(&mut self) -> &mut Self {
749        let http_status: HttpStatus = HttpStatus::default();
750        self.set_version(HttpVersion::Http1_1);
751        self.set_status_code(http_status.code());
752        let phrase: &'static str = HttpStatus::phrase_ref(http_status.code());
753        let stored: &mut String = self.get_mut_reason_phrase();
754        if stored.as_str() != phrase {
755            stored.clear();
756            stored.push_str(phrase);
757        }
758        self.recycle_headers();
759        self.get_mut_body().clear();
760        self
761    }
762
763    /// Hands the header entries to the pool and empties the header map.
764    ///
765    /// The map ends up empty, exactly as clearing it would, but the name and
766    /// the value buffers of every header survive in the pool. The next
767    /// response reuses them instead of allocating new ones.
768    ///
769    /// # Returns
770    ///
771    /// - `()` - The headers have been recycled.
772    fn recycle_headers(&mut self) {
773        let headers: &mut ResponseHeaders = self.get_mut_headers();
774        if headers.is_empty() {
775            return;
776        }
777        return_header_entries(headers.drain());
778    }
779
780    /// Tries to parse cookies from the `Set-Cookie` header.
781    ///
782    /// This method retrieves the last `Set-Cookie` header value and parses it
783    /// into a collection of key-value pairs representing the cookies.
784    ///
785    /// # Returns
786    ///
787    /// - `Option<HashMapXxHash3_64<String, String>>` - The parsed cookies if the `Set-Cookie` header exists, otherwise `None`.
788    #[inline(always)]
789    pub fn try_get_cookies(&self) -> Option<HashMapXxHash3_64<String, String>> {
790        let mut cookies: HashMapXxHash3_64<String, String> = hash_map_xx_hash3_64();
791        let mut found_header: bool = false;
792        for (name, values) in self.get_headers() {
793            if !name.eq_ignore_ascii_case(SET_COOKIE) {
794                continue;
795            }
796            for header_value in values {
797                found_header = true;
798                let parsed: CookieBuilder = CookieBuilder::parse(header_value);
799                if !parsed.get_name().is_empty() {
800                    cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
801                }
802            }
803        }
804        found_header.then_some(cookies)
805    }
806
807    /// Parses cookies from the `Set-Cookie` headers.
808    ///
809    /// This method retrieves all `Set-Cookie` header values and parses each one
810    /// into a collection of key-value pairs representing the cookies.
811    ///
812    /// # Returns
813    ///
814    /// - `HashMapXxHash3_64<String, String>` - The parsed cookies.
815    ///
816    /// # Panics
817    ///
818    /// This function will panic if the `Set-Cookie` header is not found.
819    #[inline(always)]
820    pub fn get_cookies(&self) -> HashMapXxHash3_64<String, String> {
821        self.try_get_cookies().unwrap()
822    }
823
824    /// Tries to get a cookie value by its key from `Set-Cookie` headers.
825    ///
826    /// This method parses the cookies from all `Set-Cookie` headers,
827    /// then attempts to retrieve the value for the specified key.
828    ///
829    /// # Arguments
830    ///
831    /// - `K` - The cookie key, which implements `AsRef<str>`.
832    ///
833    /// # Returns
834    ///
835    /// - `Option<String>` - The cookie value if exists.
836    #[inline(always)]
837    pub fn try_get_cookie<K>(&self, key: K) -> Option<String>
838    where
839        K: AsRef<str>,
840    {
841        let key_ref: &str = key.as_ref();
842        if key_ref.is_empty() || !is_cookie_name_valid(key_ref) {
843            return None;
844        }
845        let mut found: Option<&str> = None;
846        for (name, values) in self.get_headers() {
847            if !name.eq_ignore_ascii_case(SET_COOKIE) {
848                continue;
849            }
850            for header_value in values {
851                let first_part: &str = header_value.split(SEMICOLON).next().unwrap_or(EMPTY_STR);
852                if let Some((cookie_name, cookie_val)) = first_part.trim().split_once(EQUAL)
853                    && cookie_name.trim() == key_ref
854                {
855                    let val: &str = cookie_val.trim();
856                    if !val.bytes().any(is_control_byte) {
857                        found = Some(val);
858                    }
859                }
860            }
861        }
862        found.map(str::to_owned)
863    }
864
865    /// Gets a cookie value by its key from `Set-Cookie` headers.
866    ///
867    /// This method parses the cookies from all `Set-Cookie` headers,
868    /// then retrieves the value for the specified key.
869    ///
870    /// # Arguments
871    ///
872    /// - `K` - The cookie key, which implements `AsRef<str>`.
873    ///
874    /// # Returns
875    ///
876    /// - `String` - The cookie value.
877    ///
878    /// # Panics
879    ///
880    /// This function will panic if the `Set-Cookie` header is not found
881    /// or the cookie key does not exist.
882    #[inline(always)]
883    pub fn get_cookie<K>(&self, key: K) -> String
884    where
885        K: AsRef<str>,
886    {
887        self.try_get_cookie(key).unwrap()
888    }
889
890    /// Removes framing fields before a header-only response is serialized.
891    #[cold]
892    fn clear_framing_headers(&mut self) {
893        self.get_mut_headers()
894            .retain(|name: &String, _: &mut VecDeque<String>| {
895                !name.eq_ignore_ascii_case(CONTENT_LENGTH)
896                    && !name.eq_ignore_ascii_case(TRANSFER_ENCODING)
897            });
898    }
899
900    /// Builds the full HTTP response as a byte vector.
901    ///
902    /// This method constructs the complete HTTP response, including the status line,
903    /// headers, and body. It handles content encoding, content type, connection
904    /// management, and content length.
905    /// Informational, 204, 205, and 304 responses never serialize the body.
906    /// A 205 response declares a zero length; the other bodyless statuses
907    /// omit framing headers. For 304, the body cannot establish the length
908    /// of the selected representation.
909    ///
910    /// # Returns
911    ///
912    /// - `Vec<u8>` - The complete HTTP response bytes.
913    #[inline]
914    pub fn build(&mut self) -> Vec<u8> {
915        let mut out: Vec<u8> = Vec::new();
916        Self::build_wire_into::<true, true>(self, &mut out);
917        out
918    }
919
920    /// Appends the full HTTP response wire bytes directly into `out`.
921    ///
922    /// Unlike [`Response::build`], this avoids allocating a new byte vector and
923    /// skips mutating default framing headers back into `self.headers`, making
924    /// repeated keep-alive serialization zero-allocation when `out` is reused.
925    ///
926    /// # Arguments
927    ///
928    /// - `&mut Vec<u8>` - Destination byte buffer to append wire bytes to.
929    #[inline]
930    pub fn build_into(&mut self, out: &mut Vec<u8>) {
931        Self::build_wire_into::<true, false>(self, out);
932    }
933
934    /// Builds an HTTP response to `HEAD` without serializing or compressing its body.
935    ///
936    /// Set the body to the matching `GET` representation if its length is known.
937    /// An empty buffer, an event stream, or a body that would be compressed does
938    /// not establish that length, so the generated response omits it.
939    ///
940    /// # Returns
941    ///
942    /// - `Vec<u8>` - The status line and headers ending at the header terminator.
943    #[must_use]
944    pub fn build_head(&mut self) -> Vec<u8> {
945        let mut out: Vec<u8> = Vec::new();
946        Self::build_wire_into::<false, true>(self, &mut out);
947        out
948    }
949
950    /// Appends the header-only `HEAD` response wire bytes directly into `out`.
951    ///
952    /// # Arguments
953    ///
954    /// - `&mut Vec<u8>` - Destination byte buffer to append wire bytes to.
955    #[inline]
956    pub fn build_head_into(&mut self, out: &mut Vec<u8>) {
957        Self::build_wire_into::<false, false>(self, out);
958    }
959
960    /// Serializes either a full response or the header-only response to `HEAD` into `out`.
961    ///
962    /// # Arguments
963    ///
964    /// - `&mut Vec<u8>` - Destination wire buffer.
965    fn build_wire_into<const INCLUDE_BODY: bool, const POPULATE_HEADERS: bool>(
966        &mut self,
967        out: &mut Vec<u8>,
968    ) {
969        let status_code: usize = self.get_status_code();
970        let is_default_ok: bool =
971            status_code == HttpStatus::Ok.code() && self.get_reason_phrase().as_str() == OK;
972        if !is_default_ok
973            && (self.get_reason_phrase().is_empty()
974                || self.get_reason_phrase().as_str() == OK
975                || !Self::is_valid_header_value(self.get_reason_phrase()))
976        {
977            // The phrase is written into the existing buffer rather than
978            // replaced, so a response that announces the same status over and
979            // over stops allocating for it.
980            let phrase: &'static str = HttpStatus::phrase_ref(status_code);
981            if self.get_reason_phrase().as_str() != phrase {
982                let stored: &mut String = self.get_mut_reason_phrase();
983                stored.clear();
984                stored.push_str(phrase);
985            }
986        }
987        if INCLUDE_BODY
988            && self.get_headers().is_empty()
989            && status_code >= HttpStatus::Ok.code()
990            && status_code != HttpStatus::NoContent.code()
991            && status_code != HttpStatus::ResetContent.code()
992            && status_code != HttpStatus::NotModified.code()
993        {
994            let content_type: &str = default_content_type();
995            let body_len: usize = self.get_body().len();
996            let mut digits: [u8; B_20] = [0; B_20];
997            let rendered_len: &str = render_length(body_len, &mut digits);
998            let fast_prefix: Option<&[u8]> = if is_default_ok {
999                match self.get_version() {
1000                    HttpVersion::Http1_1 => Some(FAST_HTTP11_200_CL_PREFIX),
1001                    HttpVersion::Http2 => Some(FAST_HTTP2_200_CL_PREFIX),
1002                    HttpVersion::Http3 => Some(FAST_HTTP3_200_CL_PREFIX),
1003                    _ => None,
1004                }
1005            } else {
1006                None
1007            };
1008            let body_slice: &[u8] = self.get_body().as_slice();
1009            if let Some(prefix) = fast_prefix {
1010                let prefix_len: usize = prefix.len();
1011                let digits_bytes: &[u8] = rendered_len.as_bytes();
1012                let digits_len: usize = digits_bytes.len();
1013                let suffix_len: usize = FAST_DEFAULT_HEADERS_SUFFIX.len();
1014                let total_size: usize = prefix_len + digits_len + suffix_len + body_len;
1015                let base: usize = out.len();
1016                out.reserve(total_size);
1017                // SAFETY: `out` has reserved at least `total_size` spare bytes after `base`;
1018                // we copy four contiguous non-overlapping regions and advance length to `base + total_size`.
1019                unsafe {
1020                    let mut dst: *mut u8 = out.as_mut_ptr().add(base);
1021                    ptr::copy_nonoverlapping(prefix.as_ptr(), dst, prefix_len);
1022                    dst = dst.add(prefix_len);
1023                    ptr::copy_nonoverlapping(digits_bytes.as_ptr(), dst, digits_len);
1024                    dst = dst.add(digits_len);
1025                    ptr::copy_nonoverlapping(FAST_DEFAULT_HEADERS_SUFFIX.as_ptr(), dst, suffix_len);
1026                    dst = dst.add(suffix_len);
1027                    if body_len > 0 {
1028                        ptr::copy_nonoverlapping(body_slice.as_ptr(), dst, body_len);
1029                    }
1030                    out.set_len(base + total_size);
1031                }
1032            } else {
1033                let raw_version: &str = self.get_version().as_str();
1034                let version_str: &str = if !matches!(self.get_version(), HttpVersion::Unknown(_))
1035                    || Self::is_valid_http_version(raw_version)
1036                {
1037                    raw_version
1038                } else {
1039                    HTTP_VERSION_1_1
1040                };
1041                let phrase_str: &str = self.get_reason_phrase().as_str();
1042                let mut code_digits: [u8; B_20] = [0; B_20];
1043                let rendered_code: &str = render_length(status_code, &mut code_digits);
1044                let total_size: usize = version_str.len()
1045                    + 1
1046                    + rendered_code.len()
1047                    + 1
1048                    + phrase_str.len()
1049                    + FAST_CL_PREFIX.len()
1050                    + rendered_len.len()
1051                    + FAST_DEFAULT_HEADERS_SUFFIX.len()
1052                    + body_len;
1053                out.reserve(total_size);
1054                out.extend_from_slice(version_str.as_bytes());
1055                out.push(b' ');
1056                out.extend_from_slice(rendered_code.as_bytes());
1057                out.push(b' ');
1058                out.extend_from_slice(phrase_str.as_bytes());
1059                out.extend_from_slice(FAST_CL_PREFIX);
1060                out.extend_from_slice(rendered_len.as_bytes());
1061                out.extend_from_slice(FAST_DEFAULT_HEADERS_SUFFIX);
1062                out.extend_from_slice(body_slice);
1063            }
1064            if POPULATE_HEADERS {
1065                self.populate_default_headers_batch(content_type, rendered_len);
1066            }
1067            return;
1068        }
1069        let mut has_connection: bool = false;
1070        let mut has_content_type: bool = false;
1071        let mut is_event_stream: bool = false;
1072        let mut has_transfer_encoding: bool = false;
1073        let mut has_non_canonical_cl: bool = false;
1074        let mut compress_type: Option<Compress> = None;
1075        let mut existing_headers_bytes: usize = 0;
1076        for (name, values) in self.get_headers() {
1077            if name.len() == 14
1078                && name != CONTENT_LENGTH
1079                && name.eq_ignore_ascii_case(CONTENT_LENGTH)
1080            {
1081                has_non_canonical_cl = true;
1082            }
1083            if values.is_empty() {
1084                continue;
1085            }
1086            for header_value in values.iter() {
1087                existing_headers_bytes +=
1088                    name.len() + COLON.len() + header_value.len() + HTTP_BR.len();
1089            }
1090            match name.len() {
1091                10 if name.eq_ignore_ascii_case(CONNECTION) => {
1092                    has_connection = true;
1093                }
1094                12 if name.eq_ignore_ascii_case(CONTENT_TYPE) => {
1095                    has_content_type = true;
1096                    if let Some(value) = values.back() {
1097                        is_event_stream = value
1098                            .split(SEMICOLON)
1099                            .next()
1100                            .unwrap_or(EMPTY_STR)
1101                            .trim()
1102                            .eq_ignore_ascii_case(TEXT_EVENT_STREAM);
1103                    }
1104                }
1105                16 if name.eq_ignore_ascii_case(CONTENT_ENCODING) => {
1106                    compress_type = values
1107                        .back()
1108                        .map(|value: &String| value.parse::<Compress>().unwrap_or_default());
1109                }
1110                17 if name.eq_ignore_ascii_case(TRANSFER_ENCODING) => {
1111                    has_transfer_encoding = true;
1112                }
1113                _ => {}
1114            }
1115        }
1116        let is_bodyless: bool = (100..=199).contains(&status_code)
1117            || status_code == HttpStatus::NoContent.code()
1118            || status_code == HttpStatus::ResetContent.code()
1119            || status_code == HttpStatus::NotModified.code();
1120        let mut compressed_body: Option<Vec<u8>> = None;
1121        let mut emit_content_length: Option<usize> = None;
1122        let mut skip_wire_cl: bool = false;
1123        let mut skip_wire_te: bool = false;
1124        let body: &[u8] = if POPULATE_HEADERS {
1125            if !has_connection {
1126                self.set_header_without_check(CONNECTION, KEEP_ALIVE);
1127            }
1128            match status_code {
1129                100..=199 | 204 | 205 | 304 => {
1130                    self.clear_framing_headers();
1131                    if status_code == HttpStatus::ResetContent.code() {
1132                        self.set_header_without_check(CONTENT_LENGTH, ZERO_STR);
1133                    }
1134                    &[]
1135                }
1136                _ => {
1137                    if !has_content_type {
1138                        self.set_header_without_check(CONTENT_TYPE, default_content_type());
1139                    }
1140                    if INCLUDE_BODY {
1141                        if let Some(encoding) = compress_type
1142                            && !encoding.is_unknown()
1143                        {
1144                            let mut buf: Vec<u8> = take_compress_buffer();
1145                            let _: bool = encoding.encode_into(self.get_body(), &mut buf);
1146                            compressed_body = Some(buf);
1147                        }
1148                        if has_transfer_encoding {
1149                            self.get_mut_headers().retain(
1150                                |name: &String, _: &mut VecDeque<String>| {
1151                                    !name.eq_ignore_ascii_case(CONTENT_LENGTH)
1152                                },
1153                            );
1154                        } else if !is_event_stream {
1155                            if has_non_canonical_cl {
1156                                self.get_mut_headers().retain(
1157                                    |name: &String, _: &mut VecDeque<String>| {
1158                                        name == CONTENT_LENGTH
1159                                            || !name.eq_ignore_ascii_case(CONTENT_LENGTH)
1160                                    },
1161                                );
1162                            }
1163                            let body_len: usize = compressed_body
1164                                .as_ref()
1165                                .map_or_else(|| self.get_body().len(), Vec::len);
1166                            self.set_wire_content_length(body_len);
1167                        }
1168                        compressed_body
1169                            .as_deref()
1170                            .unwrap_or_else(|| self.get_body().as_slice())
1171                    } else {
1172                        self.clear_framing_headers();
1173                        let body_len: usize = self.get_body().len();
1174                        if body_len != 0
1175                            && !is_event_stream
1176                            && !compress_type
1177                                .is_some_and(|encoding: Compress| !encoding.is_unknown())
1178                        {
1179                            self.set_wire_content_length(body_len);
1180                        }
1181                        &[]
1182                    }
1183                }
1184            }
1185        } else if is_bodyless {
1186            skip_wire_cl = true;
1187            skip_wire_te = true;
1188            if status_code == HttpStatus::ResetContent.code() {
1189                emit_content_length = Some(0);
1190            }
1191            &[]
1192        } else if INCLUDE_BODY {
1193            if let Some(encoding) = compress_type
1194                && !encoding.is_unknown()
1195            {
1196                let mut buf: Vec<u8> = take_compress_buffer();
1197                let _: bool = encoding.encode_into(self.get_body(), &mut buf);
1198                compressed_body = Some(buf);
1199            }
1200            if has_transfer_encoding {
1201                skip_wire_cl = true;
1202            } else if !is_event_stream {
1203                let body_len: usize = compressed_body
1204                    .as_ref()
1205                    .map_or_else(|| self.get_body().len(), Vec::len);
1206                skip_wire_cl = true;
1207                emit_content_length = Some(body_len);
1208            }
1209            compressed_body
1210                .as_deref()
1211                .unwrap_or_else(|| self.get_body().as_slice())
1212        } else {
1213            skip_wire_cl = true;
1214            skip_wire_te = true;
1215            let body_len: usize = self.get_body().len();
1216            if body_len != 0
1217                && !is_event_stream
1218                && !compress_type.is_some_and(|encoding: Compress| !encoding.is_unknown())
1219            {
1220                emit_content_length = Some(body_len);
1221            }
1222            &[]
1223        };
1224        let extra_default_bytes: usize = if POPULATE_HEADERS {
1225            FAST_CONNECTION_KEEP_ALIVE_LINE.len()
1226                + FAST_DEFAULT_CONTENT_TYPE_LINE.len()
1227                + FAST_CONTENT_LENGTH_PREFIX.len()
1228                + B_20
1229                + HTTP_BR.len()
1230        } else {
1231            let mut extra: usize = 0;
1232            if !has_connection {
1233                extra += FAST_CONNECTION_KEEP_ALIVE_LINE.len();
1234            }
1235            if !is_bodyless && !has_content_type {
1236                extra += FAST_DEFAULT_CONTENT_TYPE_LINE.len();
1237            }
1238            if emit_content_length.is_some() {
1239                extra += FAST_CONTENT_LENGTH_PREFIX.len() + B_20 + HTTP_BR.len();
1240            }
1241            extra
1242        };
1243        let head_size: usize = self.get_reason_phrase().len()
1244            + B_16
1245            + HTTP_BR.len()
1246            + existing_headers_bytes
1247            + extra_default_bytes;
1248        out.reserve(head_size + body.len());
1249        let fast_status_line: Option<&[u8]> = if is_default_ok {
1250            match self.get_version() {
1251                HttpVersion::Http1_1 => Some(FAST_HTTP11_200_LINE),
1252                HttpVersion::Http2 => Some(FAST_HTTP2_200_LINE),
1253                HttpVersion::Http3 => Some(FAST_HTTP3_200_LINE),
1254                _ => None,
1255            }
1256        } else {
1257            None
1258        };
1259        if let Some(status_line) = fast_status_line {
1260            out.extend_from_slice(status_line);
1261        } else {
1262            let raw_version: &str = self.get_version().as_str();
1263            let version_str: &str = if !matches!(self.get_version(), HttpVersion::Unknown(_))
1264                || Self::is_valid_http_version(raw_version)
1265            {
1266                raw_version
1267            } else {
1268                HTTP_VERSION_1_1
1269            };
1270            out.extend_from_slice(version_str.as_bytes());
1271            out.push(b' ');
1272            let mut code: [u8; B_20] = [0; B_20];
1273            out.extend_from_slice(render_length(status_code, &mut code).as_bytes());
1274            out.push(b' ');
1275            out.extend_from_slice(self.get_reason_phrase().as_bytes());
1276            out.extend_from_slice(HTTP_BR.as_bytes());
1277        }
1278        for (header_key, header_values) in self.get_headers().iter() {
1279            if !POPULATE_HEADERS {
1280                if skip_wire_cl
1281                    && header_key.len() == 14
1282                    && header_key.eq_ignore_ascii_case(CONTENT_LENGTH)
1283                {
1284                    continue;
1285                }
1286                if skip_wire_te
1287                    && header_key.len() == 17
1288                    && header_key.eq_ignore_ascii_case(TRANSFER_ENCODING)
1289                {
1290                    continue;
1291                }
1292            }
1293            if !Self::is_valid_header_name(header_key) {
1294                continue;
1295            }
1296            for header_value in header_values.iter() {
1297                if Self::is_valid_header_value(header_value) {
1298                    Self::push_header(out, header_key, header_value);
1299                }
1300            }
1301        }
1302        if !POPULATE_HEADERS {
1303            if !has_connection {
1304                out.extend_from_slice(FAST_CONNECTION_KEEP_ALIVE_LINE);
1305            }
1306            if !is_bodyless && !has_content_type {
1307                out.extend_from_slice(FAST_DEFAULT_CONTENT_TYPE_LINE);
1308            }
1309            if let Some(body_len) = emit_content_length {
1310                if body_len == 0 {
1311                    out.extend_from_slice(FAST_CONTENT_LENGTH_ZERO_LINE);
1312                } else {
1313                    let mut cl_digits: [u8; B_20] = [0; B_20];
1314                    let rendered: &str = render_length(body_len, &mut cl_digits);
1315                    out.extend_from_slice(FAST_CONTENT_LENGTH_PREFIX);
1316                    out.extend_from_slice(rendered.as_bytes());
1317                    out.extend_from_slice(HTTP_BR.as_bytes());
1318                }
1319            }
1320        }
1321        out.extend_from_slice(HTTP_BR.as_bytes());
1322        out.extend_from_slice(body);
1323        if let Some(buf) = compressed_body {
1324            return_compress_buffer(buf);
1325        }
1326    }
1327
1328    /// Populates the three default wire headers using one thread-local pool lookup.
1329    ///
1330    /// # Arguments
1331    ///
1332    /// - `&str` - The default content type value.
1333    /// - `&str` - The decimal body length string.
1334    #[inline(always)]
1335    fn populate_default_headers_batch(&mut self, content_type: &str, rendered_len: &str) {
1336        let headers: &mut ResponseHeaders = self.get_mut_headers();
1337        let pairs: [(&str, &str); 3] = [
1338            (CONNECTION, KEEP_ALIVE),
1339            (CONTENT_TYPE, content_type),
1340            (CONTENT_LENGTH, rendered_len),
1341        ];
1342        HEADER_ENTRY_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
1343            let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
1344            for (key, value) in pairs {
1345                let (mut name, mut values): (String, VecDeque<String>) = pool
1346                    .pop()
1347                    .unwrap_or_else(|| (String::new(), VecDeque::new()));
1348                name.clear();
1349                name.push_str(key);
1350                if values.len() == 1 {
1351                    values[0].clear();
1352                    values[0].push_str(value);
1353                } else {
1354                    while values.len() > 1 {
1355                        values.pop_back();
1356                    }
1357                    if let Some(slot) = values.front_mut() {
1358                        slot.clear();
1359                        slot.push_str(value);
1360                    } else {
1361                        values.push_back(value.to_owned());
1362                    }
1363                }
1364                headers.insert(name, values);
1365            }
1366        });
1367    }
1368
1369    /// Sets the generated content length using a stack buffer.
1370    ///
1371    /// # Arguments
1372    ///
1373    /// - `usize` - The selected representation's length in bytes.
1374    #[inline(always)]
1375    fn set_wire_content_length(&mut self, body_len: usize) {
1376        let mut digits: [u8; B_20] = [0; B_20];
1377        let rendered: &str = render_length(body_len, &mut digits);
1378        self.set_header_without_check(CONTENT_LENGTH, rendered);
1379    }
1380}