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::*;

/// Compresses `data` into `out` using a raw DEFLATE stream with a reusable compressor state.
///
/// # Arguments
///
/// - `&mut flate2::Compress` - The raw DEFLATE compressor state to reset and reuse.
/// - `&[u8]` - The uncompressed input bytes.
/// - `&mut Vec<u8>` - The destination buffer to append compressed bytes into.
///
/// # Returns
///
/// - `bool` - `true` when the stream completed cleanly, `false` on error.
fn compress_raw_with_state(
    compressor: &mut flate2::Compress,
    data: &[u8],
    out: &mut Vec<u8>,
) -> bool {
    compressor.reset();
    loop {
        let consumed: usize = compressor.total_in() as usize;
        let input: &[u8] = &data[consumed..];
        if out.capacity() - out.len() < 64 {
            let grow: usize = (input.len() / 2).max(DEFLATE_MIN_RESERVE);
            out.reserve(grow);
        }
        let before_in: u64 = compressor.total_in();
        let before_out: u64 = compressor.total_out();
        match compressor.compress_vec(input, out, FlushCompress::Finish) {
            Ok(Status::StreamEnd) => return true,
            Ok(Status::Ok | Status::BufError) => {
                if compressor.total_in() == before_in && compressor.total_out() == before_out {
                    let grow: usize = out.capacity().max(DEFLATE_MIN_RESERVE);
                    out.reserve(grow);
                }
            }
            Err(_) => return false,
        }
    }
}

/// Compresses `data` into `out` as raw DEFLATE using a thread-local compressor state.
///
/// # Arguments
///
/// - `&[u8]` - The uncompressed input bytes.
/// - `&mut Vec<u8>` - The destination buffer to append compressed bytes into.
///
/// # Returns
///
/// - `bool` - `true` when compression succeeded, `false` otherwise.
pub(crate) fn compress_raw_into(data: &[u8], out: &mut Vec<u8>) -> bool {
    DEFLATE_COMPRESSOR.with(|cell: &RefCell<flate2::Compress>| {
        if let Ok(mut compressor) = cell.try_borrow_mut() {
            compress_raw_with_state(&mut compressor, data, out)
        } else {
            let mut compressor: flate2::Compress =
                flate2::Compress::new(Compression::default(), false);
            compress_raw_with_state(&mut compressor, data, out)
        }
    })
}

/// Decompresses one raw DEFLATE stream from `data` into `out` using a reusable decompressor state.
///
/// # Arguments
///
/// - `&mut Decompress` - The raw DEFLATE decompressor state to reset and reuse.
/// - `&[u8]` - The compressed input bytes.
/// - `&mut Vec<u8>` - The destination buffer to append decompressed bytes into.
///
/// # Returns
///
/// - `Option<usize>` - Number of compressed input bytes consumed on `StreamEnd`, or `None` on
///   corruption, truncation, or exceeding `MAX_DECOMPRESSED_BYTES`.
fn decompress_raw_with_state(
    decompressor: &mut Decompress,
    data: &[u8],
    out: &mut Vec<u8>,
) -> Option<usize> {
    decompressor.reset(false);
    let limit: usize = MAX_DECOMPRESSED_BYTES + 1;
    loop {
        if out.len() > MAX_DECOMPRESSED_BYTES {
            return None;
        }
        let max_room: usize = limit - out.len();
        if out.capacity() == out.len() {
            let grow: usize = out
                .capacity()
                .clamp(DEFLATE_MIN_RESERVE, DEFLATE_MAX_GROW_STEP)
                .min(max_room);
            out.reserve_exact(grow);
        }
        let consumed: usize = decompressor.total_in() as usize;
        let input: &[u8] = &data[consumed..];
        let before_in: u64 = decompressor.total_in();
        let before_out: u64 = decompressor.total_out();
        match decompressor.decompress_vec(input, out, FlushDecompress::None) {
            Ok(Status::StreamEnd) => {
                if out.len() > MAX_DECOMPRESSED_BYTES {
                    return None;
                }
                return Some(decompressor.total_in() as usize);
            }
            Ok(Status::Ok | Status::BufError) => {
                if out.len() > MAX_DECOMPRESSED_BYTES {
                    return None;
                }
                if decompressor.total_in() == before_in
                    && decompressor.total_out() == before_out
                    && out.len() < out.capacity()
                {
                    return None;
                }
            }
            Err(_) => return None,
        }
    }
}

/// Decompresses one raw DEFLATE stream from `data` into `out` using a thread-local decompressor.
///
/// # Arguments
///
/// - `&[u8]` - The compressed input bytes.
/// - `&mut Vec<u8>` - The destination buffer to append decompressed bytes into.
///
/// # Returns
///
/// - `Option<usize>` - Number of compressed input bytes consumed, or `None` on error or overflow.
pub(crate) fn decompress_raw_into(data: &[u8], out: &mut Vec<u8>) -> Option<usize> {
    DEFLATE_DECOMPRESSOR.with(|cell: &RefCell<Decompress>| {
        if let Ok(mut decompressor) = cell.try_borrow_mut() {
            decompress_raw_with_state(&mut decompressor, data, out)
        } else {
            let mut decompressor: Decompress = Decompress::new(false);
            decompress_raw_with_state(&mut decompressor, data, out)
        }
    })
}

/// Compresses the given data using the Deflate compression algorithm.
///
/// This function takes a byte slice of data and compresses it using the Deflate compression algorithm.
/// The data is compressed via a thread-local reusable compressor state to eliminate per-call state
/// allocations. If compression succeeds, the resulting compressed data is returned as an owned
/// `Vec<u8>`. If any error occurs during the compression process, an empty `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 initial_capacity: usize = data
        .len()
        .saturating_add(16)
        .min(buffer_size.max(16))
        .max(32);
    let mut out: Vec<u8> = Vec::with_capacity(initial_capacity);
    if !compress_raw_into(data, &mut out) {
        return Cow::Owned(Vec::new());
    }
    Cow::Owned(out)
}

/// Decompresses Deflate compressed data.
///
/// # Arguments
///
/// - `&'_ [u8]` - A reference to a byte slice containing the compressed data to decode.
/// - `usize` - The capacity hint for decompression.
///
/// # Returns
///
/// - `Cow<'_, [u8]>` - The decompressed data.
pub fn decode(data: &'_ [u8], buffer_size: usize) -> Cow<'_, [u8]> {
    if data.is_empty() {
        return Cow::Owned(Vec::new());
    }
    let initial_capacity: usize = data
        .len()
        .saturating_mul(4)
        .min(buffer_size.max(DEFLATE_MIN_RESERVE))
        .min(MAX_DECOMPRESSED_BYTES);
    let mut decompressed_data: Vec<u8> = Vec::with_capacity(initial_capacity);
    if decompress_raw_into(data, &mut decompressed_data).is_none() {
        return Cow::Owned(Vec::new());
    }
    Cow::Owned(decompressed_data)
}