use std::collections::VecDeque;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use super::waiters::{Signal, WaitList, lock, wake_all};
use crate::kernel::{Effect, fail, from_async, succeed, suspend, sync};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum QueueError {
Disconnected,
}
impl fmt::Display for QueueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
QueueError::Disconnected => write!(f, "queue is disconnected"),
}
}
}
impl std::error::Error for QueueError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Strategy {
Bounded,
Dropping,
Sliding,
Unbounded,
}
enum Put<A> {
Stored,
Refused(A),
Full(A),
}
pub(crate) struct State<A> {
buf: VecDeque<A>,
cap: usize,
strategy: Strategy,
shutdown: bool,
takers: WaitList<(), A>,
offerers: WaitList<A, Option<A>>,
}
impl<A> State<A> {
fn admit_offerers(&mut self, ws: &mut Vec<Waker>) {
while self.buf.len() < self.cap {
let Some((id, item, w)) = self.offerers.pop_front() else {
break;
};
self.buf.push_back(item);
self.offerers.grant(id, None);
ws.push(w);
}
}
fn put(&mut self, item: A, ws: &mut Vec<Waker>) -> Put<A> {
if self.shutdown {
return Put::Refused(item);
}
let item = match self.takers.grant_front(item) {
Ok(((), w)) => {
ws.push(w);
return Put::Stored;
}
Err(item) => item,
};
if self.buf.len() < self.cap {
self.buf.push_back(item);
return Put::Stored;
}
match self.strategy {
Strategy::Sliding => {
self.buf.pop_front();
self.buf.push_back(item);
Put::Stored
}
Strategy::Dropping => Put::Refused(item),
Strategy::Bounded => Put::Full(item),
Strategy::Unbounded => {
self.buf.push_back(item);
Put::Stored
}
}
}
fn pop(&mut self, ws: &mut Vec<Waker>) -> Option<A> {
let v = self.buf.pop_front()?;
self.admit_offerers(ws);
Some(v)
}
fn put_back(&mut self, item: A, ws: &mut Vec<Waker>) {
match self.takers.grant_front(item) {
Ok(((), w)) => ws.push(w),
Err(item) => self.buf.push_front(item),
}
}
}
#[repr(align(128))]
pub(crate) struct Inner<A> {
state: Mutex<State<A>>,
closed: Arc<Signal>,
}
pub struct Queue<A> {
inner: Arc<Inner<A>>,
}
impl<A> Clone for Queue<A> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
}
}
}
impl<A> fmt::Debug for Queue<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let st = lock(&self.inner.state);
f.debug_struct("Queue")
.field("strategy", &st.strategy)
.field("size", &st.buf.len())
.field("shutdown", &st.shutdown)
.finish()
}
}
impl<A: Send + 'static> Queue<A> {
fn with(strategy: Strategy, cap: usize) -> Self {
Self {
inner: Arc::new(Inner {
state: Mutex::new(State {
buf: VecDeque::new(),
cap,
strategy,
shutdown: false,
takers: WaitList::default(),
offerers: WaitList::default(),
}),
closed: Arc::new(Signal::default()),
}),
}
}
pub fn bounded(capacity: usize) -> Self {
Self::with(Strategy::Bounded, capacity.max(1))
}
pub fn unbounded() -> Self {
Self::with(Strategy::Unbounded, usize::MAX)
}
pub fn dropping(capacity: usize) -> Self {
Self::with(Strategy::Dropping, capacity.max(1))
}
pub fn sliding(capacity: usize) -> Self {
Self::with(Strategy::Sliding, capacity.max(1))
}
pub fn capacity(&self) -> Option<usize> {
let st = lock(&self.inner.state);
(st.strategy != Strategy::Unbounded).then_some(st.cap)
}
pub(crate) fn offer_future(&self, item: A) -> OfferFuture<A> {
OfferFuture {
inner: Arc::clone(&self.inner),
item: Some(item),
id: None,
}
}
pub(crate) fn put_now(&self, item: A) -> Result<bool, A> {
let mut ws = Vec::new();
let put = lock(&self.inner.state).put(item, &mut ws);
wake_all(ws);
match put {
Put::Stored => Ok(true),
Put::Refused(_) => Ok(false),
Put::Full(item) => Err(item),
}
}
pub(crate) fn pop_now(&self) -> Result<A, bool> {
let mut ws = Vec::new();
let head = {
let mut st = lock(&self.inner.state);
match st.pop(&mut ws) {
Some(v) => Ok(v),
None => Err(st.shutdown),
}
};
wake_all(ws);
head
}
pub(crate) fn take_one_future(&self) -> TakeOneFuture<A> {
TakeOneFuture {
inner: Arc::clone(&self.inner),
id: None,
}
}
pub(crate) fn take_future(&self, min: usize, max: usize) -> TakeFuture<A> {
TakeFuture {
inner: Arc::clone(&self.inner),
min,
max,
got: Vec::new(),
id: None,
}
}
pub fn offer<E, R>(&self, item: A) -> Effect<bool, E, R>
where
E: Send + 'static,
R: Send + Sync + 'static,
{
let q = self.clone();
suspend(move || match q.put_now(item) {
Ok(stored) => succeed(stored),
Err(item) => from_async(move || async move { Ok(q.offer_future(item).await.is_ok()) }),
})
}
pub fn try_offer<E, R>(&self, item: A) -> Effect<bool, E, R> {
let inner = Arc::clone(&self.inner);
sync(move || {
let mut ws = Vec::new();
let stored = matches!(lock(&inner.state).put(item, &mut ws), Put::Stored);
wake_all(ws);
stored
})
}
pub fn offer_all<E, R>(&self, items: impl IntoIterator<Item = A>) -> Effect<Vec<A>, E, R>
where
E: Send + 'static,
R: Send + Sync + 'static,
{
let items: Vec<A> = items.into_iter().collect();
let q = self.clone();
from_async(move || async move {
let mut left = Vec::new();
for item in items {
if let Err(item) = q.offer_future(item).await {
left.push(item);
}
}
Ok(left)
})
}
pub fn try_offer_all<E, R>(&self, items: impl IntoIterator<Item = A>) -> Effect<Vec<A>, E, R> {
let items: Vec<A> = items.into_iter().collect();
let inner = Arc::clone(&self.inner);
sync(move || {
let mut ws = Vec::new();
let left = {
let mut st = lock(&inner.state);
items
.into_iter()
.filter_map(|item| match st.put(item, &mut ws) {
Put::Stored => None,
Put::Refused(item) | Put::Full(item) => Some(item),
})
.collect()
};
wake_all(ws);
left
})
}
fn take_between_effect<R>(&self, min: usize, max: usize) -> Effect<Vec<A>, QueueError, R>
where
R: Send + Sync + 'static,
{
let q = self.clone();
from_async(move || q.take_future(min, max))
}
pub fn take<R: Send + Sync + 'static>(&self) -> Effect<A, QueueError, R> {
let q = self.clone();
suspend(move || match q.pop_now() {
Ok(v) => succeed(v),
Err(true) => fail(QueueError::Disconnected),
Err(false) => from_async(move || q.take_one_future()),
})
}
pub fn take_all<R: Send + Sync + 'static>(&self) -> Effect<Vec<A>, QueueError, R> {
self.take_between_effect(1, usize::MAX)
}
pub fn take_up_to<R: Send + Sync + 'static>(&self, n: usize) -> Effect<Vec<A>, QueueError, R> {
if n == 0 {
return crate::kernel::succeed(Vec::new());
}
self.take_between_effect(1, n)
}
pub fn take_n<R: Send + Sync + 'static>(&self, n: usize) -> Effect<Vec<A>, QueueError, R> {
self.take_between_effect(n, n)
}
pub fn take_between<R: Send + Sync + 'static>(
&self,
min: usize,
max: usize,
) -> Effect<Vec<A>, QueueError, R> {
if min > max || max == 0 {
return crate::kernel::succeed(Vec::new());
}
self.take_between_effect(min, max)
}
pub fn poll<R>(&self) -> Effect<Option<A>, QueueError, R> {
let inner = Arc::clone(&self.inner);
let step = move || {
let mut ws = Vec::new();
let out = {
let mut st = lock(&inner.state);
match st.pop(&mut ws) {
Some(v) => Ok(Some(v)),
None if st.shutdown => Err(QueueError::Disconnected),
None => Ok(None),
}
};
wake_all(ws);
out
};
crate::kernel::suspend(move || match step() {
Ok(v) => crate::kernel::succeed(v),
Err(e) => crate::kernel::fail(e),
})
}
pub fn size<E, R>(&self) -> Effect<usize, E, R> {
let inner = Arc::clone(&self.inner);
sync(move || lock(&inner.state).buf.len())
}
pub fn is_empty<E, R>(&self) -> Effect<bool, E, R> {
let inner = Arc::clone(&self.inner);
sync(move || lock(&inner.state).buf.is_empty())
}
pub fn is_full<E, R>(&self) -> Effect<bool, E, R> {
let inner = Arc::clone(&self.inner);
sync(move || {
let st = lock(&inner.state);
st.strategy != Strategy::Unbounded && st.buf.len() >= st.cap
})
}
pub fn shutdown<E, R>(&self) -> Effect<(), E, R> {
let inner = Arc::clone(&self.inner);
sync(move || shutdown_now(&inner))
}
pub fn is_shutdown<E, R>(&self) -> Effect<bool, E, R> {
let inner = Arc::clone(&self.inner);
sync(move || lock(&inner.state).shutdown)
}
pub fn await_shutdown<E, R>(&self) -> Effect<(), E, R>
where
E: Send + 'static,
R: Send + Sync + 'static,
{
let closed = Arc::clone(&self.inner.closed);
from_async(move || async move {
closed.wait().await;
Ok(())
})
}
pub(crate) fn shutdown_sync(&self) {
shutdown_now(&self.inner);
}
pub(crate) fn is_full_now(&self) -> bool {
let st = lock(&self.inner.state);
st.strategy != Strategy::Unbounded && st.buf.len() >= st.cap
}
pub(crate) fn size_now(&self) -> usize {
lock(&self.inner.state).buf.len()
}
}
fn shutdown_now<A>(inner: &Inner<A>) {
let ws = {
let mut st = lock(&inner.state);
if st.shutdown {
return;
}
st.shutdown = true;
let mut ws: Vec<Waker> = st.takers.drain().into_iter().map(|(_, (), w)| w).collect();
for (id, item, w) in st.offerers.drain() {
st.offerers.grant(id, Some(item));
ws.push(w);
}
ws
};
wake_all(ws);
inner.closed.fire();
}
pub(crate) struct OfferFuture<A> {
inner: Arc<Inner<A>>,
item: Option<A>,
id: Option<u64>,
}
impl<A> Unpin for OfferFuture<A> {}
impl<A> Future for OfferFuture<A> {
type Output = Result<(), A>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), A>> {
let this = &mut *self;
let mut ws = Vec::new();
let out = {
let mut st = lock(&this.inner.state);
match (this.id, this.item.take()) {
(Some(id), _) => match st.offerers.take_grant(id) {
Some(None) => {
this.id = None;
Poll::Ready(Ok(()))
}
Some(Some(item)) => {
this.id = None;
Poll::Ready(Err(item))
}
None => {
st.offerers.refresh(id, cx.waker());
Poll::Pending
}
},
(None, Some(item)) => match st.put(item, &mut ws) {
Put::Stored => Poll::Ready(Ok(())),
Put::Refused(item) => Poll::Ready(Err(item)),
Put::Full(item) => {
this.id = Some(st.offerers.push(item, cx.waker()));
Poll::Pending
}
},
(None, None) => panic!("id_effect: queue offer polled after completion"),
}
};
wake_all(ws);
out
}
}
impl<A> Drop for OfferFuture<A> {
fn drop(&mut self) {
if let Some(id) = self.id.take() {
let mut st = lock(&self.inner.state);
if st.offerers.take_grant(id).is_none() {
st.offerers.remove(id);
}
}
}
}
pub(crate) struct TakeOneFuture<A> {
inner: Arc<Inner<A>>,
id: Option<u64>,
}
impl<A> Unpin for TakeOneFuture<A> {}
impl<A> Future for TakeOneFuture<A> {
type Output = Result<A, QueueError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
let mut ws = Vec::new();
let out = {
let mut st = lock(&this.inner.state);
if let Some(id) = this.id
&& let Some(v) = st.takers.take_grant(id)
{
this.id = None;
Poll::Ready(Ok(v))
} else if let Some(v) = st.pop(&mut ws) {
if let Some(id) = this.id.take() {
st.takers.remove(id);
}
Poll::Ready(Ok(v))
} else if st.shutdown {
if let Some(id) = this.id.take() {
st.takers.remove(id);
}
Poll::Ready(Err(QueueError::Disconnected))
} else {
match this.id {
Some(id) if st.takers.refresh(id, cx.waker()) => {}
_ => this.id = Some(st.takers.push((), cx.waker())),
}
Poll::Pending
}
};
wake_all(ws);
out
}
}
impl<A> Drop for TakeOneFuture<A> {
fn drop(&mut self) {
let Some(id) = self.id.take() else {
return;
};
let mut ws = Vec::new();
{
let mut st = lock(&self.inner.state);
match st.takers.take_grant(id) {
Some(v) => st.put_back(v, &mut ws),
None => {
st.takers.remove(id);
}
}
}
wake_all(ws);
}
}
pub(crate) struct TakeFuture<A> {
inner: Arc<Inner<A>>,
min: usize,
max: usize,
got: Vec<A>,
id: Option<u64>,
}
impl<A> Unpin for TakeFuture<A> {}
impl<A> Future for TakeFuture<A> {
type Output = Result<Vec<A>, QueueError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
let mut ws = Vec::new();
let out = {
let mut st = lock(&this.inner.state);
if let Some(id) = this.id
&& let Some(v) = st.takers.take_grant(id)
{
this.id = None;
this.got.push(v);
}
while this.got.len() < this.max {
match st.pop(&mut ws) {
Some(v) => this.got.push(v),
None => break,
}
}
if this.got.len() >= this.min {
if let Some(id) = this.id.take() {
st.takers.remove(id);
}
Poll::Ready(Ok(std::mem::take(&mut this.got)))
} else if st.shutdown {
if let Some(id) = this.id.take() {
st.takers.remove(id);
}
for v in std::mem::take(&mut this.got).into_iter().rev() {
st.put_back(v, &mut ws);
}
Poll::Ready(Err(QueueError::Disconnected))
} else {
match this.id {
Some(id) if st.takers.refresh(id, cx.waker()) => {}
_ => this.id = Some(st.takers.push((), cx.waker())),
}
Poll::Pending
}
};
wake_all(ws);
out
}
}
impl<A> Drop for TakeFuture<A> {
fn drop(&mut self) {
let id = self.id.take();
if id.is_none() && self.got.is_empty() {
return;
}
let mut ws = Vec::new();
{
let mut st = lock(&self.inner.state);
if let Some(id) = id {
match st.takers.take_grant(id) {
Some(v) => self.got.push(v),
None => {
st.takers.remove(id);
}
}
}
for v in std::mem::take(&mut self.got).into_iter().rev() {
st.put_back(v, &mut ws);
}
}
wake_all(ws);
}
}