#![no_std]
extern crate alloc;
#[cfg(not(loom))]
use alloc::sync::Arc;
#[cfg(not(loom))]
use core::sync::atomic::{AtomicUsize, Ordering};
#[cfg(loom)]
use loom::sync::atomic::{AtomicUsize, Ordering};
#[cfg(loom)]
use loom::sync::Arc;
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::cell::UnsafeCell;
use core::fmt;
pub mod oracle;
#[derive(Clone)]
pub struct SampleRing<T, const N: usize> {
head: usize,
len: usize,
slots: [Option<T>; N],
}
impl<T, const N: usize> SampleRing<T, N> {
#[must_use]
pub fn new() -> Self {
Self {
head: 0,
len: 0,
slots: core::array::from_fn(|_| None),
}
}
pub fn push(&mut self, value: T) -> Option<T> {
if N == 0 {
return Some(value);
}
if self.len == N {
let evicted = match self.slots.get_mut(self.head) {
Some(slot) => slot.replace(value),
None => return Some(value),
};
self.head = (self.head + 1) % N;
return evicted;
}
let slot = (self.head + self.len) % N;
match self.slots.get_mut(slot) {
Some(cell) => {
*cell = Some(value);
self.len += 1;
None
}
None => Some(value),
}
}
#[must_use]
pub fn iter(&self) -> Iter<'_, T, N> {
Iter { ring: self, pos: 0 }
}
#[must_use]
pub const fn len(&self) -> usize {
self.len
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
#[must_use]
pub fn last(&self) -> Option<&T> {
if self.len == 0 {
return None;
}
let slot = (self.head + self.len - 1) % N;
self.slots.get(slot).and_then(Option::as_ref)
}
}
impl<T, const N: usize> Default for SampleRing<T, N> {
fn default() -> Self {
Self::new()
}
}
impl<T: fmt::Debug, const N: usize> fmt::Debug for SampleRing<T, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<'a, T, const N: usize> IntoIterator for &'a SampleRing<T, N> {
type Item = &'a T;
type IntoIter = Iter<'a, T, N>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Clone)]
pub struct Iter<'a, T, const N: usize> {
ring: &'a SampleRing<T, N>,
pos: usize,
}
impl<'a, T, const N: usize> Iterator for Iter<'a, T, N> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.pos >= self.ring.len {
return None;
}
let slot = (self.ring.head + self.pos) % N;
self.pos += 1;
self.ring.slots.get(slot).and_then(Option::as_ref)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.ring.len - self.pos;
(remaining, Some(remaining))
}
}
impl<T, const N: usize> ExactSizeIterator for Iter<'_, T, N> {}
pub struct SpscRing<T, const CAP: usize> {
mask: usize,
head: PaddedCursor,
tail: PaddedCursor,
slots: Box<[Slot<T>]>,
}
#[repr(align(64))]
#[derive(Default)]
struct PaddedCursor(AtomicUsize);
struct Slot<T> {
sequence: AtomicUsize,
value: UnsafeCell<Option<T>>,
}
#[allow(unsafe_code)] unsafe impl<T: Send, const CAP: usize> Send for SpscRing<T, CAP> {}
#[allow(unsafe_code)] unsafe impl<T: Send, const CAP: usize> Sync for SpscRing<T, CAP> {}
#[allow(unsafe_code)]
impl<T, const CAP: usize> SpscRing<T, CAP> {
#[must_use]
pub fn new() -> Self {
const {
assert!(
CAP.is_power_of_two() && CAP >= 2,
"SpscRing capacity must be a power of two >= 2 (CAP == 1 makes \
the sequence protocol's write and consume transitions collide, \
losing unconsumed values)"
);
}
let slots = (0..CAP)
.map(|i| Slot {
sequence: AtomicUsize::new(i),
value: UnsafeCell::new(None),
})
.collect::<Vec<_>>();
Self {
mask: CAP - 1,
head: PaddedCursor::default(),
tail: PaddedCursor::default(),
slots: slots.into_boxed_slice(),
}
}
#[must_use = "a full ring hands the value back: dropping it loses data"]
pub fn try_push(&self, value: T) -> Option<T> {
let pos = self.head.0.load(Ordering::Relaxed);
#[allow(clippy::indexing_slicing)] let slot = &self.slots[pos & self.mask];
if slot.sequence.load(Ordering::Acquire) != pos {
return Some(value); }
unsafe {
*slot.value.get() = Some(value);
}
slot.sequence.store(pos.wrapping_add(1), Ordering::Release);
self.head.0.store(pos.wrapping_add(1), Ordering::Relaxed);
None
}
#[must_use]
pub fn try_pop(&self) -> Option<T> {
let pos = self.tail.0.load(Ordering::Relaxed);
#[allow(clippy::indexing_slicing)] let slot = &self.slots[pos & self.mask];
if slot.sequence.load(Ordering::Acquire) != pos + 1 {
return None; }
let value = unsafe { (*slot.value.get()).take() };
slot.sequence
.store(pos.wrapping_add(CAP), Ordering::Release);
self.tail.0.store(pos.wrapping_add(1), Ordering::Relaxed);
value
}
#[must_use]
pub fn len(&self) -> usize {
self.head
.0
.load(Ordering::Relaxed)
.wrapping_sub(self.tail.0.load(Ordering::Relaxed))
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<T, const CAP: usize> Default for SpscRing<T, CAP> {
fn default() -> Self {
Self::new()
}
}
impl<T, const CAP: usize> fmt::Debug for SpscRing<T, CAP> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SpscRing")
.field("cap", &CAP)
.field("len", &self.len())
.finish()
}
}
#[must_use]
pub fn channel<T, const CAP: usize>() -> (SpscSender<T, CAP>, SpscReceiver<T, CAP>) {
let ring = Arc::new(SpscRing::new());
(
SpscSender {
ring: Arc::clone(&ring),
},
SpscReceiver { ring },
)
}
pub struct SpscSender<T, const CAP: usize> {
ring: Arc<SpscRing<T, CAP>>,
}
impl<T, const CAP: usize> SpscSender<T, CAP> {
#[inline]
pub fn send(&self, value: T) -> Result<(), T> {
match self.ring.try_push(value) {
None => Ok(()),
Some(back) => Err(back),
}
}
}
pub struct SpscReceiver<T, const CAP: usize> {
ring: Arc<SpscRing<T, CAP>>,
}
impl<T, const CAP: usize> SpscReceiver<T, CAP> {
#[inline]
#[must_use]
pub fn recv(&self) -> Option<T> {
self.ring.try_pop()
}
}