mod bitmap;
mod freelist;
mod stack;
#[allow(unused)]
pub(crate) use bitmap::BitmapAllocator;
pub(crate) use freelist::FreeListAllocator;
pub(crate) use stack::StackAllocator;
pub(crate) trait Allocator {
fn allocate(&mut self) -> Option<usize>;
fn free(&mut self, index: usize);
fn available(&self) -> usize;
fn capacity(&self) -> usize;
#[inline]
fn is_full(&self) -> bool {
self.available() == 0
}
#[inline]
fn is_empty(&self) -> bool {
self.available() == self.capacity()
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec::Vec;
fn test_allocator<A: Allocator>(mut allocator: A) {
let capacity = allocator.capacity();
assert_eq!(allocator.available(), capacity);
assert!(allocator.is_empty());
assert!(!allocator.is_full());
let mut indices = Vec::new();
for _ in 0..capacity {
let idx = allocator.allocate().expect("should allocate");
indices.push(idx);
}
assert_eq!(allocator.available(), 0);
assert!(!allocator.is_empty());
assert!(allocator.is_full());
assert!(allocator.allocate().is_none());
for idx in indices {
allocator.free(idx);
}
assert_eq!(allocator.available(), capacity);
assert!(allocator.is_empty());
assert!(!allocator.is_full());
}
#[test]
fn test_stack_allocator() {
test_allocator(StackAllocator::new(100));
}
#[test]
fn test_freelist_allocator() {
test_allocator(FreeListAllocator::new(100));
}
#[test]
fn test_bitmap_allocator() {
test_allocator(BitmapAllocator::new(100));
}
}