http-compress 23.4.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::*;

/// Allocates or reuses a default-initialized buffer of length `len` from a thread-local pool slot.
///
/// # Arguments
///
/// - `usize` - Required number of default-initialized elements.
/// - `F` - Selector projecting the typed free-list from `BrotliBufferPool`.
///
/// # Returns
///
/// - `PooledSlice<T>` - A zero/default-initialized slice of length `len`.
#[inline]
pub(crate) fn alloc_from_pool<T, F>(len: usize, select: F) -> PooledSlice<T>
where
    T: Default + Clone,
    F: FnOnce(&mut BrotliBufferPool) -> &mut Vec<Vec<T>>,
{
    if len == 0 {
        return PooledSlice(Vec::new());
    }
    let max_cap: usize = len
        .saturating_mul(BROTLI_POOL_MAX_WASTE_RATIO)
        .max(BROTLI_POOL_SMALL_ELEM_THRESHOLD);
    let reused: Option<Vec<T>> = BROTLI_BUFFER_POOL.with(|cell: &RefCell<BrotliBufferPool>| {
        let Ok(mut pool) = cell.try_borrow_mut() else {
            return None;
        };
        let list: &mut Vec<Vec<T>> = select(&mut pool);
        let mut best_index: Option<usize> = None;
        let mut best_cap: usize = usize::MAX;
        for (idx, item) in list.iter().enumerate() {
            let cap: usize = item.capacity();
            if cap >= len && cap <= max_cap && cap < best_cap {
                best_cap = cap;
                best_index = Some(idx);
                if cap == len {
                    break;
                }
            }
        }
        best_index.map(|idx: usize| list.swap_remove(idx))
    });
    if let Some(mut buf) = reused {
        buf.clear();
        buf.resize(len, T::default());
        return PooledSlice(buf);
    }
    PooledSlice(vec![T::default(); len])
}

/// Returns a freed Brotli buffer to its thread-local pool slot when within capacity bounds.
///
/// # Arguments
///
/// - `PooledSlice<T>` - The buffer to recycle.
/// - `F` - Selector projecting the typed free-list from `BrotliBufferPool`.
#[inline]
pub(crate) fn free_to_pool<T, F>(slice: PooledSlice<T>, select: F)
where
    F: FnOnce(&mut BrotliBufferPool) -> &mut Vec<Vec<T>>,
{
    let PooledSlice(buf) = slice;
    let cap: usize = buf.capacity();
    if cap == 0 || cap.saturating_mul(size_of::<T>()) > BROTLI_MAX_POOL_BYTES {
        return;
    }
    let _: Result<(), _> = BROTLI_BUFFER_POOL.try_with(|cell: &RefCell<BrotliBufferPool>| {
        if let Ok(mut pool) = cell.try_borrow_mut() {
            let list: &mut Vec<Vec<T>> = select(&mut pool);
            if list.len() < BROTLI_MAX_POOL_PER_TYPE {
                list.push(buf);
            }
        }
    });
}

/// Appends a Brotli-compressed representation of `data` directly into `out`.
///
/// # Arguments
///
/// - `&[u8]` - Uncompressed input bytes.
/// - `&mut Vec<u8>` - Destination byte buffer.
///
/// # Returns
///
/// - `bool` - `true` when compression succeeded; `false` on error.
pub fn encode_into(data: &[u8], out: &mut Vec<u8>) -> bool {
    let start_len: usize = out.len();
    let lgwin: u32 = data
        .len()
        .saturating_add(BROTLI_WINDOW_GAP)
        .next_power_of_two()
        .trailing_zeros()
        .clamp(BROTLI_MIN_WINDOW_BITS, BROTLI_DEFAULT_WINDOW_BITS);
    let mut guard: BrotliEncoderGuard =
        BrotliEncoderGuard(BrotliEncoderStateStruct::new(BrotliTlAlloc));
    let BrotliEncoderGuard(state) = &mut guard;
    state.set_parameter(
        BrotliEncoderParameter::BROTLI_PARAM_QUALITY,
        BROTLI_DEFAULT_QUALITY,
    );
    state.set_parameter(BrotliEncoderParameter::BROTLI_PARAM_LGWIN, lgwin);
    let size_hint: u32 = u32::try_from(data.len()).unwrap_or(u32::MAX);
    state.set_parameter(BrotliEncoderParameter::BROTLI_PARAM_SIZE_HINT, size_hint);
    let mut available_in: usize = data.len();
    let mut input_offset: usize = 0;
    let mut total_out: Option<usize> = Some(0);
    BROTLI_ENCODE_SCRATCH.with(|cell: &RefCell<[u8; BROTLI_ENCODE_SCRATCH_LEN]>| {
        let mut fallback: [u8; BROTLI_ENCODE_SCRATCH_LEN];
        let mut borrowed: Option<RefMut<'_, [u8; BROTLI_ENCODE_SCRATCH_LEN]>> =
            cell.try_borrow_mut().ok();
        let scratch: &mut [u8] = match borrowed.as_deref_mut() {
            Some(buf) => buf.as_mut_slice(),
            None => {
                fallback = [0u8; BROTLI_ENCODE_SCRATCH_LEN];
                fallback.as_mut_slice()
            }
        };
        loop {
            let mut available_out: usize = scratch.len();
            let mut output_offset: usize = 0;
            let ok: bool = state.compress_stream(
                BrotliEncoderOperation::BROTLI_OPERATION_FINISH,
                &mut available_in,
                data,
                &mut input_offset,
                &mut available_out,
                scratch,
                &mut output_offset,
                &mut total_out,
                &mut |_: &mut PredictionModeContextMap<InputReferenceMut<'_>>,
                      _: &mut [StaticCommand],
                      _: InputPair<'_>,
                      _: &mut BrotliTlAlloc| {},
            );
            if !ok {
                out.truncate(start_len);
                return false;
            }
            if output_offset > 0 {
                out.extend_from_slice(&scratch[..output_offset]);
            }
            if state.is_finished() {
                return true;
            }
        }
    })
}

/// Compresses the given data using the Brotli compression algorithm.
///
/// The bytes are compressed through `BrotliEncoderStateStruct` backed by a thread-local buffer
/// pool and a payload-sized sliding window, producing a standard RFC 7932 Brotli stream that any
/// `Content-Encoding: br` consumer can decode. An empty owned `Vec<u8>` is returned on failure.
///
/// # Arguments
///
/// - `&'_ [u8]` - The bytes to compress.
/// - `usize` - The capacity hint for the output buffer.
///
/// # Returns
///
/// - `Cow<'_, [u8]>` - The compressed bytes, or an empty owned `Vec<u8>` on failure.
pub fn encode(data: &'_ [u8], buffer_size: usize) -> Cow<'_, [u8]> {
    let lgwin: u32 = data
        .len()
        .saturating_add(BROTLI_WINDOW_GAP)
        .next_power_of_two()
        .trailing_zeros()
        .clamp(BROTLI_MIN_WINDOW_BITS, BROTLI_DEFAULT_WINDOW_BITS);
    let mut guard: BrotliEncoderGuard =
        BrotliEncoderGuard(BrotliEncoderStateStruct::new(BrotliTlAlloc));
    let BrotliEncoderGuard(state) = &mut guard;
    state.set_parameter(
        BrotliEncoderParameter::BROTLI_PARAM_QUALITY,
        BROTLI_DEFAULT_QUALITY,
    );
    state.set_parameter(BrotliEncoderParameter::BROTLI_PARAM_LGWIN, lgwin);
    let size_hint: u32 = u32::try_from(data.len()).unwrap_or(u32::MAX);
    state.set_parameter(BrotliEncoderParameter::BROTLI_PARAM_SIZE_HINT, size_hint);
    let mut available_in: usize = data.len();
    let mut input_offset: usize = 0;
    let mut total_out: Option<usize> = Some(0);
    let mut out: Vec<u8> = Vec::new();
    let ok: bool = BROTLI_ENCODE_SCRATCH.with(|cell: &RefCell<[u8; BROTLI_ENCODE_SCRATCH_LEN]>| {
        let mut fallback: [u8; BROTLI_ENCODE_SCRATCH_LEN];
        let mut borrowed: Option<RefMut<'_, [u8; BROTLI_ENCODE_SCRATCH_LEN]>> =
            cell.try_borrow_mut().ok();
        let scratch: &mut [u8] = match borrowed.as_deref_mut() {
            Some(buf) => buf.as_mut_slice(),
            None => {
                fallback = [0u8; BROTLI_ENCODE_SCRATCH_LEN];
                fallback.as_mut_slice()
            }
        };
        loop {
            let mut available_out: usize = scratch.len();
            let mut output_offset: usize = 0;
            let ok: bool = state.compress_stream(
                BrotliEncoderOperation::BROTLI_OPERATION_FINISH,
                &mut available_in,
                data,
                &mut input_offset,
                &mut available_out,
                scratch,
                &mut output_offset,
                &mut total_out,
                &mut |_: &mut PredictionModeContextMap<InputReferenceMut<'_>>,
                      _: &mut [StaticCommand],
                      _: InputPair<'_>,
                      _: &mut BrotliTlAlloc| {},
            );
            if !ok {
                return false;
            }
            if state.is_finished() && out.is_empty() {
                out = scratch[..output_offset].to_vec();
                return true;
            }
            if output_offset > 0 {
                if out.is_empty() {
                    let initial_capacity: usize = data
                        .len()
                        .min(buffer_size.max(output_offset))
                        .max(output_offset);
                    out.reserve(initial_capacity);
                }
                out.extend_from_slice(&scratch[..output_offset]);
            }
            if state.is_finished() {
                return true;
            }
        }
    });
    if !ok {
        return Cow::Owned(Vec::new());
    }
    Cow::Owned(out)
}

/// Decompresses Brotli-compressed data.
///
/// Decoding uses `BrotliDecompressStream` backed by the thread-local buffer pool while enforcing
/// `MAX_DECOMPRESSED_BYTES`. An empty owned `Vec<u8>` is returned when the input is invalid or
/// exceeds the decompression limit.
///
/// # Arguments
///
/// - `&'_ [u8]` - The Brotli-compressed bytes to decode.
/// - `usize` - The capacity hint for the output buffer.
///
/// # Returns
///
/// - `Cow<'_, [u8]>` - The decompressed bytes, or an empty owned `Vec<u8>` on failure.
pub fn decode(data: &'_ [u8], buffer_size: usize) -> Cow<'_, [u8]> {
    if data.is_empty() {
        return Cow::Owned(Vec::new());
    }
    let mut state: BrotliState<BrotliTlAlloc, BrotliTlAlloc, BrotliTlAlloc> =
        BrotliState::new(BrotliTlAlloc, BrotliTlAlloc, BrotliTlAlloc);
    let mut available_in: usize = data.len();
    let mut input_offset: usize = 0;
    let mut total_out: usize = 0;
    let mut out: Vec<u8> = Vec::new();
    let ok: bool = BROTLI_DECODE_SCRATCH.with(|cell: &RefCell<[u8; BROTLI_DECODE_SCRATCH_LEN]>| {
        let mut fallback: [u8; BROTLI_DECODE_SCRATCH_LEN];
        let mut borrowed: Option<RefMut<'_, [u8; BROTLI_DECODE_SCRATCH_LEN]>> =
            cell.try_borrow_mut().ok();
        let scratch: &mut [u8] = match borrowed.as_deref_mut() {
            Some(buf) => buf.as_mut_slice(),
            None => {
                fallback = [0u8; BROTLI_DECODE_SCRATCH_LEN];
                fallback.as_mut_slice()
            }
        };
        loop {
            let mut available_out: usize = scratch.len();
            let mut output_offset: usize = 0;
            let result: BrotliResult = BrotliDecompressStream(
                &mut available_in,
                &mut input_offset,
                data,
                &mut available_out,
                &mut output_offset,
                scratch,
                &mut total_out,
                &mut state,
            );
            if out.len().saturating_add(output_offset) > MAX_DECOMPRESSED_BYTES {
                return false;
            }
            match result {
                BrotliResult::ResultSuccess => {
                    if out.is_empty() {
                        out = scratch[..output_offset].to_vec();
                    } else if output_offset > 0 {
                        out.extend_from_slice(&scratch[..output_offset]);
                    }
                    return true;
                }
                BrotliResult::NeedsMoreOutput => {
                    if output_offset > 0 {
                        if out.is_empty() {
                            let initial_capacity: usize = data
                                .len()
                                .saturating_mul(4)
                                .max(output_offset.saturating_mul(2))
                                .min(buffer_size.max(output_offset.saturating_mul(2)))
                                .min(MAX_DECOMPRESSED_BYTES);
                            out.reserve(initial_capacity);
                        }
                        out.extend_from_slice(&scratch[..output_offset]);
                    }
                }
                BrotliResult::NeedsMoreInput | BrotliResult::ResultFailure => {
                    return false;
                }
            }
        }
    });
    if !ok {
        return Cow::Owned(Vec::new());
    }
    Cow::Owned(out)
}