pub mod block;
pub mod chunks;
pub mod global;
use std::alloc::Layout;
pub struct Location<H> {
pub(crate) ptr: *mut u8,
pub(crate) header: H,
pub(crate) layout: Layout,
}
pub trait Region<H> {
type Pointers: Iterator<Item = *mut u8>;
fn allocate(&mut self, layout: Layout, header: H) -> Result<*mut u8, H>;
fn deallocate(&mut self, ptr: *mut u8) -> Option<H>;
fn has_allocated(&self, ptr: *mut u8) -> bool;
fn allocations(&self) -> Self::Pointers;
fn count(&self) -> usize;
fn deallocate_all(&mut self) -> DeallocateAll<'_, H, Self>
where
Self: Sized,
{
DeallocateAll {
iter: self.allocations(),
region: self,
}
}
}
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);
}
}