Files
@ 5da3dcf76c51
Branch filter:
Location: CSY/reowolf/src/collections/freelist.rs
5da3dcf76c51
9.7 KiB
application/rls-services+xml
Remove stale todo
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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | use std::marker::PhantomData;
use alloc::raw_vec::RawVec;
/// Entry in a freelist. Contains a generation number to ensure silly mistakes
/// using an item's index after freeing it.
struct Entry<T> {
generation: usize,
item: T,
}
/// Key of an item in the freelist. Contains a generation number to prevent
/// use-after-free during development.
// TODO: Two usizes are probably overkill
#[derive(Copy, Clone)]
pub struct Key<T> {
generation: usize,
index: usize,
_type: PhantomData<T>,
}
/// Generic freelist structure. Item insertion/retrieval/deletion works like a
/// HashMap through keys.
pub struct FreeList<T> {
items: *mut Entry<T>,
capacity: usize,
length: usize,
free: Vec<usize>,
}
impl<T> FreeList<T> {
pub fn new() -> Self<T> {
std::alloc::Layout::from_size_align()
Self{
items: std::ptr::null_mut(),
capacity: 0,
length: 0,
free: Vec::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
alloc::
Self{
items: std::,
free: Vec::with_capacity(capacity),
length: 0,
}
}
/// Inserts a new item into the freelist. Will return a key that can be used
/// to retrieve the item and delete it.
pub fn insert(&mut self, item: T) -> Key<T> {
let mut generation;
let mut index;
if self.free.is_empty() {
// No free elements, make sure we have enough capacity
if self.length == self.items.capacity() {
self.items.reserve(self.length, 1);
}
// Now we do
generation = 0;
index = self.length;
unsafe {
let target = self.items.ptr().add(self.length);
std::ptr::write(&mut target.item, item);
self.length += 1;
}
} else {
// We have a free spot. Note that the generation is incremented upon
// freeing an item. So we can just take the current generation value
// here.
index = self.free.pop().unwrap();
unsafe {
let target = self.items.ptr().add(self.length);
generation = target.generation;
std::ptr::write(&mut target.item, item);
}
}
Key { generation, index, _type: PhantomData::default() }
}
/// Removes the entry using the provided key. Will panic if the element was
/// removed already.
pub fn erase(&mut self, index: Key<T>) {
// This should always be the case
debug_assert!(index.index < self.length);
// Retrieve element and make sure that the generation matches
unsafe {
let entry = self.items.ptr().add(index.index);
assert_eq!(entry.generation, entry.generation);
*entry.generation += 1;
std::ptr::drop_in_place(&mut entry.item);
}
// Add the entry to the freelist.
self.free.push(index.index);
}
}
impl<T> std::ops::Index<Key<T>> for FreeList<T> {
type Output = T;
fn index(&self, index: &Key<T>) -> &Self::Output {
debug_assert!(index.index < self.length);
unsafe {
let entry = self.items.ptr().add(index.index);
assert_eq!(entry.generation, index.generation);
return &entry.item;
}
}
}
impl<T> std::ops::IndexMut<Key<T>> for FreeList<T> {
fn index_mut(&self, index: &Key<T>) -> &Self::Output {
debug_assert!(index.index < self.length);
unsafe {
let entry = self.items.ptr().add(index.index);
assert_eq!(entry.generation, index.generation);
return &mut entry.item;
}
}
}
impl<T> Drop for FreeList<T> {
fn drop(&mut self) {
// Sort free indices to use them while traversing the allocated items
self.free.sort_unstable();
let free_length = self.free.len();
let mut next_free_idx = 1;
let mut next_free_item = usize::MAX;
if free_length != 0 {
next_free_item = self.free[0];
}
// Go through all items. If we didn't yet drop the item, then we do
// so here.
for item_idx in 0..self.length {
if item_idx == next_free_item {
if next_free_idx < free_length {
next_free_item = self.free[next_free_idx];
next_free_idx += 1;
} else {
next_free_item = usize::MAX;
}
// Skipped the current item, go to the next one
continue
}
// Need to deallocate the current item
unsafe {
let entry = self.items.ptr().add(item_idx);
std::ptr::drop_in_place(&mut entry.item);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
struct Counters {
constructed: Arc<AtomicU32>,
destructed: Arc<AtomicU32>,
}
impl Counters {
pub fn new() -> Self {
Self{
constructed: Arc::new(AtomicU32::new(0)),
destructed: Arc::new(AtomicU32::new(0)),
}
}
}
struct TestEntity {
counters: Counters,
pub value: u32,
}
impl TestEntity {
pub fn new(counters: &Counters, value: u32) -> Self {
counters.constructed.fetch_add(1, Ordering::SeqCst);
return TestEntity{
counters: Counters{
constructed: counters.constructed.clone(),
destructed: counters.destructed.clone(),
},
value,
}
}
}
impl Drop for TestEntity {
fn drop(&mut self) {
self.counters.destructed.fetch_add(1, Ordering::SeqCst);
}
}
#[test]
fn only_constructing() {
const NUM_CREATED: u32 = 3;
let counters = Counters::new();
let mut list = FreeList::new();
for i in 0..NUM_CREATED {
list.insert(TestEntity::new(&counters, i));
assert_eq!(counters.constructed.load(Ordering::AcqRel), i + 1);
}
// Everything is constructed, check freelist
assert_eq!(counters.constructed.load(Ordering::AcqRel), NUM_CREATED);
assert_eq!(list.length, 3);
assert!(list.items.capacity() >= 3);
assert!(list.free.is_empty());
// Drop and check everything is properly dropped
drop(list);
assert_eq!(counters.destructed.load(Ordering::AcqRel), NUM_CREATED)
}
#[test]
fn reusing_slots() {
const NUM_ROUNDS: u32 = 10;
const NUM_IN_USE: u32 = 10;
let counters = Counters::new();
let mut list = FreeList::new();
let mut indices = Vec::with_capacity(NUM_IN_USE as usize);
for round_idx in 0..NUM_ROUNDS {
indices.clear();
// Adding entries
for i in 0..NUM_IN_USE {
let new_index = list.insert(TestEntity::new(&counters, i));
indices.push(new_index);
}
// Length should always remain the same as the total number of
// entries in use
assert_eq!(list.length, NUM_IN_USE as usize);
// Removing entries, and making sure that everything is still
// accessible
for idx in 0..NUM_IN_USE {
// Make sure we can still retrieve the item we're going to delete
let idx_to_remove = NUM_IN_USE - 1 - idx;
let pop_index = indices.pop().unwrap();
let entry = &list[pop_index];
assert_eq!(entry.value, idx_to_remove);
// Remove the entry and make sure the other ones are still
// accessible
list.erase(pop_index);
for remaining_idx in 0..idx_to_remove + 1 {
let remaining_key = &indices[remaining_idx as usize];
let remaining_entry = &list[*remaining_key];
assert_eq!(remaining_entry.value, remaining_idx);
}
}
// Now that we're empty, our constructed and destructed counts
// should match
let expected_count = (round_idx + 1) * NUM_IN_USE;
assert_eq!(counters.constructed.load(Ordering::AcqRel), expected_count);
assert_eq!(counters.destructed.load(Ordering::AcqRel), expected_count);
}
// Make sure the capacity didn't grow out of bounds, maximum growth rate
// I've ever encountered on `Vec`s is 2. So:
assert!(list.items.capacity() >= NUM_IN_USE as usize && list.items.capacity() < 2*NUM_IN_USE as usize);
// Finally, when we drop the list we shouldn't be destructing anything
// anymore.
drop(list);
let final_count = NUM_ROUNDS * NUM_IN_USE;
assert_eq!(counters.constructed.load(Ordering::AcqRel), final_count);
assert_eq!(counters.destructed.load(Ordering::AcqRel), final_count);
}
#[test]
#[should_panic]
fn panic_on_reused_key_of_empty_slot() {
let counters = Counters::new();
let mut list = FreeList::new();
let key = list.insert(TestEntity::new(&counters, 0));
list.erase(key);
let entry = &list[key];
}
#[test]
#[should_panic]
fn panic_on_reused_key_of_used_slot() {
let counters = Counters::new();
let mut list = FreeList::new();
let key1 = list.insert(TestEntity::new(&counters, 0));
list.erase(key1);
let key2 = list.insert(TestEntity::new(&counters, 0));
assert_eq!(key1.index, key2.index);
assert_ne!(key1.generation, key2.generation);
let entry = &list[key1];
}
}
|