Skip to main content

aeon_tk/mesh/
store.rs

1use std::cell::UnsafeCell;
2
3use bumpalo::Bump;
4use thread_local::ThreadLocal;
5
6/// A per-thread store that contains memory pools and caches for multi-threaded
7/// workloads.
8#[derive(Debug, Default)]
9pub struct MeshStore {
10    /// Linear allocator for each thread.
11    arena: Bump,
12}
13
14impl MeshStore {
15    /// Allocates scratch data for use by the current thread.
16    pub fn scratch<T: Default>(&self, len: usize) -> &mut [T] {
17        self.arena.alloc_slice_fill_default(len)
18    }
19
20    /// Resets memory cached in mesh store.
21    pub fn reset(&mut self) {
22        self.arena.reset();
23    }
24}
25
26/// A data type which stores a pool of thread local variables.
27/// Thus allowing each thread to access one copy of `T` mutably.
28#[derive(Debug)]
29pub struct UnsafeThreadCache<T: Send> {
30    pool: ThreadLocal<UnsafeCell<T>>,
31}
32
33impl<T: Send> UnsafeThreadCache<T> {
34    /// Constructs an empty thread cache.
35    pub fn new() -> Self {
36        Self::default()
37    }
38}
39
40impl<T: Send + Default> UnsafeThreadCache<T> {
41    /// Retrieves the object `T` associated with this thread, initializing the
42    /// default value in place if this has not already been done.
43    pub unsafe fn get_or_default(&self) -> &mut T {
44        unsafe { &mut *self.pool.get_or_default().get() }
45    }
46}
47
48impl<T: Send> Default for UnsafeThreadCache<T> {
49    fn default() -> Self {
50        Self {
51            pool: ThreadLocal::default(),
52        }
53    }
54}