use std::{iter, mem, num::NonZero, slice};
pub use full::Full;
pub use lease::Lease;
pub use pool::Pool;
use crate::{alloc, depot::capacity};
mod full;
pub mod inline;
mod lease;
mod pool;
pub mod raw;
pub struct Fifo<T> {
storage: raw::Storage<T>,
state: raw::State<u32>,
}
impl<T> Fifo<T> {
pub fn try_new(capacity: capacity::Count) -> Result<Self, alloc::Error> {
Ok(Self {
storage: raw::Storage::try_new(capacity, ())?,
state: raw::State::EMPTY,
})
}
pub fn try_with(capacity: NonZero<u32>, first: Option<T>) -> Result<Self, alloc::Error> {
let mut queue = Self::try_new(capacity::Count::new(capacity.get()))?;
if let Some(first) = first {
raw::Vacant(&mut queue).push_back(first);
}
Ok(queue)
}
pub fn vacant(&mut self) -> Option<raw::Vacant<'_, T>> {
self.try_vacant().ok()
}
pub fn try_vacant(&mut self) -> Result<raw::Vacant<'_, T>, Full> {
let capacity = self.storage.extent();
if self.len() == capacity.get() {
return Err(Full { capacity });
}
Ok(raw::Vacant(self))
}
pub fn push_back(&mut self, value: T) -> Result<(), T> {
let Some(vacant) = self.vacant() else {
return Err(value);
};
vacant.push_back(value);
Ok(())
}
pub fn pop_front(&mut self) -> Option<T> {
Some(self.front_entry()?.remove())
}
pub fn front_entry(&mut self) -> Option<raw::Front<'_, T>> {
if self.is_empty() {
return None;
}
Some(raw::Front(self))
}
pub fn clear(&mut self) {
if !self.is_empty() {
if mem::needs_drop::<T>() {
raw::Storage::retire(self);
} else {
self.state = raw::State::EMPTY;
}
}
}
pub const fn capacity(&self) -> usize {
self.storage.extent().get()
}
pub fn len(&self) -> usize {
self.state.len()
}
pub fn count(&self) -> capacity::Count {
self.state.count()
}
pub fn is_empty(&self) -> bool {
self.state.is_empty()
}
pub fn is_full(&self) -> bool {
self.len() == self.capacity()
}
pub fn front(&self) -> Option<&T> {
raw::Storage::front(self)
}
pub fn get(&self, index: usize) -> Option<&T> {
raw::Storage::get(self, index)
}
pub fn as_slices(&self) -> (&[T], &[T]) {
raw::Storage::slices(self)
}
}
impl<'a, T> IntoIterator for &'a Fifo<T> {
type Item = &'a T;
type IntoIter = iter::Chain<slice::Iter<'a, T>, slice::Iter<'a, T>>;
fn into_iter(self) -> Self::IntoIter {
let (front, back) = self.as_slices();
front.iter().chain(back)
}
}
impl<'a, T> IntoIterator for &'a mut Fifo<T> {
type Item = &'a mut T;
type IntoIter = iter::Chain<slice::IterMut<'a, T>, slice::IterMut<'a, T>>;
fn into_iter(self) -> Self::IntoIter {
let (front, back) = raw::Storage::slices_mut(self);
front.iter_mut().chain(back)
}
}
impl<T> Drop for Fifo<T> {
fn drop(&mut self) {
if mem::needs_drop::<T>() {
raw::Storage::retire(self);
}
}
}
const _: () = {
assert!(size_of::<Fifo<u64>>() == 3 * size_of::<usize>());
assert!(size_of::<raw::Front<'static, u64>>() == size_of::<usize>());
assert!(size_of::<Option<raw::Front<'static, u64>>>() == size_of::<usize>());
assert!(size_of::<raw::Vacant<'static, u64>>() == size_of::<usize>());
};