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                    let key_owned: String = key_str.trim().to_ascii_lowercase();
179                    let val_trimmed: &str = value_str.trim();
180                    if key_owned == SET_COOKIE
181                        && let Some(existing) = headers.get_mut(SET_COOKIE)
182                    {
183                        existing.push(SET_COOKIE_DELIMITER);
184                        existing.push_str(val_trimmed);
185                    } else {
186                        headers.insert(key_owned, val_trimmed.to_owned());
187                    }
188                }
189            }
190            pos = next_pos;
191        }
192        let body: Vec<u8> = if body_start >= response.len() {
193            Vec::new()
194        } else {
195            let body_slice: &[u8] = &response[body_start..];
196            if find_crlf(body_slice, 0).is_none() {
197                body_slice.to_vec()
198            } else {
199                let mut body_out: Vec<u8> = Vec::with_capacity(body_slice.len());
200                let mut cursor: usize = 0;
201                while let Some(crlf_pos) = find_crlf(body_slice, cursor) {
202                    body_out.extend_from_slice(&body_slice[cursor..crlf_pos]);
203                    cursor = crlf_pos + HTTP_BR_BYTES.len();
204                    if cursor < body_slice.len() {
205                        body_out.extend_from_slice(BR_BYTES);
206                    }
207                }
208                if cursor < body_slice.len() {
209                    body_out.extend_from_slice(&body_slice[cursor..]);
210                }
211                body_out
212            }
213        };
214        HttpResponse {
215            version,
216            status_code,
217            reason_phrase,
218            headers,
219            body,
220        }
221    }
222
223    /// Was the response a 1xx informational status?
224    ///
225    /// # Returns
226    ///
227    /// - `bool` - `true` when the status code lies in the `100..200` range.
228    #[inline]
229    pub fn is_informational(&self) -> bool {
230        (100..200).contains(&self.get_status_code())
231    }
232
233    /// Was the response a 2xx success?
234    ///
235    /// # Returns
236    ///
237    /// - `bool` - `true` when the status code lies in the `200..300` range.
238    pub fn is_success(&self) -> bool {
239        (200..300).contains(&self.get_status_code())
240    }
241
242    /// Was the response a 3xx redirect?
243    ///
244    /// # Returns
245    ///
246    /// - `bool` - `true` when the status code lies in the `300..400` range.
247    pub fn is_redirect(&self) -> bool {
248        (300..400).contains(&self.get_status_code())
249    }
250
251    /// Was the response a 4xx client error?
252    ///
253    /// # Returns
254    ///
255    /// - `bool` - `true` when the status code lies in the `400..500` range.
256    pub fn is_client_error(&self) -> bool {
257        (400..500).contains(&self.get_status_code())
258    }
259
260    /// Was the response a 5xx server error?
261    ///
262    /// # Returns
263    ///
264    /// - `bool` - `true` when the status code lies in the `500..600` range.
265    pub fn is_server_error(&self) -> bool {
266        (500..600).contains(&self.get_status_code())
267    }
268
269    /// Look up a single header value (case-insensitive) without heap allocation for short keys.
270    ///
271    /// # Arguments
272    ///
273    /// - `K` - The header name to look up, matched case-insensitively.
274    ///
275    /// # Returns
276    ///
277    /// - `Option<&str>` - The header value, or `None` when the header is absent.
278    pub fn get_header<K>(&self, key: K) -> Option<&str>
279    where
280        K: AsRef<str>,
281    {
282        let raw: &str = key.as_ref();
283        let bytes: &[u8] = raw.as_bytes();
284        if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
285            return self.get_headers().get(raw).map(String::as_str);
286        }
287        if bytes.len() <= RESPONSE_HEADER_STACK_LIMIT {
288            let mut stack_buf: [MaybeUninit<u8>; RESPONSE_HEADER_STACK_LIMIT] =
289                [const { MaybeUninit::uninit() }; RESPONSE_HEADER_STACK_LIMIT];
290            for (idx, &byte) in bytes.iter().enumerate() {
291                stack_buf[idx].write(byte.to_ascii_lowercase());
292            }
293            // SAFETY: Replacing ASCII uppercase bytes with ASCII lowercase preserves UTF-8 validity,
294            // and `0..bytes.len()` were initialized in the loop above.
295            let lower: &str = unsafe {
296                from_utf8_unchecked(slice::from_raw_parts(
297                    stack_buf.as_ptr().cast::<u8>(),
298                    bytes.len(),
299                ))
300            };
301            return self.get_headers().get(lower).map(String::as_str);
302        }
303        let normalized: String = raw.to_ascii_lowercase();
304        self.get_headers().get(&normalized).map(String::as_str)
305    }
306
307    /// Get the response body as a UTF-8 string (lossy on invalid bytes).
308    ///
309    /// # Returns
310    ///
311    /// - `String` - The owned body text, with invalid byte sequences replaced.
312    pub fn text(&self) -> String {
313        String::from_utf8_lossy(self.get_body()).into_owned()
314    }
315
316    /// Get the response body as raw bytes.
317    ///
318    /// # Returns
319    ///
320    /// - `&[u8]` - The raw, undecoded body bytes.
321    pub fn bytes(&self) -> &[u8] {
322        self.get_body()
323    }
324
325    /// Deserialize the response body from JSON into `T`.
326    ///
327    /// # Returns
328    ///
329    /// - `Result<T, serde_json::Error>` - Parsed JSON payload or a deserialization error.
330    pub fn json<T>(&self) -> Result<T, serde_json::Error>
331    where
332        T: DeserializeOwned,
333    {
334        from_slice(self.get_body())
335    }
336
337    /// Converts a `4xx` or `5xx` HTTP response into an error while returning `1xx`–`3xx` responses unchanged.
338    ///
339    /// # Returns
340    ///
341    /// - `Result<Self, RequestError>` - `Ok(self)` for status codes `< 400`, or `Err(RequestError)` otherwise.
342    #[inline]
343    pub fn error_for_status(self) -> Result<Self, RequestError> {
344        let code: usize = self.get_status_code();
345        if code >= 400 {
346            return Err(RequestError::Request(format!(
347                "HTTP status error: {code} {}",
348                self.get_reason_phrase()
349            )));
350        }
351        Ok(self)
352    }
353
354    /// Returns the `Content-Type` response header value when present.
355    ///
356    /// # Returns
357    ///
358    /// - `Option<&str>` - `Content-Type` header value, if present.
359    #[inline]
360    pub fn content_type(&self) -> Option<&str> {
361        self.get_header(CONTENT_TYPE)
362    }
363
364    /// Returns the parsed decimal `Content-Length` header value when present and valid.
365    ///
366    /// # Returns
367    ///
368    /// - `Option<usize>` - Declared byte length, if present and valid.
369    #[inline]
370    pub fn content_length(&self) -> Option<usize> {
371        self.get_header(CONTENT_LENGTH)?
372            .trim()
373            .parse::<usize>()
374            .ok()
375    }
376
377    /// Returns the `Location` response header value when present.
378    ///
379    /// # Returns
380    ///
381    /// - `Option<&str>` - Redirect or created-resource `Location` header, if present.
382    #[inline]
383    pub fn location(&self) -> Option<&str> {
384        self.get_header(LOCATION)
385    }
386
387    /// Borrows the response body as a strict UTF-8 `&str` without allocating.
388    ///
389    /// # Returns
390    ///
391    /// - `Result<&str, Utf8Error>` - Borrowed UTF-8 body text or decoding error.
392    #[inline]
393    pub fn text_strict(&self) -> Result<&str, Utf8Error> {
394        from_utf8(self.get_body())
395    }
396
397    /// Returns all raw `Set-Cookie` header lines received on this response.
398    ///
399    /// # Returns
400    ///
401    /// - `Vec<&str>` - Every individual `Set-Cookie` header value in arrival order.
402    pub fn set_cookies(&self) -> Vec<&str> {
403        let Some(raw) = self.get_header(SET_COOKIE) else {
404            return Vec::new();
405        };
406        raw.split(SET_COOKIE_DELIMITER)
407            .filter(|entry: &&str| !entry.is_empty())
408            .collect()
409    }
410
411    /// Parses all cookies declared by one or more `Set-Cookie` headers, when present.
412    ///
413    /// # Returns
414    ///
415    /// - `Option<HashMapXxHash3_64<String, String>>` - Parsed cookie map, or `None` when `Set-Cookie` is absent.
416    pub fn try_get_cookies(&self) -> Option<HashMapXxHash3_64<String, String>> {
417        let header: &str = self.get_header(SET_COOKIE)?;
418        let mut cookies: HashMapXxHash3_64<String, String> = hash_map_xx_hash3_64();
419        for line in header.split(SET_COOKIE_DELIMITER) {
420            if line.is_empty() {
421                continue;
422            }
423            let parsed: CookieBuilder = CookieBuilder::parse(line);
424            if !parsed.get_name().is_empty() {
425                cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
426            }
427        }
428        Some(cookies)
429    }
430
431    /// Decode the body using the headers' Content-Encoding (gzip / deflate /
432    /// br). Returns a fresh response with the decoded body — the original is
433    /// untouched. `buffer_size` controls the chunk size for streaming decoders.
434    ///
435    /// # Arguments
436    ///
437    /// - `usize` - The chunk size used by the streaming decoders.
438    ///
439    /// # Returns
440    ///
441    /// - `HttpResponse` - A new response identical to this one except that its
442    ///   body holds the decoded bytes.
443    pub fn decode(&self, buffer_size: usize) -> HttpResponse {
444        let decoded: Vec<u8> = Compress::from(self.get_headers())
445            .decode(self.get_body(), buffer_size)
446            .into_owned();
447        HttpResponse {
448            version: self.get_version().clone(),
449            status_code: self.get_status_code(),
450            reason_phrase: self.get_reason_phrase().clone(),
451            headers: self.get_headers().clone(),
452            body: decoded,
453        }
454    }
455
456    /// Decodes the response body in place when a supported `Content-Encoding` is present.
457    ///
458    /// Avoids cloning headers, reason phrase, and uncompressed body bytes when no content
459    /// decoding is required.
460    ///
461    /// # Arguments
462    ///
463    /// - `usize` - The chunk size used by the streaming decoders.
464    #[inline]
465    pub(crate) fn decode_in_place(&mut self, buffer_size: usize) {
466        let algo: Compress = Compress::from(self.get_headers());
467        if algo.is_unknown() {
468            return;
469        }
470        let decoded: Vec<u8> = algo.decode(self.get_body(), buffer_size).into_owned();
471        let Self { body, .. } = self;
472        *body = decoded;
473    }
474}