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: Vec::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        if response.is_empty() {
30            return Self::default();
31        }
32        let status_end: usize = find_crlf(response, 0).unwrap_or(response.len());
33        let status_line: &[u8] = &response[..status_end];
34        let sl_len: usize = status_line.len();
35        let mut idx: usize = 0;
36        while idx < sl_len && (status_line[idx] == SPACE_U8 || status_line[idx] == TAB_U8) {
37            idx += 1;
38        }
39        let v_start: usize = idx;
40        while idx < sl_len && status_line[idx] != SPACE_U8 && status_line[idx] != TAB_U8 {
41            idx += 1;
42        }
43        let version_bytes: &[u8] = &status_line[v_start..idx];
44        while idx < sl_len && (status_line[idx] == SPACE_U8 || status_line[idx] == TAB_U8) {
45            idx += 1;
46        }
47        let c_start: usize = idx;
48        while idx < sl_len && status_line[idx] != SPACE_U8 && status_line[idx] != TAB_U8 {
49            idx += 1;
50        }
51        let code_bytes: &[u8] = &status_line[c_start..idx];
52        while idx < sl_len && (status_line[idx] == SPACE_U8 || status_line[idx] == TAB_U8) {
53            idx += 1;
54        }
55        let mut r_end: usize = sl_len;
56        while r_end > idx
57            && (status_line[r_end - 1] == SPACE_U8 || status_line[r_end - 1] == TAB_U8)
58        {
59            r_end -= 1;
60        }
61        let reason_bytes: &[u8] = &status_line[idx..r_end];
62        let version: HttpVersion = if version_bytes.is_empty() {
63            HttpVersion::default()
64        } else if version_bytes == HTTP_VERSION_1_1.as_bytes() {
65            HttpVersion::Http1_1
66        } else if version_bytes == HTTP_VERSION_1_0.as_bytes() {
67            HttpVersion::Http1_0
68        } else if version_bytes == HTTP_VERSION_2.as_bytes() {
69            HttpVersion::Http2
70        } else {
71            from_utf8(version_bytes)
72                .ok()
73                .and_then(|version_str: &str| version_str.parse::<HttpVersion>().ok())
74                .unwrap_or_default()
75        };
76        let status_code: usize = if code_bytes.is_empty() {
77            HttpStatus::Unknown.code()
78        } else {
79            let mut parsed: usize = 0;
80            let mut valid: bool = true;
81            for &byte in code_bytes {
82                if byte.is_ascii_digit() {
83                    if let Some(next) = parsed
84                        .checked_mul(10)
85                        .and_then(|val: usize| val.checked_add((byte - ASCII_ZERO) as usize))
86                    {
87                        parsed = next;
88                    } else {
89                        valid = false;
90                        break;
91                    }
92                } else {
93                    valid = false;
94                    break;
95                }
96            }
97            if valid {
98                parsed
99            } else {
100                HttpStatus::Unknown.code()
101            }
102        };
103        let reason_phrase: String = if reason_bytes.is_empty() {
104            HttpStatus::Unknown.to_string()
105        } else {
106            let needs_ws_collapse: bool = reason_bytes.windows(2).any(|pair: &[u8]| {
107                pair[0] == TAB_U8
108                    || pair[1] == TAB_U8
109                    || (pair[0] == SPACE_U8 && pair[1] == SPACE_U8)
110            }) || reason_bytes[0] == TAB_U8;
111            if !needs_ws_collapse && let Ok(reason_str) = from_utf8(reason_bytes) {
112                reason_str.to_owned()
113            } else {
114                let mut result: String = String::with_capacity(reason_bytes.len());
115                let mut r_pos: usize = 0;
116                let mut first_word: bool = true;
117                while r_pos < reason_bytes.len() {
118                    while r_pos < reason_bytes.len()
119                        && (reason_bytes[r_pos] == SPACE_U8 || reason_bytes[r_pos] == TAB_U8)
120                    {
121                        r_pos += 1;
122                    }
123                    let w_start: usize = r_pos;
124                    while r_pos < reason_bytes.len()
125                        && reason_bytes[r_pos] != SPACE_U8
126                        && reason_bytes[r_pos] != TAB_U8
127                    {
128                        r_pos += 1;
129                    }
130                    if r_pos > w_start {
131                        if !first_word {
132                            result.push(' ');
133                        }
134                        first_word = false;
135                        result.push_str(&String::from_utf8_lossy(&reason_bytes[w_start..r_pos]));
136                    }
137                }
138                result
139            }
140        };
141        let mut pos: usize = if status_end < response.len() {
142            status_end + HTTP_BR_BYTES.len()
143        } else {
144            response.len()
145        };
146        let mut headers: HashMapXxHash3_64<String, String> =
147            if pos < response.len() && !response[pos..].starts_with(HTTP_BR_BYTES) {
148                HashMap::with_capacity_and_hasher(4, BuildHasherDefault::default())
149            } else {
150                new_response_headers()
151            };
152        let mut body_start: usize = response.len();
153        while pos < response.len() {
154            let line_end: usize = find_crlf(response, pos).unwrap_or(response.len());
155            let line: &[u8] = &response[pos..line_end];
156            let next_pos: usize = if line_end < response.len() {
157                line_end + HTTP_BR_BYTES.len()
158            } else {
159                response.len()
160            };
161            if line.is_empty() {
162                body_start = next_pos;
163                break;
164            }
165            if let Some(colon_pos) = line.iter().position(|byte: &u8| *byte == COLON_U8)
166                && colon_pos > 0
167                && colon_pos + 1 < line.len()
168            {
169                let key_bytes: &[u8] = &line[..colon_pos];
170                let value_start: usize = if line[colon_pos + 1] == SPACE_U8 {
171                    colon_pos + 2
172                } else {
173                    colon_pos + 1
174                };
175                let value_bytes: &[u8] = &line[value_start..];
176                if let (Ok(key_str), Ok(value_str)) = (from_utf8(key_bytes), from_utf8(value_bytes))
177                {
178                    headers.insert(
179                        key_str.trim().to_ascii_lowercase(),
180                        value_str.trim().to_owned(),
181                    );
182                }
183            }
184            pos = next_pos;
185        }
186        let body: Vec<u8> = if body_start >= response.len() {
187            Vec::new()
188        } else {
189            let body_slice: &[u8] = &response[body_start..];
190            if find_crlf(body_slice, 0).is_none() {
191                body_slice.to_vec()
192            } else {
193                let mut body_out: Vec<u8> = Vec::with_capacity(body_slice.len());
194                let mut cursor: usize = 0;
195                while let Some(crlf_pos) = find_crlf(body_slice, cursor) {
196                    body_out.extend_from_slice(&body_slice[cursor..crlf_pos]);
197                    cursor = crlf_pos + HTTP_BR_BYTES.len();
198                    if cursor < body_slice.len() {
199                        body_out.extend_from_slice(BR_BYTES);
200                    }
201                }
202                if cursor < body_slice.len() {
203                    body_out.extend_from_slice(&body_slice[cursor..]);
204                }
205                body_out
206            }
207        };
208        HttpResponse {
209            version,
210            status_code,
211            reason_phrase,
212            headers,
213            body,
214        }
215    }
216
217    /// Was the response a 2xx success?
218    ///
219    /// # Returns
220    ///
221    /// - `bool` - `true` when the status code lies in the `200..300` range.
222    pub fn is_success(&self) -> bool {
223        (200..300).contains(&self.get_status_code())
224    }
225
226    /// Was the response a 3xx redirect?
227    ///
228    /// # Returns
229    ///
230    /// - `bool` - `true` when the status code lies in the `300..400` range.
231    pub fn is_redirect(&self) -> bool {
232        (300..400).contains(&self.get_status_code())
233    }
234
235    /// Was the response a 4xx client error?
236    ///
237    /// # Returns
238    ///
239    /// - `bool` - `true` when the status code lies in the `400..500` range.
240    pub fn is_client_error(&self) -> bool {
241        (400..500).contains(&self.get_status_code())
242    }
243
244    /// Was the response a 5xx server error?
245    ///
246    /// # Returns
247    ///
248    /// - `bool` - `true` when the status code lies in the `500..600` range.
249    pub fn is_server_error(&self) -> bool {
250        (500..600).contains(&self.get_status_code())
251    }
252
253    /// Look up a single header value (case-insensitive) without heap allocation for short keys.
254    ///
255    /// # Arguments
256    ///
257    /// - `K` - The header name to look up, matched case-insensitively.
258    ///
259    /// # Returns
260    ///
261    /// - `Option<&str>` - The header value, or `None` when the header is absent.
262    pub fn get_header<K>(&self, key: K) -> Option<&str>
263    where
264        K: AsRef<str>,
265    {
266        let raw: &str = key.as_ref();
267        let bytes: &[u8] = raw.as_bytes();
268        if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
269            return self.get_headers().get(raw).map(String::as_str);
270        }
271        if bytes.len() <= RESPONSE_HEADER_STACK_LIMIT {
272            let mut stack_buf: [MaybeUninit<u8>; RESPONSE_HEADER_STACK_LIMIT] =
273                [const { MaybeUninit::uninit() }; RESPONSE_HEADER_STACK_LIMIT];
274            for (idx, &byte) in bytes.iter().enumerate() {
275                stack_buf[idx].write(byte.to_ascii_lowercase());
276            }
277            // SAFETY: Replacing ASCII uppercase bytes with ASCII lowercase preserves UTF-8 validity,
278            // and `0..bytes.len()` were initialized in the loop above.
279            let lower: &str = unsafe {
280                from_utf8_unchecked(slice::from_raw_parts(
281                    stack_buf.as_ptr().cast::<u8>(),
282                    bytes.len(),
283                ))
284            };
285            return self.get_headers().get(lower).map(String::as_str);
286        }
287        let normalized: String = raw.to_ascii_lowercase();
288        self.get_headers().get(&normalized).map(String::as_str)
289    }
290
291    /// Get the response body as a UTF-8 string (lossy on invalid bytes).
292    ///
293    /// # Returns
294    ///
295    /// - `String` - The owned body text, with invalid byte sequences replaced.
296    pub fn text(&self) -> String {
297        String::from_utf8_lossy(self.get_body()).into_owned()
298    }
299
300    /// Get the response body as raw bytes.
301    ///
302    /// # Returns
303    ///
304    /// - `&[u8]` - The raw, undecoded body bytes.
305    pub fn bytes(&self) -> &[u8] {
306        self.get_body()
307    }
308
309    /// Deserialize the response body from JSON into `T`.
310    ///
311    /// # Returns
312    ///
313    /// - `Result<T, serde_json::Error>` - Parsed JSON payload or a deserialization error.
314    pub fn json<T>(&self) -> Result<T, serde_json::Error>
315    where
316        T: DeserializeOwned,
317    {
318        from_slice(self.get_body())
319    }
320
321    /// Parses cookies declared by the response's `Set-Cookie` header, when present.
322    ///
323    /// # Returns
324    ///
325    /// - `Option<HashMapXxHash3_64<String, String>>` - Parsed cookie map, or `None` when `Set-Cookie` is absent.
326    pub fn try_get_cookies(&self) -> Option<HashMapXxHash3_64<String, String>> {
327        let header: &str = self.get_header(SET_COOKIE)?;
328        let parsed: CookieBuilder = CookieBuilder::parse(header);
329        let mut cookies: HashMapXxHash3_64<String, String> = hash_map_xx_hash3_64();
330        if !parsed.get_name().is_empty() {
331            cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
332        }
333        Some(cookies)
334    }
335
336    /// Decode the body using the headers' Content-Encoding (gzip / deflate /
337    /// br). Returns a fresh response with the decoded body — the original is
338    /// untouched. `buffer_size` controls the chunk size for streaming decoders.
339    ///
340    /// # Arguments
341    ///
342    /// - `usize` - The chunk size used by the streaming decoders.
343    ///
344    /// # Returns
345    ///
346    /// - `HttpResponse` - A new response identical to this one except that its
347    ///   body holds the decoded bytes.
348    pub fn decode(&self, buffer_size: usize) -> HttpResponse {
349        let decoded: Vec<u8> = Compress::from(self.get_headers())
350            .decode(self.get_body(), buffer_size)
351            .into_owned();
352        HttpResponse {
353            version: self.get_version().clone(),
354            status_code: self.get_status_code(),
355            reason_phrase: self.get_reason_phrase().clone(),
356            headers: self.get_headers().clone(),
357            body: decoded,
358        }
359    }
360
361    /// Decodes the response body in place when a supported `Content-Encoding` is present.
362    ///
363    /// Avoids cloning headers, reason phrase, and uncompressed body bytes when no content
364    /// decoding is required.
365    ///
366    /// # Arguments
367    ///
368    /// - `usize` - The chunk size used by the streaming decoders.
369    #[inline]
370    pub(crate) fn decode_in_place(&mut self, buffer_size: usize) {
371        let algo: Compress = Compress::from(self.get_headers());
372        if algo.is_unknown() {
373            return;
374        }
375        let decoded: Vec<u8> = algo.decode(self.get_body(), buffer_size).into_owned();
376        self.set_body(decoded);
377    }
378}