brotli 9.1.5

A brotli compressor and decompressor that with an interface avoiding the rust stdlib. This makes it suitable for embedded devices and kernels. It is designed with a pluggable allocator so that the standard lib's allocator may be employed. The default build also includes a stdlib allocator and stream interface. Disable this with --features=no-stdlib. All included code is safe.
Documentation
//! Allocator types and checked allocation for Brotli.

extern crate alloc_no_stdlib as alloc;

pub use self::alloc::{
    AllocatedStackMemory, Allocator, SliceWrapper, SliceWrapperMut, StackAllocator,
};

#[cfg(test)]
pub(crate) use self::alloc::{
    bzero, declare_stack_allocator_struct, define_allocator_memory_pool,
    define_stack_allocator_traits, static_array,
};

/// The allocator returned fewer elements than were requested.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct AllocError;

impl core::fmt::Display for AllocError {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.write_str("the allocator returned fewer elements than requested")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for AllocError {}

/// Wraps an allocator that returns the requested buffer or an empty buffer on failure.
pub struct CheckedAllocator<A>(pub A);

impl<A> CheckedAllocator<A> {
    /// Returns a buffer with at least `len` elements, or `AllocError` on failure.
    /// A zero-length request succeeds with an empty buffer without calling the allocator.
    pub fn try_alloc_cell<T>(&mut self, len: usize) -> Result<A::AllocatedMemory, AllocError>
    where
        A: Allocator<T>,
    {
        try_alloc_cell(&mut self.0, len)
    }

    /// Returns a nonempty buffer to the allocator that allocated it.
    pub fn free_cell<T>(&mut self, memory: A::AllocatedMemory)
    where
        A: Allocator<T>,
    {
        if !memory.slice().is_empty() {
            self.0.free_cell(memory);
        }
    }
}

// Convert the raw allocator's empty sentinel into an AllocError here.
#[allow(clippy::disallowed_methods)]
pub(crate) fn try_alloc_cell<T, A: Allocator<T>>(
    alloc: &mut A,
    len: usize,
) -> Result<A::AllocatedMemory, AllocError> {
    if len == 0 {
        return Ok(alloc_default::<T, A>());
    }
    let memory = alloc.alloc_cell(len);
    if memory.slice().len() < len {
        // Hand a short buffer back so pooled allocators do not lose it.
        if !memory.slice().is_empty() {
            alloc.free_cell(memory);
        }
        return Err(AllocError);
    }
    Ok(memory)
}

// The entire allocation represents the copied data, so its length must match.
pub(crate) fn try_copy_slice<T: Copy, A: Allocator<T>>(
    alloc: &mut A,
    data: &[T],
) -> Result<A::AllocatedMemory, AllocError> {
    let mut memory = try_alloc_cell(alloc, data.len())?;
    if memory.slice().len() != data.len() {
        alloc.free_cell(memory);
        return Err(AllocError);
    }
    memory.slice_mut().copy_from_slice(data);
    Ok(memory)
}

pub(crate) fn alloc_default<T, A: Allocator<T>>() -> A::AllocatedMemory {
    A::AllocatedMemory::default()
}

#[cfg(test)]
mod tests {
    use super::{AllocError, AllocatedStackMemory, Allocator, CheckedAllocator, SliceWrapper};

    struct TestAllocator<'a>(&'a mut [u8]);

    impl<'a> Allocator<u8> for TestAllocator<'a> {
        type AllocatedMemory = AllocatedStackMemory<'a, u8>;

        fn alloc_cell(&mut self, len: usize) -> Self::AllocatedMemory {
            assert_ne!(len, 0);
            if self.0.len() == len {
                AllocatedStackMemory {
                    mem: core::mem::take(&mut self.0),
                }
            } else {
                Self::AllocatedMemory::default()
            }
        }

        fn free_cell(&mut self, memory: Self::AllocatedMemory) {
            assert!(!memory.slice().is_empty());
            self.0 = memory.mem;
        }
    }

    #[test]
    fn checked_allocation_handles_empty_requests_and_failures() {
        let mut backing = [0; 4];
        let mut alloc = CheckedAllocator(TestAllocator(&mut backing));
        let empty = alloc.try_alloc_cell(0).unwrap();
        assert!(empty.slice().is_empty());
        alloc.free_cell(empty);

        assert_eq!(alloc.try_alloc_cell(5).err(), Some(AllocError));
        let memory = alloc.try_alloc_cell(4).unwrap();
        assert_eq!(memory.slice().len(), 4);
        assert_eq!(alloc.try_alloc_cell(4).err(), Some(AllocError));
        alloc.free_cell(memory);
        assert!(alloc.try_alloc_cell(4).is_ok());
    }
}