http-request 23.3.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::*;

/// Inherent implementation of [`ChunkedDecoder`].
impl ChunkedDecoder {
    /// Creates a fresh incremental chunked decoder.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized decoder positioned at byte offset `0`.
    #[inline(always)]
    pub(crate) fn new() -> Self {
        Self {
            cursor: 0,
            decoded: Vec::new(),
            wire_end: None,
        }
    }

    /// Incrementally parses newly arrived wire bytes starting from the saved cursor.
    ///
    /// Decodes complete chunks directly into the output buffer in a single O(N) pass,
    /// avoiding O(N^2) rescanning on multi-read chunked responses.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Complete raw body slice accumulated after the response head so far.
    ///
    /// # Returns
    ///
    /// - `Result<bool, RequestError>` - `Ok(true)` once the terminating chunk and trailers are complete.
    #[inline]
    pub(crate) fn advance(&mut self, body_bytes: &[u8]) -> Result<bool, RequestError> {
        let Self {
            cursor,
            decoded,
            wire_end,
        } = self;
        if wire_end.is_some() {
            return Ok(true);
        }
        while *cursor < body_bytes.len() {
            let Some(line_end) = find_crlf(body_bytes, *cursor) else {
                return Ok(false);
            };
            let chunk_size: usize = parse_chunk_size(&body_bytes[*cursor..line_end])?;
            let data_start: usize = line_end + HTTP_BR_BYTES.len();
            if chunk_size == 0 {
                if body_bytes[data_start..].starts_with(HTTP_CARRIAGE_RETURN_LINE_FEED) {
                    let end: usize = data_start + HTTP_BR_BYTES.len();
                    *cursor = end;
                    *wire_end = Some(end);
                    return Ok(true);
                }
                if let Some(trailer_end) = find_double_crlf(body_bytes, data_start) {
                    let end: usize = trailer_end + HTTP_BR_BYTES.len() * 2;
                    let _: Option<&[u8]> =
                        validate_header_block(&body_bytes[data_start..end], &[], false)?;
                    *cursor = end;
                    *wire_end = Some(end);
                    return Ok(true);
                }
                if body_bytes.len().saturating_sub(data_start) > MAX_RESPONSE_HEAD_BYTES {
                    return Err(RequestError::Request(RESPONSE_TOO_LARGE.to_owned()));
                }
                return Ok(false);
            }
            let next_decoded_len: usize = decoded
                .len()
                .checked_add(chunk_size)
                .ok_or(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest))?;
            if next_decoded_len > MAX_RESPONSE_BODY_BYTES {
                return Err(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
            }
            let data_end: usize = data_start
                .checked_add(chunk_size)
                .ok_or(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest))?;
            let next: usize = data_end
                .checked_add(HTTP_BR_BYTES.len())
                .ok_or(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest))?;
            if next > body_bytes.len() {
                return Ok(false);
            }
            if &body_bytes[data_end..next] != HTTP_BR_BYTES {
                return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()));
            }
            decoded.extend_from_slice(&body_bytes[data_start..data_end]);
            *cursor = next;
        }
        Ok(false)
    }

    /// Reports whether extra unread bytes trailed after the terminating chunk block.
    ///
    /// # Arguments
    ///
    /// - `usize` - Total raw wire body length received after the response head.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the body is incomplete or contains trailing bytes.
    #[inline(always)]
    pub(crate) fn has_trailing(&self, body_len: usize) -> bool {
        let Self { wire_end, .. } = self;
        match *wire_end {
            Some(end) => end != body_len,
            None => true,
        }
    }

    /// Consumes the decoder and returns the decoded payload bytes if complete.
    ///
    /// # Returns
    ///
    /// - `Result<Vec<u8>, RequestError>` - Decoded payload, or incomplete framing error.
    #[inline(always)]
    pub(crate) fn into_decoded(self) -> Result<Vec<u8>, RequestError> {
        let Self {
            decoded, wire_end, ..
        } = self;
        if wire_end.is_some() {
            Ok(decoded)
        } else {
            Err(RequestError::HttpRequestPartsInsufficient(
                HttpStatus::BadRequest,
            ))
        }
    }
}