1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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);
    }
}