rust_dsa/bumpalloc.rs
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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
use std::alloc::{alloc, dealloc, Layout};
use std::mem;
use std::ptr::NonNull;
/// A bump allocator for type `T`.
///
/// # Example
/// ```
/// use rust_dsa::BumpAlloc;
///
/// // First, we create a new bump allocator.
/// let mut arena: BumpAlloc<i32> = BumpAlloc::new(3);
///
/// // We can allocate pointers.
/// let ptr1 = arena.alloc().unwrap();
/// let ptr2 = arena.alloc().unwrap();
/// let ptr3 = arena.alloc().unwrap();
///
/// // Eventually, we run out of room.
/// assert_eq!(arena.alloc(), None);
/// assert_eq!(arena.available_slots(), 0);
///
/// // We can free allocations to make more room.
/// arena.free(ptr1);
/// arena.free(ptr2);
/// arena.free(ptr3);
/// assert!(arena.can_alloc());
/// assert!(arena.alloc().is_some());
/// assert!(arena.alloc().is_some());
///
/// // We can iterate over existing allocations.
/// assert_eq!(arena.allocations().count(), 2);
///
/// // Finally, we can free everything.
/// arena.free_all();
/// ```
pub struct BumpAlloc<T> {
n: usize,
queue: Vec<usize>,
buffer: NonNull<T>,
free: Vec<bool>,
}
impl<T> BumpAlloc<T> {
/// Creates a new allocator.
///
/// # Panics
/// Panics if the allocation fails or if `size_of::<T>()` is zero.
pub fn new(n: usize) -> BumpAlloc<T> {
let buffer = if n == 0 {
NonNull::dangling()
} else if mem::size_of::<T>() == 0 {
panic!("`T` has size 0");
} else {
let layout = Layout::array::<T>(n).expect("alloction is too big");
let ptr = unsafe { alloc(layout) as *mut T };
NonNull::new(ptr).expect("allocation failed")
};
BumpAlloc {
n,
queue: (0..n).collect(),
buffer,
free: vec![true; n],
}
}
/// Allocates a slot, if one is available.
///
/// # Example
/// ```
/// use rust_dsa::BumpAlloc;
///
/// let mut arena: BumpAlloc<char> = BumpAlloc::new(3);
///
/// assert!(arena.alloc().is_some());
/// assert!(arena.alloc().is_some());
/// assert!(arena.alloc().is_some());
/// assert!(arena.alloc().is_none());
/// ```
pub fn alloc(&mut self) -> Option<NonNull<T>> {
let slot = self.queue.pop()?;
self.free[slot] = false;
unsafe { NonNull::new(self.buffer.as_ptr().add(slot)) }
}
/// Frees a slot.
///
/// # Panics
/// Panics if the pointer was not allocated by this `BumpAlloc` struct.
///
/// # Example
/// ```
/// use rust_dsa::BumpAlloc;
///
/// let mut arena: BumpAlloc<String> = BumpAlloc::new(10);
///
/// let ptr = arena.alloc().unwrap();
/// assert_eq!(arena.available_slots(), 9);
///
/// arena.free(ptr);
///
/// assert_eq!(arena.available_slots(), 10);
/// ```
pub fn free(&mut self, ptr: NonNull<T>) {
if ptr.as_ptr().align_offset(mem::align_of::<T>()) != 0 {
panic!("invalid pointer");
}
let slot: usize = unsafe {
ptr.as_ptr()
.offset_from(self.buffer.as_ptr())
.try_into()
.expect("invalid pointer")
};
if self.free.get(slot) != Some(&false) {
panic!("invalid pointer");
}
self.free[slot] = true;
self.queue.push(slot);
}
/// Returns an interator over the currently allocated pointers.
///
/// # Example
/// ```
/// use rust_dsa::BumpAlloc;
///
/// let mut arena: BumpAlloc<u8> = BumpAlloc::new(100);
/// arena.alloc();
/// arena.alloc();
/// arena.alloc();
/// assert_eq!(arena.available_slots(), 97);
///
/// let allocations: Vec<_> = arena.allocations().collect();
/// for ptr in allocations {
/// arena.free(ptr);
/// }
///
/// assert_eq!(arena.available_slots(), 100);
/// ```
pub fn allocations(&self) -> Allocations<'_, T> {
Allocations { ba: self, n: 0 }
}
/// Frees all the currently allocated pointers.
///
/// # Example
/// ```
/// use rust_dsa::BumpAlloc;
///
/// let mut arena: BumpAlloc<i32> = BumpAlloc::new(10);
/// arena.alloc();
/// arena.alloc();
/// arena.alloc();
/// assert_eq!(arena.available_slots(), 7);
///
/// arena.free_all();
///
/// assert_eq!(arena.available_slots(), 10);
/// ```
pub fn free_all(&mut self) {
self.free = vec![true; self.n];
self.queue = (0..self.n).collect();
}
/// Returns the number of available slots that can be allocated.
///
/// # Example
/// ```
/// use rust_dsa::BumpAlloc;
///
/// let mut arena: BumpAlloc<i32> = BumpAlloc::new(10);
/// assert_eq!(arena.available_slots(), 10);
///
/// arena.alloc();
/// arena.alloc();
/// arena.alloc();
/// assert_eq!(arena.available_slots(), 7);
/// ```
pub fn available_slots(&self) -> usize {
self.queue.len()
}
/// Returns `true` if [`BumpAlloc::alloc`] will return `Some`.
///
/// # Example
/// ```
/// use rust_dsa::BumpAlloc;
///
/// let mut arena: BumpAlloc<bool> = BumpAlloc::new(1);
/// assert!(arena.can_alloc());
///
/// arena.alloc();
///
/// assert!(!arena.can_alloc());
/// ```
pub fn can_alloc(&self) -> bool {
self.available_slots() > 0
}
}
impl<T> Drop for BumpAlloc<T> {
fn drop(&mut self) {
mem::take(&mut self.queue);
mem::take(&mut self.free);
let layout = Layout::array::<T>(self.n).unwrap();
unsafe {
dealloc(self.buffer.as_ptr() as *mut u8, layout);
}
}
}
pub struct Allocations<'a, T> {
ba: &'a BumpAlloc<T>,
n: usize,
}
impl<'a, T> Iterator for Allocations<'a, T> {
type Item = NonNull<T>;
fn next(&mut self) -> Option<NonNull<T>> {
while self.ba.free.get(self.n) == Some(&true) {
self.n += 1;
}
if self.ba.free.get(self.n).is_some() {
let ptr = unsafe { self.ba.buffer.as_ptr().add(self.n) };
self.n += 1;
NonNull::new(ptr)
} else {
None
}
}
}