Skip to main content

http_request/response/
impl.rs

1use super::*;
2
3/// Default construction for [`HttpResponse`].
4impl Default for HttpResponse {
5    /// Returns the default `HttpResponse`.
6    ///
7    /// The status code and reason phrase fall back to `HttpStatus::Unknown`,
8    /// the header map is empty, and the body is empty.
9    fn default() -> Self {
10        Self {
11            version: HttpVersion::default(),
12            status_code: HttpStatus::Unknown.code(),
13            reason_phrase: HttpStatus::Unknown.to_string(),
14            headers: new_response_headers(),
15            body: ResponseBody::new(),
16        }
17    }
18}
19
20/// Inherent implementation of [`HttpResponse`].
21impl HttpResponse {
22    /// Construct from raw response bytes (status line + headers + body).
23    ///
24    /// # Arguments
25    ///
26    /// - `&[u8]` - The complete raw response bytes, including the status line,
27    ///   the header block, and the body.
28    pub fn from_bytes(response: &[u8]) -> Self {
29        let split_lines: Vec<&[u8]> = split_multi_byte(response, HTTP_BR_BYTES);
30        let mut lines: IntoIter<&[u8]> = split_lines.into_iter();
31        let status_line: &[u8] = lines.next().unwrap_or(&[]);
32        let status_parts: Vec<&[u8]> = split_whitespace(status_line);
33        let version: HttpVersion = status_parts
34            .first()
35            .and_then(|part: &&[u8]| from_utf8(part).ok())
36            .and_then(|version_str: &str| version_str.parse::<HttpVersion>().ok())
37            .unwrap_or_default();
38        let status_code: ResponseStatusCode = status_parts
39            .get(1)
40            .and_then(|part: &&[u8]| from_utf8(part).ok())
41            .and_then(|code_str: &str| code_str.parse().ok())
42            .unwrap_or(HttpStatus::Unknown.code());
43        let reason_phrase: String = status_parts.get(2..).map_or_else(
44            || HttpStatus::Unknown.to_string(),
45            |parts: &[&[u8]]| {
46                if parts.is_empty() {
47                    HttpStatus::Unknown.to_string()
48                } else if parts.len() == 1 {
49                    String::from_utf8_lossy(parts[0]).into_owned()
50                } else {
51                    let total_len: usize =
52                        parts.iter().map(|p: &&[u8]| p.len()).sum::<usize>() + parts.len() - 1;
53                    let mut result: String = String::with_capacity(total_len);
54                    for (i, part) in parts.iter().enumerate() {
55                        if i > 0 {
56                            result.push(' ');
57                        }
58                        result.push_str(&String::from_utf8_lossy(part));
59                    }
60                    result
61                }
62            },
63        );
64        let mut headers: HttpResponseHeaders = new_response_headers();
65        for line in lines.by_ref() {
66            if line.is_empty() {
67                break;
68            }
69            let mut colon_pos: Option<usize> = None;
70            for (i, &byte) in line.iter().enumerate() {
71                if byte == COLON_U8 {
72                    colon_pos = Some(i);
73                    break;
74                }
75            }
76            if let Some(pos) = colon_pos
77                && pos > 0
78                && pos + 1 < line.len()
79            {
80                let key_bytes: &[u8] = &line[..pos];
81                let value_start: usize = if line.get(pos + 1) == Some(&SPACE_U8) {
82                    pos + 2
83                } else {
84                    pos + 1
85                };
86                let value_bytes: &[u8] = &line[value_start..];
87                if let (Ok(key_str), Ok(value_str)) = (from_utf8(key_bytes), from_utf8(value_bytes))
88                {
89                    headers.insert(
90                        key_str.trim().to_ascii_lowercase(),
91                        value_str.trim().to_owned(),
92                    );
93                }
94            }
95        }
96        let body: ResponseBody = match lines.len() {
97            0 => ResponseBody::new(),
98            1 => {
99                let line: &[u8] = lines.next().unwrap_or(&[]);
100                line.to_vec()
101            }
102            _ => {
103                let lines_slice: &[&[u8]] = lines.as_slice();
104                let total_size: usize = lines_slice
105                    .iter()
106                    .map(|line: &&[u8]| line.len())
107                    .sum::<usize>()
108                    + lines_slice.len().saturating_sub(1) * BR_BYTES.len();
109                let mut body: ResponseBody = ResponseBody::with_capacity(total_size);
110                let mut first: bool = true;
111                for line in lines {
112                    if !first {
113                        body.extend_from_slice(BR_BYTES);
114                    }
115                    body.extend_from_slice(line);
116                    first = false;
117                }
118                body
119            }
120        };
121        HttpResponse {
122            version,
123            status_code,
124            reason_phrase,
125            headers,
126            body,
127        }
128    }
129
130    /// Was the response a 2xx success?
131    ///
132    /// # Returns
133    ///
134    /// - `bool` - `true` when the status code lies in the `200..300` range.
135    pub fn is_success(&self) -> bool {
136        (200..300).contains(&self.get_status_code())
137    }
138
139    /// Was the response a 3xx redirect?
140    ///
141    /// # Returns
142    ///
143    /// - `bool` - `true` when the status code lies in the `300..400` range.
144    pub fn is_redirect(&self) -> bool {
145        (300..400).contains(&self.get_status_code())
146    }
147
148    /// Was the response a 4xx client error?
149    ///
150    /// # Returns
151    ///
152    /// - `bool` - `true` when the status code lies in the `400..500` range.
153    pub fn is_client_error(&self) -> bool {
154        (400..500).contains(&self.get_status_code())
155    }
156
157    /// Was the response a 5xx server error?
158    ///
159    /// # Returns
160    ///
161    /// - `bool` - `true` when the status code lies in the `500..600` range.
162    pub fn is_server_error(&self) -> bool {
163        (500..600).contains(&self.get_status_code())
164    }
165
166    /// Look up a single header value (case-insensitive) without heap allocation for short keys.
167    ///
168    /// # Arguments
169    ///
170    /// - `K` - The header name to look up, matched case-insensitively.
171    ///
172    /// # Returns
173    ///
174    /// - `Option<&str>` - The header value, or `None` when the header is absent.
175    pub fn get_header<K>(&self, key: K) -> Option<&str>
176    where
177        K: AsRef<str>,
178    {
179        let raw: &str = key.as_ref();
180        let bytes: &[u8] = raw.as_bytes();
181        if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
182            return self.get_headers().get(raw).map(String::as_str);
183        }
184        if bytes.len() <= RESPONSE_HEADER_STACK_LIMIT {
185            let mut stack_buf: [u8; RESPONSE_HEADER_STACK_LIMIT] = [0; RESPONSE_HEADER_STACK_LIMIT];
186            for (idx, &byte) in bytes.iter().enumerate() {
187                stack_buf[idx] = byte.to_ascii_lowercase();
188            }
189            if let Ok(lower) = from_utf8(&stack_buf[..bytes.len()]) {
190                return self.get_headers().get(lower).map(String::as_str);
191            }
192        }
193        let normalized: String = raw.to_ascii_lowercase();
194        self.get_headers().get(&normalized).map(String::as_str)
195    }
196
197    /// Get the response body as a UTF-8 string (lossy on invalid bytes).
198    ///
199    /// # Returns
200    ///
201    /// - `String` - The owned body text, with invalid byte sequences replaced.
202    pub fn text(&self) -> String {
203        String::from_utf8_lossy(self.get_body()).into_owned()
204    }
205
206    /// Get the response body as raw bytes.
207    ///
208    /// # Returns
209    ///
210    /// - `&[u8]` - The raw, undecoded body bytes.
211    pub fn bytes(&self) -> &[u8] {
212        self.get_body()
213    }
214
215    /// Deserialize the response body from JSON into `T`.
216    ///
217    /// # Returns
218    ///
219    /// - `Result<T, serde_json::Error>` - Parsed JSON payload or a deserialization error.
220    pub fn json<T>(&self) -> Result<T, serde_json::Error>
221    where
222        T: DeserializeOwned,
223    {
224        from_slice(self.get_body())
225    }
226
227    /// Parses cookies declared by the response's `Set-Cookie` header, when present.
228    ///
229    /// # Returns
230    ///
231    /// - `Option<Cookies>` - Parsed cookie map, or `None` when `Set-Cookie` is absent.
232    pub fn try_get_cookies(&self) -> Option<Cookies> {
233        let header: &str = self.get_header(SET_COOKIE)?;
234        let parsed: CookieBuilder = CookieBuilder::parse(header);
235        let mut cookies: Cookies = hash_map_xx_hash3_64();
236        if !parsed.get_name().is_empty() {
237            cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
238        }
239        Some(cookies)
240    }
241
242    /// Decode the body using the headers' Content-Encoding (gzip / deflate /
243    /// br). Returns a fresh response with the decoded body — the original is
244    /// untouched. `buffer_size` controls the chunk size for streaming decoders.
245    ///
246    /// # Arguments
247    ///
248    /// - `usize` - The chunk size used by the streaming decoders.
249    ///
250    /// # Returns
251    ///
252    /// - `HttpResponse` - A new response identical to this one except that its
253    ///   body holds the decoded bytes.
254    pub fn decode(&self, buffer_size: usize) -> HttpResponse {
255        let decoded: ResponseBody = Compress::from(self.get_headers())
256            .decode(self.get_body(), buffer_size)
257            .into_owned();
258        HttpResponse {
259            version: self.get_version().clone(),
260            status_code: self.get_status_code(),
261            reason_phrase: self.get_reason_phrase().clone(),
262            headers: self.get_headers().clone(),
263            body: decoded,
264        }
265    }
266}