http-compress 23.2.0

A high-performance async library for HTTP compression/decompression, supporting Brotli, Deflate, and Gzip algorithms. Provides both compression and decompression capabilities with optimized memory usage, ideal for HTTP clients/servers and network programming.
Documentation
use super::*;

/// Parses one RFC 1952 gzip member header starting at `offset` and returns the deflate payload offset.
///
/// # Arguments
///
/// - `&[u8]` - The complete gzip stream slice.
/// - `usize` - The starting offset of the gzip member header.
///
/// # Returns
///
/// - `Option<usize>` - Byte offset where the raw DEFLATE stream begins, or `None` if malformed.
fn parse_gzip_header(data: &[u8], offset: usize) -> Option<usize> {
    let header_end: usize = offset.checked_add(GZIP_HEADER_LEN)?;
    if header_end > data.len() {
        return None;
    }
    if data[offset] != GZIP_ID1
        || data[offset + 1] != GZIP_ID2
        || data[offset + 2] != GZIP_METHOD_DEFLATE
    {
        return None;
    }
    let flags: u8 = data[offset + 3];
    if flags & GZIP_FLAG_RESERVED != 0 {
        return None;
    }
    let mut pos: usize = header_end;
    if flags & GZIP_FLAG_FEXTRA != 0 {
        let len_end: usize = pos.checked_add(2)?;
        if len_end > data.len() {
            return None;
        }
        let extra_len: usize = usize::from(u16::from_le_bytes([data[pos], data[pos + 1]]));
        pos = len_end.checked_add(extra_len)?;
        if pos > data.len() {
            return None;
        }
    }
    if flags & GZIP_FLAG_FNAME != 0 {
        let nul_offset: usize = data[pos..].iter().position(|byte: &u8| *byte == 0)?;
        pos = pos.checked_add(nul_offset)?.checked_add(1)?;
    }
    if flags & GZIP_FLAG_FCOMMENT != 0 {
        let nul_offset: usize = data[pos..].iter().position(|byte: &u8| *byte == 0)?;
        pos = pos.checked_add(nul_offset)?.checked_add(1)?;
    }
    if flags & GZIP_FLAG_FHCRC != 0 {
        let crc_end: usize = pos.checked_add(2)?;
        if crc_end > data.len() {
            return None;
        }
        let mut header_crc: Crc = Crc::new();
        header_crc.update(&data[offset..pos]);
        let stored_crc: u16 = u16::from_le_bytes([data[pos], data[pos + 1]]);
        if stored_crc != header_crc.sum() as u16 {
            return None;
        }
        pos = crc_end;
    }
    Some(pos)
}

/// Compresses the given data using Gzip compression.
///
/// This function writes an RFC 1952 gzip header, compresses the payload using the thread-local
/// reusable raw DEFLATE compressor, and appends the CRC32 and ISIZE trailer. If compression fails,
/// an empty owned `Vec<u8>` is returned.
///
/// # Arguments
///
/// - `&'_ [u8]` - A reference to a byte slice containing the data to be compressed.
/// - `usize` - The capacity hint for the output buffer.
///
/// # Returns
///
/// - `Cow<'_, [u8]>` - The compressed data. If compression is successful, the
///   compressed data is returned as an owned `Vec<u8>`. If an error occurs, an empty owned `Vec<u8>`
///   is returned.
pub fn encode(data: &'_ [u8], buffer_size: usize) -> Cow<'_, [u8]> {
    let framing_overhead: usize = GZIP_HEADER_LEN + GZIP_TRAILER_LEN + 16;
    let initial_capacity: usize = data
        .len()
        .saturating_add(framing_overhead)
        .min(buffer_size.max(framing_overhead))
        .max(framing_overhead);
    let mut out: Vec<u8> = Vec::with_capacity(initial_capacity);
    out.extend_from_slice(&GZIP_DEFAULT_HEADER);
    let mut crc: Crc = Crc::new();
    crc.update(data);
    if !deflate::compress_raw_into(data, &mut out) {
        return Cow::Owned(Vec::new());
    }
    out.extend_from_slice(&crc.sum().to_le_bytes());
    out.extend_from_slice(&(data.len() as u32).to_le_bytes());
    Cow::Owned(out)
}

/// Decompresses the given Gzip-compressed data.
///
/// Supports both single-member and concatenated multi-member RFC 1952 gzip streams while reusing
/// the thread-local raw DEFLATE decompressor and enforcing `MAX_DECOMPRESSED_BYTES`. If
/// decompression fails or exceeds the limit, an empty owned `Vec<u8>` is returned.
///
/// # Arguments
///
/// - `&'_ [u8]` - A reference to a byte slice containing the Gzip-compressed data.
/// - `usize` - A capacity hint for the output buffer.
///
/// # Returns
///
/// - `Cow<'_, [u8]>` - The decompressed data. If decompression is successful, the
///   decompressed data is returned as an owned `Vec<u8>`. If an error occurs, an empty owned `Vec<u8>`
///   is returned.
pub fn decode(data: &'_ [u8], buffer_size: usize) -> Cow<'_, [u8]> {
    if data.len() < GZIP_HEADER_LEN + GZIP_TRAILER_LEN {
        return Cow::Owned(Vec::new());
    }
    let data_len: usize = data.len();
    let trailer_hint: usize = usize::try_from(u32::from_le_bytes([
        data[data_len - 4],
        data[data_len - 3],
        data[data_len - 2],
        data[data_len - 1],
    ]))
    .unwrap_or(0);
    let max_trusted_hint: usize = data_len
        .saturating_mul(GZIP_HINT_MAX_RATIO)
        .min(MAX_DECOMPRESSED_BYTES);
    let initial_capacity: usize = if trailer_hint > 0 && trailer_hint <= max_trusted_hint {
        trailer_hint
            .saturating_add(GZIP_HINT_HEADROOM)
            .min(buffer_size.max(GZIP_HINT_DIRECT_CAP))
            .min(MAX_DECOMPRESSED_BYTES + 1)
    } else {
        data_len
            .saturating_mul(4)
            .min(buffer_size.max(GZIP_FALLBACK_RESERVE))
            .min(MAX_DECOMPRESSED_BYTES)
    };
    let mut decompressed_data: Vec<u8> = Vec::with_capacity(initial_capacity);
    let mut offset: usize = 0;
    while offset < data_len {
        let Some(deflate_start) = parse_gzip_header(data, offset) else {
            return Cow::Owned(Vec::new());
        };
        let member_out_start: usize = decompressed_data.len();
        let Some(consumed) =
            deflate::decompress_raw_into(&data[deflate_start..], &mut decompressed_data)
        else {
            return Cow::Owned(Vec::new());
        };
        let trailer_start: usize = deflate_start + consumed;
        let Some(trailer_end) = trailer_start.checked_add(GZIP_TRAILER_LEN) else {
            return Cow::Owned(Vec::new());
        };
        if trailer_end > data_len {
            return Cow::Owned(Vec::new());
        }
        let expected_crc: u32 = u32::from_le_bytes([
            data[trailer_start],
            data[trailer_start + 1],
            data[trailer_start + 2],
            data[trailer_start + 3],
        ]);
        let expected_isize: u32 = u32::from_le_bytes([
            data[trailer_start + 4],
            data[trailer_start + 5],
            data[trailer_start + 6],
            data[trailer_start + 7],
        ]);
        let member_bytes: &[u8] = &decompressed_data[member_out_start..];
        let mut crc: Crc = Crc::new();
        crc.update(member_bytes);
        if crc.sum() != expected_crc || member_bytes.len() as u32 != expected_isize {
            return Cow::Owned(Vec::new());
        }
        offset = trailer_end;
    }
    Cow::Owned(decompressed_data)
}