http-request 23.0.0

http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, automatic handling of redirects (including detecting redirect loops), and enhanced response body decoding (both automatic and manual), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects.
Documentation
use super::*;

/// Default construction for [`HttpResponse`].
impl Default for HttpResponse {
    /// Returns the default `HttpResponse`.
    ///
    /// The status code and reason phrase fall back to `HttpStatus::Unknown`,
    /// the header map is empty, and the body is empty.
    fn default() -> Self {
        Self {
            version: HttpVersion::default(),
            status_code: HttpStatus::Unknown.code(),
            reason_phrase: HttpStatus::Unknown.to_string(),
            headers: new_response_headers(),
            body: Vec::new(),
        }
    }
}

/// Inherent implementation of [`HttpResponse`].
impl HttpResponse {
    /// Construct from raw response bytes (status line + headers + body).
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - The complete raw response bytes, including the status line,
    ///   the header block, and the body.
    pub fn from_bytes(response: &[u8]) -> Self {
        if response.is_empty() {
            return Self::default();
        }
        let status_end: usize = find_crlf(response, 0).unwrap_or(response.len());
        let status_line: &[u8] = &response[..status_end];
        let sl_len: usize = status_line.len();
        let mut idx: usize = 0;
        while idx < sl_len && (status_line[idx] == SPACE_U8 || status_line[idx] == TAB_U8) {
            idx += 1;
        }
        let v_start: usize = idx;
        while idx < sl_len && status_line[idx] != SPACE_U8 && status_line[idx] != TAB_U8 {
            idx += 1;
        }
        let version_bytes: &[u8] = &status_line[v_start..idx];
        while idx < sl_len && (status_line[idx] == SPACE_U8 || status_line[idx] == TAB_U8) {
            idx += 1;
        }
        let c_start: usize = idx;
        while idx < sl_len && status_line[idx] != SPACE_U8 && status_line[idx] != TAB_U8 {
            idx += 1;
        }
        let code_bytes: &[u8] = &status_line[c_start..idx];
        while idx < sl_len && (status_line[idx] == SPACE_U8 || status_line[idx] == TAB_U8) {
            idx += 1;
        }
        let mut r_end: usize = sl_len;
        while r_end > idx
            && (status_line[r_end - 1] == SPACE_U8 || status_line[r_end - 1] == TAB_U8)
        {
            r_end -= 1;
        }
        let reason_bytes: &[u8] = &status_line[idx..r_end];
        let version: HttpVersion = if version_bytes.is_empty() {
            HttpVersion::default()
        } else if version_bytes == HTTP_VERSION_1_1.as_bytes() {
            HttpVersion::Http1_1
        } else if version_bytes == HTTP_VERSION_1_0.as_bytes() {
            HttpVersion::Http1_0
        } else if version_bytes == HTTP_VERSION_2.as_bytes() {
            HttpVersion::Http2
        } else {
            from_utf8(version_bytes)
                .ok()
                .and_then(|version_str: &str| version_str.parse::<HttpVersion>().ok())
                .unwrap_or_default()
        };
        let status_code: usize = if code_bytes.is_empty() {
            HttpStatus::Unknown.code()
        } else {
            let mut parsed: usize = 0;
            let mut valid: bool = true;
            for &byte in code_bytes {
                if byte.is_ascii_digit() {
                    if let Some(next) = parsed
                        .checked_mul(10)
                        .and_then(|val: usize| val.checked_add((byte - ASCII_ZERO) as usize))
                    {
                        parsed = next;
                    } else {
                        valid = false;
                        break;
                    }
                } else {
                    valid = false;
                    break;
                }
            }
            if valid {
                parsed
            } else {
                HttpStatus::Unknown.code()
            }
        };
        let reason_phrase: String = if reason_bytes.is_empty() {
            HttpStatus::Unknown.to_string()
        } else {
            let needs_ws_collapse: bool = reason_bytes.windows(2).any(|pair: &[u8]| {
                pair[0] == TAB_U8
                    || pair[1] == TAB_U8
                    || (pair[0] == SPACE_U8 && pair[1] == SPACE_U8)
            }) || reason_bytes[0] == TAB_U8;
            if !needs_ws_collapse && let Ok(reason_str) = from_utf8(reason_bytes) {
                reason_str.to_owned()
            } else {
                let mut result: String = String::with_capacity(reason_bytes.len());
                let mut r_pos: usize = 0;
                let mut first_word: bool = true;
                while r_pos < reason_bytes.len() {
                    while r_pos < reason_bytes.len()
                        && (reason_bytes[r_pos] == SPACE_U8 || reason_bytes[r_pos] == TAB_U8)
                    {
                        r_pos += 1;
                    }
                    let w_start: usize = r_pos;
                    while r_pos < reason_bytes.len()
                        && reason_bytes[r_pos] != SPACE_U8
                        && reason_bytes[r_pos] != TAB_U8
                    {
                        r_pos += 1;
                    }
                    if r_pos > w_start {
                        if !first_word {
                            result.push(' ');
                        }
                        first_word = false;
                        result.push_str(&String::from_utf8_lossy(&reason_bytes[w_start..r_pos]));
                    }
                }
                result
            }
        };
        let mut pos: usize = if status_end < response.len() {
            status_end + HTTP_BR_BYTES.len()
        } else {
            response.len()
        };
        let mut headers: HashMapXxHash3_64<String, String> =
            if pos < response.len() && !response[pos..].starts_with(HTTP_BR_BYTES) {
                HashMap::with_capacity_and_hasher(4, BuildHasherDefault::default())
            } else {
                new_response_headers()
            };
        let mut body_start: usize = response.len();
        while pos < response.len() {
            let line_end: usize = find_crlf(response, pos).unwrap_or(response.len());
            let line: &[u8] = &response[pos..line_end];
            let next_pos: usize = if line_end < response.len() {
                line_end + HTTP_BR_BYTES.len()
            } else {
                response.len()
            };
            if line.is_empty() {
                body_start = next_pos;
                break;
            }
            if let Some(colon_pos) = line.iter().position(|byte: &u8| *byte == COLON_U8)
                && colon_pos > 0
                && colon_pos + 1 < line.len()
            {
                let key_bytes: &[u8] = &line[..colon_pos];
                let value_start: usize = if line[colon_pos + 1] == SPACE_U8 {
                    colon_pos + 2
                } else {
                    colon_pos + 1
                };
                let value_bytes: &[u8] = &line[value_start..];
                if let (Ok(key_str), Ok(value_str)) = (from_utf8(key_bytes), from_utf8(value_bytes))
                {
                    headers.insert(
                        key_str.trim().to_ascii_lowercase(),
                        value_str.trim().to_owned(),
                    );
                }
            }
            pos = next_pos;
        }
        let body: Vec<u8> = if body_start >= response.len() {
            Vec::new()
        } else {
            let body_slice: &[u8] = &response[body_start..];
            if find_crlf(body_slice, 0).is_none() {
                body_slice.to_vec()
            } else {
                let mut body_out: Vec<u8> = Vec::with_capacity(body_slice.len());
                let mut cursor: usize = 0;
                while let Some(crlf_pos) = find_crlf(body_slice, cursor) {
                    body_out.extend_from_slice(&body_slice[cursor..crlf_pos]);
                    cursor = crlf_pos + HTTP_BR_BYTES.len();
                    if cursor < body_slice.len() {
                        body_out.extend_from_slice(BR_BYTES);
                    }
                }
                if cursor < body_slice.len() {
                    body_out.extend_from_slice(&body_slice[cursor..]);
                }
                body_out
            }
        };
        HttpResponse {
            version,
            status_code,
            reason_phrase,
            headers,
            body,
        }
    }

    /// Was the response a 2xx success?
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the status code lies in the `200..300` range.
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.get_status_code())
    }

    /// Was the response a 3xx redirect?
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the status code lies in the `300..400` range.
    pub fn is_redirect(&self) -> bool {
        (300..400).contains(&self.get_status_code())
    }

    /// Was the response a 4xx client error?
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the status code lies in the `400..500` range.
    pub fn is_client_error(&self) -> bool {
        (400..500).contains(&self.get_status_code())
    }

    /// Was the response a 5xx server error?
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the status code lies in the `500..600` range.
    pub fn is_server_error(&self) -> bool {
        (500..600).contains(&self.get_status_code())
    }

    /// Look up a single header value (case-insensitive) without heap allocation for short keys.
    ///
    /// # Arguments
    ///
    /// - `K` - The header name to look up, matched case-insensitively.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - The header value, or `None` when the header is absent.
    pub fn get_header<K>(&self, key: K) -> Option<&str>
    where
        K: AsRef<str>,
    {
        let raw: &str = key.as_ref();
        let bytes: &[u8] = raw.as_bytes();
        if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
            return self.get_headers().get(raw).map(String::as_str);
        }
        if bytes.len() <= RESPONSE_HEADER_STACK_LIMIT {
            let mut stack_buf: [MaybeUninit<u8>; RESPONSE_HEADER_STACK_LIMIT] =
                [const { MaybeUninit::uninit() }; RESPONSE_HEADER_STACK_LIMIT];
            for (idx, &byte) in bytes.iter().enumerate() {
                stack_buf[idx].write(byte.to_ascii_lowercase());
            }
            // SAFETY: Replacing ASCII uppercase bytes with ASCII lowercase preserves UTF-8 validity,
            // and `0..bytes.len()` were initialized in the loop above.
            let lower: &str = unsafe {
                from_utf8_unchecked(slice::from_raw_parts(
                    stack_buf.as_ptr().cast::<u8>(),
                    bytes.len(),
                ))
            };
            return self.get_headers().get(lower).map(String::as_str);
        }
        let normalized: String = raw.to_ascii_lowercase();
        self.get_headers().get(&normalized).map(String::as_str)
    }

    /// Get the response body as a UTF-8 string (lossy on invalid bytes).
    ///
    /// # Returns
    ///
    /// - `String` - The owned body text, with invalid byte sequences replaced.
    pub fn text(&self) -> String {
        String::from_utf8_lossy(self.get_body()).into_owned()
    }

    /// Get the response body as raw bytes.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - The raw, undecoded body bytes.
    pub fn bytes(&self) -> &[u8] {
        self.get_body()
    }

    /// Deserialize the response body from JSON into `T`.
    ///
    /// # Returns
    ///
    /// - `Result<T, serde_json::Error>` - Parsed JSON payload or a deserialization error.
    pub fn json<T>(&self) -> Result<T, serde_json::Error>
    where
        T: DeserializeOwned,
    {
        from_slice(self.get_body())
    }

    /// Parses cookies declared by the response's `Set-Cookie` header, when present.
    ///
    /// # Returns
    ///
    /// - `Option<HashMapXxHash3_64<String, String>>` - Parsed cookie map, or `None` when `Set-Cookie` is absent.
    pub fn try_get_cookies(&self) -> Option<HashMapXxHash3_64<String, String>> {
        let header: &str = self.get_header(SET_COOKIE)?;
        let parsed: CookieBuilder = CookieBuilder::parse(header);
        let mut cookies: HashMapXxHash3_64<String, String> = hash_map_xx_hash3_64();
        if !parsed.get_name().is_empty() {
            cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
        }
        Some(cookies)
    }

    /// Decode the body using the headers' Content-Encoding (gzip / deflate /
    /// br). Returns a fresh response with the decoded body — the original is
    /// untouched. `buffer_size` controls the chunk size for streaming decoders.
    ///
    /// # Arguments
    ///
    /// - `usize` - The chunk size used by the streaming decoders.
    ///
    /// # Returns
    ///
    /// - `HttpResponse` - A new response identical to this one except that its
    ///   body holds the decoded bytes.
    pub fn decode(&self, buffer_size: usize) -> HttpResponse {
        let decoded: Vec<u8> = Compress::from(self.get_headers())
            .decode(self.get_body(), buffer_size)
            .into_owned();
        HttpResponse {
            version: self.get_version().clone(),
            status_code: self.get_status_code(),
            reason_phrase: self.get_reason_phrase().clone(),
            headers: self.get_headers().clone(),
            body: decoded,
        }
    }

    /// Decodes the response body in place when a supported `Content-Encoding` is present.
    ///
    /// Avoids cloning headers, reason phrase, and uncompressed body bytes when no content
    /// decoding is required.
    ///
    /// # Arguments
    ///
    /// - `usize` - The chunk size used by the streaming decoders.
    #[inline]
    pub(crate) fn decode_in_place(&mut self, buffer_size: usize) {
        let algo: Compress = Compress::from(self.get_headers());
        if algo.is_unknown() {
            return;
        }
        let decoded: Vec<u8> = algo.decode(self.get_body(), buffer_size).into_owned();
        self.set_body(decoded);
    }
}