Skip to main content

moirai_core/pool/
global.rs

1use super::stack::LockFreeStack;
2
3/// Global object pool for cross-thread sharing.
4///
5/// A lock-free stack of reusable objects shared by all threads; there is no
6/// per-thread caching layer. [`Self::get`] pops a pooled object or constructs
7/// a new one via `T::default()`; [`Self::put`] returns an object, dropping it
8/// when the pool already holds `max_size` objects.
9pub struct GlobalPool<T> {
10    /// Global stack of available objects, sized to `max_size` slots.
11    global: LockFreeStack<T>,
12}
13
14impl<T: Default + Send + 'static> GlobalPool<T> {
15    /// Create a new global pool retaining at most `max_size` objects.
16    #[must_use]
17    pub fn new(max_size: usize) -> Self {
18        Self {
19            global: LockFreeStack::with_capacity(max_size),
20        }
21    }
22
23    /// Get an object from the pool, or construct a new one if the pool is empty.
24    pub fn get(&self) -> T {
25        self.global.pop().unwrap_or_default()
26    }
27
28    /// Return an object to the pool.
29    ///
30    /// When the pool already holds `max_size` objects the object is dropped;
31    /// this is the pool's documented retention cap, not an error condition.
32    pub fn put(&self, obj: T) {
33        if let Err(obj) = self.global.push(obj) {
34            drop(obj); // pool at capacity: intentional retention-cap drop
35        }
36    }
37
38    /// Clear all objects from the pool.
39    pub fn clear(&self) {
40        while self.global.pop().is_some() {}
41    }
42}