use std::{cell::Cell, marker::PhantomData, mem};
use crate::{
alloc,
depot::{capacity, queue::ring},
};
pub struct Pool<T> {
pub(super) storage: ring::raw::Storage<T, Cell<u32>>,
pub(super) state: Cell<ring::raw::State<u32>>,
invariant: PhantomData<Cell<T>>,
}
impl<T> Pool<T> {
pub fn try_new(capacity: capacity::Count) -> Result<Self, alloc::Error> {
Ok(Self {
storage: ring::raw::Storage::try_new(capacity, Cell::new(capacity.raw()))?,
state: Cell::new(ring::raw::State::EMPTY),
invariant: PhantomData,
})
}
pub fn try_reserve(&self) -> Result<ring::Lease<'_, T>, ring::Full> {
let free = self.storage.free();
let current = free.get();
if current == 0 {
return Err(ring::Full {
capacity: self.storage.extent(),
});
}
free.set(current - 1);
Ok(ring::Lease { pool: self })
}
pub fn take_front(&self) -> Option<(T, ring::Lease<'_, T>)> {
Some((ring::raw::Storage::take(self)?, ring::Lease { pool: self }))
}
pub fn len(&self) -> usize {
self.state.get().len()
}
pub fn count(&self) -> capacity::Count {
self.state.get().count()
}
pub fn is_empty(&self) -> bool {
self.state.get().is_empty()
}
pub const fn capacity(&self) -> usize {
self.storage.extent().get()
}
}
impl<T> Drop for Pool<T> {
fn drop(&mut self) {
if mem::needs_drop::<T>() {
ring::raw::Storage::retire_pool(self);
}
}
}
const _: () = assert!(size_of::<Pool<u64>>() == size_of::<ring::Fifo<u64>>());