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        value
433            .bytes()
434            .all(|byte: u8| HTTP_HEADER_VALUE_VALID_TABLE[byte as usize])
435    }
436
437    /// Validates whether an HTTP version token contains no whitespace or control bytes.
438    ///
439    /// # Arguments
440    ///
441    /// - `&str` - The HTTP version text to inspect.
442    ///
443    /// # Returns
444    ///
445    /// - `bool` - `true` if the version token is safe to emit on the status line.
446    #[inline(always)]
447    fn is_valid_http_version(version: &str) -> bool {
448        !version.is_empty()
449            && version
450                .bytes()
451                .all(|byte: u8| byte > SPACE_U8 && byte < HTTP_HEADER_DELETE)
452    }
453
454    /// Determines whether the header should be skipped during setting.
455    ///
456    /// # Arguments
457    ///
458    /// - `&str` - The header key to inspect.
459    ///
460    /// # Returns
461    ///
462    /// - `bool` - `true` if the header is invalid or framing-controlled, `false` otherwise.
463    #[inline(always)]
464    fn should_skip_header(&self, key: &str) -> bool {
465        !Self::is_valid_header_name(key) || key.eq_ignore_ascii_case(CONTENT_LENGTH)
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    fn set_header_without_check<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        let value: &str = value.as_ref();
488        if let Some(values) = self.get_mut_headers().get_mut(key) {
489            values.truncate(1);
490            if let Some(slot) = values.front_mut() {
491                slot.clear();
492                slot.push_str(value);
493            } else {
494                values.push_back(value.to_owned());
495            }
496            return self;
497        }
498        // A recycled entry carries the buffers of the name and of the value,
499        // so a response that sets the same headers over and over stops
500        // allocating for them.
501        let (mut name, mut values): (String, VecDeque<String>) =
502            take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
503        name.clear();
504        name.push_str(key);
505        // A recycled entry may carry the values of a header that was sent
506        // more than once. Those values belong to that header, so only the
507        // first one is kept and the rest are dropped.
508        while values.len() > 1 {
509            values.pop_back();
510        }
511        if values.is_empty() {
512            values.push_back(String::new());
513        }
514        if let Some(slot) = values.front_mut() {
515            slot.clear();
516            slot.push_str(value.as_ref());
517        }
518        self.get_mut_headers().insert(name, values);
519        self
520    }
521
522    /// Sets a header in the response, replacing any existing values.
523    ///
524    /// This function replaces all existing values for a header with a single new value.
525    ///
526    /// # Arguments
527    ///
528    /// - `K` - The header key, which must implement `AsRef<str>`.
529    /// - `V` - The header value, which must implement `AsRef<String>`.
530    ///
531    /// # Returns
532    ///
533    /// - `&mut Self` - A mutable reference to self for chaining.
534    #[inline(always)]
535    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
536    where
537        K: AsRef<str>,
538        V: AsRef<str>,
539    {
540        let key: &str = key.as_ref();
541        let value: &str = value.as_ref();
542        if self.should_skip_header(key) || !Self::is_valid_header_value(value) {
543            return self;
544        }
545        self.set_header_without_check(key, value)
546    }
547
548    /// Adds a header to the response.
549    ///
550    /// This function appends a value to the response headers.
551    /// If the header already exists, the new value will be added to the existing values.
552    ///
553    /// # Arguments
554    ///
555    /// - `K` - The header key, which must implement `AsRef<str>`.
556    /// - `V` - The header value, which must implement `AsRef<String>`.
557    ///
558    /// # Returns
559    ///
560    /// - `&mut Self` - A mutable reference to self for chaining.
561    #[inline(always)]
562    pub fn add_header<K, V>(&mut self, key: K, value: V) -> &mut Self
563    where
564        K: AsRef<str>,
565        V: AsRef<str>,
566    {
567        let key_ref: &str = key.as_ref();
568        let value_ref: &str = value.as_ref();
569        if self.should_skip_header(key_ref) || !Self::is_valid_header_value(value_ref) {
570            return self;
571        }
572        if let Some(existing) = self.get_mut_headers().get_mut(key_ref) {
573            existing.push_back(value_ref.to_owned());
574            return self;
575        }
576        let (mut name, mut values): (String, VecDeque<String>) =
577            take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
578        name.clear();
579        name.push_str(key_ref);
580        while values.len() > 1 {
581            values.pop_back();
582        }
583        if let Some(slot) = values.front_mut() {
584            slot.clear();
585            slot.push_str(value_ref);
586        } else {
587            values.push_back(value_ref.to_owned());
588        }
589        self.get_mut_headers().insert(name, values);
590        self
591    }
592
593    /// Removes a header from the response.
594    ///
595    /// This function removes all values for the specified header key.
596    ///
597    /// # Arguments
598    ///
599    /// - `K` - The header key to remove, which must implement `AsRef<str>`.
600    ///
601    /// # Returns
602    ///
603    /// - `&mut Self` - A mutable reference to self for chaining.
604    #[inline(always)]
605    pub fn remove_header<K>(&mut self, key: K) -> &mut Self
606    where
607        K: AsRef<str>,
608    {
609        let _: bool = self.get_mut_headers().remove(key.as_ref()).is_some();
610        self
611    }
612
613    /// Removes a specific value from a header in the response.
614    ///
615    /// This function removes only the specified value from the header.
616    /// If the header has multiple values, only the matching value is removed.
617    /// If this was the last value for the header, the entire header is removed.
618    ///
619    /// # Arguments
620    ///
621    /// - `K` - The header key, which must implement `AsRef<str>`.
622    /// - `V` - The value to remove, which must implement `AsRef<String>`.
623    ///
624    /// # Returns
625    ///
626    /// - `&mut Self` - A mutable reference to self for chaining.
627    #[inline(always)]
628    pub fn remove_header_value<K, V>(&mut self, key: K, value: V) -> &mut Self
629    where
630        K: AsRef<str>,
631        V: AsRef<str>,
632    {
633        let key_ref: &str = key.as_ref();
634        let value_ref: &str = value.as_ref();
635        let should_remove: bool = if let Some(values) = self.get_mut_headers().get_mut(key_ref) {
636            values.retain(|data: &String| data != value_ref);
637            values.is_empty()
638        } else {
639            false
640        };
641        if should_remove {
642            self.get_mut_headers().remove(key_ref);
643        }
644        self
645    }
646
647    /// Clears all headers from the response.
648    ///
649    /// This function removes all headers, leaving the headers map empty.
650    ///
651    /// # Returns
652    ///
653    /// - `&mut Self` - A mutable reference to self for chaining.
654    #[inline(always)]
655    pub fn clear_headers(&mut self) -> &mut Self {
656        self.recycle_headers();
657        self
658    }
659
660    /// Resets the response to its default state while retaining allocated capacity.
661    ///
662    /// This keeps the header map and body allocations so persistent
663    /// (keep-alive) connections avoid repeated allocation per request.
664    ///
665    /// # Returns
666    ///
667    /// - `&mut Self` - A mutable reference to self for chaining.
668    pub fn reset(&mut self) -> &mut Self {
669        let http_status: HttpStatus = HttpStatus::default();
670        self.set_version(HttpVersion::Http1_1);
671        self.set_status_code(http_status.code());
672        let phrase: &'static str = HttpStatus::phrase_ref(http_status.code());
673        let stored: &mut String = self.get_mut_reason_phrase();
674        if stored.as_str() != phrase {
675            stored.clear();
676            stored.push_str(phrase);
677        }
678        self.recycle_headers();
679        self.get_mut_body().clear();
680        self
681    }
682
683    /// Hands the header entries to the pool and empties the header map.
684    ///
685    /// The map ends up empty, exactly as clearing it would, but the name and
686    /// the value buffers of every header survive in the pool. The next
687    /// response reuses them instead of allocating new ones.
688    ///
689    /// # Returns
690    ///
691    /// - `()` - The headers have been recycled.
692    fn recycle_headers(&mut self) {
693        let headers: &mut ResponseHeaders = self.get_mut_headers();
694        if headers.is_empty() {
695            return;
696        }
697        return_header_entries(headers.drain());
698    }
699
700    /// Tries to parse cookies from the `Set-Cookie` header.
701    ///
702    /// This method retrieves the last `Set-Cookie` header value and parses it
703    /// into a collection of key-value pairs representing the cookies.
704    ///
705    /// # Returns
706    ///
707    /// - `Option<HashMapXxHash3_64<String, String>>` - The parsed cookies if the `Set-Cookie` header exists, otherwise `None`.
708    #[inline(always)]
709    pub fn try_get_cookies(&self) -> Option<HashMapXxHash3_64<String, String>> {
710        let mut cookies: HashMapXxHash3_64<String, String> = hash_map_xx_hash3_64();
711        let mut found_header: bool = false;
712        for (name, values) in self.get_headers() {
713            if !name.eq_ignore_ascii_case(SET_COOKIE) {
714                continue;
715            }
716            for header_value in values {
717                found_header = true;
718                let parsed: CookieBuilder = CookieBuilder::parse(header_value);
719                if !parsed.get_name().is_empty() {
720                    cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
721                }
722            }
723        }
724        found_header.then_some(cookies)
725    }
726
727    /// Parses cookies from the `Set-Cookie` headers.
728    ///
729    /// This method retrieves all `Set-Cookie` header values and parses each one
730    /// into a collection of key-value pairs representing the cookies.
731    ///
732    /// # Returns
733    ///
734    /// - `HashMapXxHash3_64<String, String>` - The parsed cookies.
735    ///
736    /// # Panics
737    ///
738    /// This function will panic if the `Set-Cookie` header is not found.
739    #[inline(always)]
740    pub fn get_cookies(&self) -> HashMapXxHash3_64<String, String> {
741        self.try_get_cookies().unwrap()
742    }
743
744    /// Tries to get a cookie value by its key from `Set-Cookie` headers.
745    ///
746    /// This method parses the cookies from all `Set-Cookie` headers,
747    /// then attempts to retrieve the value for the specified key.
748    ///
749    /// # Arguments
750    ///
751    /// - `K` - The cookie key, which implements `AsRef<str>`.
752    ///
753    /// # Returns
754    ///
755    /// - `Option<String>` - The cookie value if exists.
756    #[inline(always)]
757    pub fn try_get_cookie<K>(&self, key: K) -> Option<String>
758    where
759        K: AsRef<str>,
760    {
761        self.try_get_cookies()
762            .and_then(|cookies: HashMapXxHash3_64<String, String>| {
763                cookies.get(key.as_ref()).cloned()
764            })
765    }
766
767    /// Gets a cookie value by its key from `Set-Cookie` headers.
768    ///
769    /// This method parses the cookies from all `Set-Cookie` headers,
770    /// then retrieves the value for the specified key.
771    ///
772    /// # Arguments
773    ///
774    /// - `K` - The cookie key, which implements `AsRef<str>`.
775    ///
776    /// # Returns
777    ///
778    /// - `String` - The cookie value.
779    ///
780    /// # Panics
781    ///
782    /// This function will panic if the `Set-Cookie` header is not found
783    /// or the cookie key does not exist.
784    #[inline(always)]
785    pub fn get_cookie<K>(&self, key: K) -> String
786    where
787        K: AsRef<str>,
788    {
789        self.try_get_cookie(key).unwrap()
790    }
791
792    /// Removes framing fields before a header-only response is serialized.
793    #[cold]
794    fn clear_framing_headers(&mut self) {
795        self.get_mut_headers()
796            .retain(|name: &String, _: &mut VecDeque<String>| {
797                !name.eq_ignore_ascii_case(CONTENT_LENGTH)
798                    && !name.eq_ignore_ascii_case(TRANSFER_ENCODING)
799            });
800    }
801
802    /// Builds the full HTTP response as a byte vector.
803    ///
804    /// This method constructs the complete HTTP response, including the status line,
805    /// headers, and body. It handles content encoding, content type, connection
806    /// management, and content length.
807    /// Informational, 204, 205, and 304 responses never serialize the body.
808    /// A 205 response declares a zero length; the other bodyless statuses
809    /// omit framing headers. For 304, the body cannot establish the length
810    /// of the selected representation.
811    ///
812    /// # Returns
813    ///
814    /// - `Vec<u8>` - The complete HTTP response bytes.
815    #[inline]
816    pub fn build(&mut self) -> Vec<u8> {
817        Self::build_wire::<true>(self)
818    }
819
820    /// Builds an HTTP response to `HEAD` without serializing or compressing its body.
821    ///
822    /// Set the body to the matching `GET` representation if its length is known.
823    /// An empty buffer, an event stream, or a body that would be compressed does
824    /// not establish that length, so the generated response omits it.
825    ///
826    /// # Returns
827    ///
828    /// - `Vec<u8>` - The status line and headers ending at the header terminator.
829    #[must_use]
830    pub fn build_head(&mut self) -> Vec<u8> {
831        Self::build_wire::<false>(self)
832    }
833
834    /// Serializes either a full response or the header-only response to `HEAD`.
835    ///
836    /// # Returns
837    ///
838    /// - `Vec<u8>` - The encoded HTTP response.
839    fn build_wire<const INCLUDE_BODY: bool>(&mut self) -> Vec<u8> {
840        let status_code: usize = self.get_status_code();
841        let is_default_ok: bool =
842            status_code == HttpStatus::Ok.code() && self.get_reason_phrase().as_str() == OK;
843        if !is_default_ok
844            && (self.get_reason_phrase().is_empty()
845                || self.get_reason_phrase().as_str() == OK
846                || !Self::is_valid_header_value(self.get_reason_phrase()))
847        {
848            // The phrase is written into the existing buffer rather than
849            // replaced, so a response that announces the same status over and
850            // over stops allocating for it.
851            let phrase: &'static str = HttpStatus::phrase_ref(status_code);
852            if self.get_reason_phrase().as_str() != phrase {
853                let stored: &mut String = self.get_mut_reason_phrase();
854                stored.clear();
855                stored.push_str(phrase);
856            }
857        }
858        if INCLUDE_BODY
859            && self.get_headers().is_empty()
860            && status_code >= HttpStatus::Ok.code()
861            && status_code != HttpStatus::NoContent.code()
862            && status_code != HttpStatus::ResetContent.code()
863            && status_code != HttpStatus::NotModified.code()
864        {
865            let content_type: &str = default_content_type();
866            let body_len: usize = self.get_body().len();
867            let mut digits: [u8; B_20] = [0; B_20];
868            let rendered_len: &str = render_length(body_len, &mut digits);
869            let fast_prefix: Option<&[u8]> = if is_default_ok {
870                match self.get_version() {
871                    HttpVersion::Http1_1 => Some(FAST_HTTP11_200_CL_PREFIX),
872                    HttpVersion::Http2 => Some(FAST_HTTP2_200_CL_PREFIX),
873                    HttpVersion::Http3 => Some(FAST_HTTP3_200_CL_PREFIX),
874                    _ => None,
875                }
876            } else {
877                None
878            };
879            let body_slice: &[u8] = self.get_body().as_slice();
880            let response_bytes: Vec<u8> = if let Some(prefix) = fast_prefix {
881                let prefix_len: usize = prefix.len();
882                let digits_bytes: &[u8] = rendered_len.as_bytes();
883                let digits_len: usize = digits_bytes.len();
884                let suffix_len: usize = FAST_DEFAULT_HEADERS_SUFFIX.len();
885                let total_size: usize = prefix_len + digits_len + suffix_len + body_len;
886                let mut out: Vec<u8> = Vec::with_capacity(total_size);
887                // SAFETY: `out` has capacity >= `total_size`; we copy four contiguous non-overlapping
888                // regions covering exactly `0..total_size` and then set length to `total_size`.
889                unsafe {
890                    let mut dst: *mut u8 = out.as_mut_ptr();
891                    ptr::copy_nonoverlapping(prefix.as_ptr(), dst, prefix_len);
892                    dst = dst.add(prefix_len);
893                    ptr::copy_nonoverlapping(digits_bytes.as_ptr(), dst, digits_len);
894                    dst = dst.add(digits_len);
895                    ptr::copy_nonoverlapping(FAST_DEFAULT_HEADERS_SUFFIX.as_ptr(), dst, suffix_len);
896                    dst = dst.add(suffix_len);
897                    if body_len > 0 {
898                        ptr::copy_nonoverlapping(body_slice.as_ptr(), dst, body_len);
899                    }
900                    out.set_len(total_size);
901                }
902                out
903            } else {
904                let raw_version: &str = self.get_version().as_str();
905                let version_str: &str = if !matches!(self.get_version(), HttpVersion::Unknown(_))
906                    || Self::is_valid_http_version(raw_version)
907                {
908                    raw_version
909                } else {
910                    HTTP_VERSION_1_1
911                };
912                let phrase_str: &str = self.get_reason_phrase().as_str();
913                let mut code_digits: [u8; B_20] = [0; B_20];
914                let rendered_code: &str = render_length(status_code, &mut code_digits);
915                let total_size: usize = version_str.len()
916                    + 1
917                    + rendered_code.len()
918                    + 1
919                    + phrase_str.len()
920                    + FAST_CL_PREFIX.len()
921                    + rendered_len.len()
922                    + FAST_DEFAULT_HEADERS_SUFFIX.len()
923                    + body_len;
924                let mut out: Vec<u8> = Vec::with_capacity(total_size);
925                out.extend_from_slice(version_str.as_bytes());
926                out.push(b' ');
927                out.extend_from_slice(rendered_code.as_bytes());
928                out.push(b' ');
929                out.extend_from_slice(phrase_str.as_bytes());
930                out.extend_from_slice(FAST_CL_PREFIX);
931                out.extend_from_slice(rendered_len.as_bytes());
932                out.extend_from_slice(FAST_DEFAULT_HEADERS_SUFFIX);
933                out.extend_from_slice(body_slice);
934                out
935            };
936            self.populate_default_headers_batch(content_type, rendered_len);
937            return response_bytes;
938        }
939        let mut has_connection: bool = false;
940        let mut has_content_type: bool = false;
941        let mut is_event_stream: bool = false;
942        let mut has_transfer_encoding: bool = false;
943        let mut has_non_canonical_cl: bool = false;
944        let mut compress_type: Option<Compress> = None;
945        for (name, values) in self.get_headers() {
946            if name.len() == 14
947                && name != CONTENT_LENGTH
948                && name.eq_ignore_ascii_case(CONTENT_LENGTH)
949            {
950                has_non_canonical_cl = true;
951            }
952            if values.is_empty() {
953                continue;
954            }
955            match name.len() {
956                10 if name.eq_ignore_ascii_case(CONNECTION) => {
957                    has_connection = true;
958                }
959                12 if name.eq_ignore_ascii_case(CONTENT_TYPE) => {
960                    has_content_type = true;
961                    if let Some(value) = values.back() {
962                        is_event_stream = value
963                            .split(SEMICOLON)
964                            .next()
965                            .unwrap_or(EMPTY_STR)
966                            .trim()
967                            .eq_ignore_ascii_case(TEXT_EVENT_STREAM);
968                    }
969                }
970                16 if name.eq_ignore_ascii_case(CONTENT_ENCODING) => {
971                    compress_type = values
972                        .back()
973                        .map(|value: &String| value.parse::<Compress>().unwrap_or_default());
974                }
975                17 if name.eq_ignore_ascii_case(TRANSFER_ENCODING) => {
976                    has_transfer_encoding = true;
977                }
978                _ => {}
979            }
980        }
981        if !has_connection {
982            self.set_header_without_check(CONNECTION, KEEP_ALIVE);
983        }
984        let compressed_body: Option<Vec<u8>>;
985        let body: &[u8] = match status_code {
986            100..=199 | 204 | 205 | 304 => {
987                self.clear_framing_headers();
988                if status_code == HttpStatus::ResetContent.code() {
989                    self.set_header_without_check(CONTENT_LENGTH, ZERO_STR);
990                }
991                &[]
992            }
993            _ => {
994                if !has_content_type {
995                    self.set_header_without_check(CONTENT_TYPE, default_content_type());
996                }
997                if INCLUDE_BODY {
998                    compressed_body = match compress_type {
999                        Some(encoding) if !encoding.is_unknown() => Some(
1000                            encoding
1001                                .encode(self.get_body(), DEFAULT_BUFFER_SIZE)
1002                                .into_owned(),
1003                        ),
1004                        _ => None,
1005                    };
1006                    if has_transfer_encoding {
1007                        self.get_mut_headers()
1008                            .retain(|name: &String, _: &mut VecDeque<String>| {
1009                                !name.eq_ignore_ascii_case(CONTENT_LENGTH)
1010                            });
1011                    } else if !is_event_stream {
1012                        if has_non_canonical_cl {
1013                            self.get_mut_headers().retain(
1014                                |name: &String, _: &mut VecDeque<String>| {
1015                                    name == CONTENT_LENGTH
1016                                        || !name.eq_ignore_ascii_case(CONTENT_LENGTH)
1017                                },
1018                            );
1019                        }
1020                        let body_len: usize = compressed_body
1021                            .as_ref()
1022                            .map_or_else(|| self.get_body().len(), Vec::len);
1023                        self.set_wire_content_length(body_len);
1024                    }
1025                    compressed_body
1026                        .as_deref()
1027                        .unwrap_or_else(|| self.get_body().as_slice())
1028                } else {
1029                    self.clear_framing_headers();
1030                    let body_len: usize = self.get_body().len();
1031                    if body_len != 0
1032                        && !is_event_stream
1033                        && !compress_type.is_some_and(|encoding: Compress| !encoding.is_unknown())
1034                    {
1035                        self.set_wire_content_length(body_len);
1036                    }
1037                    &[]
1038                }
1039            }
1040        };
1041        let mut head_size: usize = self.get_reason_phrase().len() + B_16 + HTTP_BR.len();
1042        head_size += self
1043            .get_headers()
1044            .iter()
1045            .map(|header_entry: (&String, &VecDeque<String>)| {
1046                let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
1047                header_values
1048                    .iter()
1049                    .map(|header_value: &String| {
1050                        header_key.len() + COLON.len() + header_value.len() + HTTP_BR.len()
1051                    })
1052                    .sum::<usize>()
1053            })
1054            .sum::<usize>();
1055        let raw_version: &str = self.get_version().as_str();
1056        let version_str: &str = if Self::is_valid_http_version(raw_version) {
1057            raw_version
1058        } else {
1059            HTTP_VERSION_1_1
1060        };
1061        let mut response_bytes: Vec<u8> = Vec::with_capacity(head_size + body.len());
1062        response_bytes.extend_from_slice(version_str.as_bytes());
1063        response_bytes.push(b' ');
1064        let mut code: [u8; B_20] = [0; B_20];
1065        response_bytes.extend_from_slice(render_length(status_code, &mut code).as_bytes());
1066        response_bytes.push(b' ');
1067        response_bytes.extend_from_slice(self.get_reason_phrase().as_bytes());
1068        response_bytes.extend_from_slice(HTTP_BR.as_bytes());
1069        self.get_headers()
1070            .iter()
1071            .for_each(|header_entry: (&String, &VecDeque<String>)| {
1072                let (header_key, header_values): (&String, &VecDeque<String>) = header_entry;
1073                if !Self::is_valid_header_name(header_key) {
1074                    return;
1075                }
1076                for header_value in header_values.iter() {
1077                    if Self::is_valid_header_value(header_value) {
1078                        Self::push_header(&mut response_bytes, header_key, header_value);
1079                    }
1080                }
1081            });
1082        response_bytes.extend_from_slice(HTTP_BR.as_bytes());
1083        response_bytes.extend_from_slice(body);
1084        response_bytes
1085    }
1086
1087    /// Populates the three default wire headers using one thread-local pool lookup.
1088    ///
1089    /// # Arguments
1090    ///
1091    /// - `&str` - The default content type value.
1092    /// - `&str` - The decimal body length string.
1093    #[inline(always)]
1094    fn populate_default_headers_batch(&mut self, content_type: &str, rendered_len: &str) {
1095        let headers: &mut ResponseHeaders = self.get_mut_headers();
1096        let pairs: [(&str, &str); 3] = [
1097            (CONNECTION, KEEP_ALIVE),
1098            (CONTENT_TYPE, content_type),
1099            (CONTENT_LENGTH, rendered_len),
1100        ];
1101        HEADER_ENTRY_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
1102            let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
1103            for (key, value) in pairs {
1104                let (mut name, mut values): (String, VecDeque<String>) = pool
1105                    .pop()
1106                    .unwrap_or_else(|| (String::new(), VecDeque::new()));
1107                name.clear();
1108                name.push_str(key);
1109                if values.len() == 1 {
1110                    values[0].clear();
1111                    values[0].push_str(value);
1112                } else {
1113                    while values.len() > 1 {
1114                        values.pop_back();
1115                    }
1116                    if let Some(slot) = values.front_mut() {
1117                        slot.clear();
1118                        slot.push_str(value);
1119                    } else {
1120                        values.push_back(value.to_owned());
1121                    }
1122                }
1123                headers.insert(name, values);
1124            }
1125        });
1126    }
1127
1128    /// Sets the generated content length using a stack buffer.
1129    ///
1130    /// # Arguments
1131    ///
1132    /// - `usize` - The selected representation's length in bytes.
1133    #[inline(always)]
1134    fn set_wire_content_length(&mut self, body_len: usize) {
1135        let mut digits: [u8; B_20] = [0; B_20];
1136        let rendered: &str = render_length(body_len, &mut digits);
1137        self.set_header_without_check(CONTENT_LENGTH, rendered);
1138    }
1139}