#![forbid(unsafe_op_in_unsafe_fn)]
#![deny(missing_docs)]
use concurrent_intrusive_collections::{
AtomicLink as Atomic, ConcurrentShardedStack as IntrusiveStack, SinglyLinked,
};
use std::cell::UnsafeCell;
use std::fmt;
pub use concurrent_intrusive_collections::PopError;
#[derive(Debug, PartialEq, Eq)]
pub enum PushError<T> {
Closed(T),
}
impl<T> PushError<T> {
pub fn into_inner(self) -> T {
match self {
Self::Closed(value) => value,
}
}
}
impl<T> fmt::Display for PushError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("stack is closed")
}
}
impl<T: fmt::Debug> std::error::Error for PushError<T> {}
struct Node<T> {
next: Atomic<Self>,
value: UnsafeCell<Option<T>>,
}
unsafe impl<T> SinglyLinked for Node<T> {
unsafe fn next(&self) -> &Atomic<Self> {
&self.next
}
}
unsafe impl<T: Send> Sync for Node<T> {}
impl<T> Node<T> {
fn new(value: T) -> Self {
Self {
next: Atomic::null(),
value: UnsafeCell::new(Some(value)),
}
}
unsafe fn take(&self) -> T {
unsafe { &mut *self.value.get() }
.take()
.expect("node consumed twice")
}
}
pub struct ConcurrentShardedStack<T: Send + 'static> {
inner: IntrusiveStack<Node<T>>,
}
impl<T: Send + 'static> Default for ConcurrentShardedStack<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Send + 'static> ConcurrentShardedStack<T> {
pub fn new() -> Self {
Self {
inner: IntrusiveStack::new(),
}
}
pub fn with_concurrency(shard_count: usize) -> Self {
Self {
inner: IntrusiveStack::with_concurrency(shard_count),
}
}
pub fn push(&self, value: T) -> Result<(), PushError<T>> {
self.inner
.push(Box::new(Node::new(value)))
.map_err(|error| {
let mut node = error.into_inner();
PushError::Closed(
node.value
.get_mut()
.take()
.expect("unpublished node is occupied"),
)
})
}
pub fn pop(&self) -> Result<T, PopError> {
self.inner.pop_with(|node| unsafe { node.take() })
}
pub fn close(&self) -> bool {
self.inner.close()
}
pub fn is_closed(&self) -> bool {
self.inner.is_closed()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn shard_count(&self) -> usize {
self.inner.shard_count()
}
}
impl<T: Send + 'static> Drop for ConcurrentShardedStack<T> {
fn drop(&mut self) {
let cleanup = scopeguard::guard(&self.inner, |inner| {
while let Ok(value) = inner.pop_with(|node| unsafe { node.take() }) {
drop(value);
}
});
while let Ok(value) = cleanup.pop_with(|node| unsafe { node.take() }) {
drop(value);
}
}
}
#[cfg(test)]
#[path = "tests/value.rs"]
mod tests;