dynvec 0.1.4

This crate provides the `DynVec` type that acts like a vector to store any datatype.
Documentation
pub mod block;
pub mod chunks;
pub mod global;

use std::alloc::Layout;

/// Represents the location of an object allocated in a region.
pub struct Location<H> {
    /// The pointer to allocated memory for the object.
    pub(crate) ptr: *mut u8,
    /// The header of the location, defined by the user.
    pub(crate) header: H,
    /// The layout that was used to allocate the object.
    pub(crate) layout: Layout,
}

/// Represents a region of the memory. Objects can be allocated into this region.
/// Regions can carry additional data with each allocation.
pub trait Region<H> {
    /// An iterator over all the allocations of this region.
    type Pointers: Iterator<Item = *mut u8>;

    /// Finds a free location within this region that is:
    /// * Properly aligned to `layout.align`
    /// * `layout.size` bytes long
    ///
    /// # Returns
    /// The pointer is returned if the allocation is successful and the provided
    /// header is given back in the error if the allocation could not be done.
    fn allocate(&mut self, layout: Layout, header: H) -> Result<*mut u8, H>;

    /// Deallocates the memory allocated at the given pointer.
    ///
    /// # Returns
    /// If the given pointer was not allocated in this region, `None`
    /// is returned. Otherwise, the header is returned.
    ///
    /// # Safety
    /// * The old value must've been properly dropped.
    fn deallocate(&mut self, ptr: *mut u8) -> Option<H>;

    /// Checks whether the given pointer is allocated in this region.
    fn has_allocated(&self, ptr: *mut u8) -> bool;

    /// Returns an iterator over all the allocations of this region.
    fn allocations(&self) -> Self::Pointers;

    /// Returns the number of allocations this region has.
    fn count(&self) -> usize;

    /// Returns an iterator that causes all allocations to be deallocated.
    /// The iterator yield the headers.
    fn deallocate_all(&mut self) -> DeallocateAll<'_, H, Self>
    where
        Self: Sized,
    {
        DeallocateAll {
            iter: self.allocations(),
            region: self,
        }
    }
}

/// An iterator that causes a region to deallocate all its allocations.
pub struct DeallocateAll<'a, H, R: Region<H>> {
    region: &'a mut R,
    iter: R::Pointers,
}

impl<'a, H, R: Region<H>> Iterator for DeallocateAll<'a, H, R> {
    type Item = (*mut u8, H);

    fn next(&mut self) -> Option<Self::Item> {
        let ptr = self.iter.next()?;
        Some((ptr, self.region.deallocate(ptr).unwrap()))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, H, R> ExactSizeIterator for DeallocateAll<'a, H, R>
where
    R: Region<H>,
    R::Pointers: ExactSizeIterator,
{
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<'a, H, R> std::iter::FusedIterator for DeallocateAll<'a, H, R>
where
    R: Region<H>,
    R::Pointers: std::iter::FusedIterator,
{
}

impl<'a, H, R> std::iter::DoubleEndedIterator for DeallocateAll<'a, H, R>
where
    R: Region<H>,
    R::Pointers: std::iter::DoubleEndedIterator,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        let ptr = self.iter.next_back()?;
        Some((ptr, self.region.deallocate(ptr).unwrap()))
    }
}

#[cfg(test)]
#[test]
fn deallocate_all() {
    let mut chunks = chunks::Chunks::new(4);

    let vec: Vec<*mut u8> = (0..100)
        .map(|_| chunks.allocate(Layout::new::<u8>(), ()).unwrap())
        .collect();

    for _ in chunks.deallocate_all() {}

    for ptr in vec {
        assert_eq!(chunks.deallocate(ptr), None);
    }
}