use std::collections::{HashMap, VecDeque};
use std::future::Future;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::Waker;
use crate::capability::HNil;
use crate::failure::Cause;
use crate::failure::FiberId;
use crate::kernel::{AnyEnv, Effect, Instr, erase_exit};
pub(crate) fn lock<T: ?Sized>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn wake_all(ws: Vec<Waker>) {
for w in ws {
w.wake();
}
}
pub(crate) fn fail_cause<A, E, R>(cause: Cause<E>) -> Effect<A, E, R> {
Effect::pure(Err(cause))
}
pub(crate) fn with_fiber_id<A, E, R>(
f: impl FnOnce(FiberId) -> Effect<A, E, R> + Send + 'static,
) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
Effect::from_instr(Instr::WithFiber(Box::new(move |_, fiber| {
f(fiber.id()).into_instr()
})))
}
pub(crate) fn hnil_in<A, E, R>(eff: Effect<A, E, HNil>) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
Effect::from_instr(Instr::Provide(
Box::new(eff.into_instr()),
Box::new(|_| Arc::new(HNil) as AnyEnv),
))
}
pub(crate) fn from_cause_future<A, E, R, F, Fut>(make: F) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = Result<A, Cause<E>>> + Send + 'static,
{
Effect::from_instr(Instr::Future(Box::pin(
async move { erase_exit(make().await) },
)))
}
struct Entry<P> {
id: u64,
payload: P,
waker: Waker,
}
pub(crate) struct WaitList<P, T> {
next: u64,
queue: VecDeque<Entry<P>>,
granted: HashMap<u64, T>,
}
impl<P, T> Default for WaitList<P, T> {
fn default() -> Self {
Self {
next: 0,
queue: VecDeque::new(),
granted: HashMap::new(),
}
}
}
impl<P, T> WaitList<P, T> {
pub(crate) fn is_empty(&self) -> bool {
self.queue.is_empty()
}
pub(crate) fn len(&self) -> usize {
self.queue.len()
}
pub(crate) fn push(&mut self, payload: P, waker: &Waker) -> u64 {
let id = self.next;
self.next += 1;
self.queue.push_back(Entry {
id,
payload,
waker: waker.clone(),
});
id
}
pub(crate) fn front(&self) -> Option<&P> {
self.queue.front().map(|e| &e.payload)
}
pub(crate) fn pop_front(&mut self) -> Option<(u64, P, Waker)> {
self.queue.pop_front().map(|e| (e.id, e.payload, e.waker))
}
pub(crate) fn grant(&mut self, id: u64, v: T) {
self.granted.insert(id, v);
}
pub(crate) fn grant_front(&mut self, v: T) -> Result<(P, Waker), T> {
match self.pop_front() {
Some((id, p, w)) => {
self.grant(id, v);
Ok((p, w))
}
None => Err(v),
}
}
pub(crate) fn take_grant(&mut self, id: u64) -> Option<T> {
self.granted.remove(&id)
}
pub(crate) fn remove(&mut self, id: u64) -> Option<P> {
let pos = self.queue.iter().position(|e| e.id == id)?;
self.queue.remove(pos).map(|e| e.payload)
}
pub(crate) fn refresh(&mut self, id: u64, waker: &Waker) -> bool {
match self.queue.iter_mut().find(|e| e.id == id) {
Some(e) => {
if !e.waker.will_wake(waker) {
e.waker = waker.clone();
}
true
}
None => false,
}
}
pub(crate) fn drain(&mut self) -> Vec<(u64, P, Waker)> {
self
.queue
.drain(..)
.map(|e| (e.id, e.payload, e.waker))
.collect()
}
}
impl<P> WaitList<P, ()> {
pub(crate) fn release_all(&mut self) -> Vec<Waker> {
let all = self.drain();
all
.into_iter()
.map(|(id, _, w)| {
self.grant(id, ());
w
})
.collect()
}
}
#[derive(Default)]
pub(crate) struct Signal {
state: Mutex<SignalState>,
}
#[derive(Default)]
struct SignalState {
fired: bool,
waiters: WaitList<(), ()>,
}
impl Signal {
pub(crate) fn fire(&self) {
let ws = {
let mut st = lock(&self.state);
st.fired = true;
st.waiters.release_all()
};
wake_all(ws);
}
pub(crate) fn wait(self: &Arc<Self>) -> SignalWait {
SignalWait {
signal: Arc::clone(self),
id: None,
}
}
}
pub(crate) struct SignalWait {
signal: Arc<Signal>,
id: Option<u64>,
}
impl Future for SignalWait {
type Output = ();
fn poll(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<()> {
let this = &mut *self;
let mut st = lock(&this.signal.state);
if let Some(id) = this.id {
if st.waiters.take_grant(id).is_some() {
this.id = None;
return std::task::Poll::Ready(());
}
st.waiters.refresh(id, cx.waker());
return std::task::Poll::Pending;
}
if st.fired {
return std::task::Poll::Ready(());
}
this.id = Some(st.waiters.push((), cx.waker()));
std::task::Poll::Pending
}
}
impl Drop for SignalWait {
fn drop(&mut self) {
if let Some(id) = self.id.take() {
let mut st = lock(&self.signal.state);
if st.waiters.take_grant(id).is_none() {
st.waiters.remove(id);
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Wake, Waker};
use super::*;
struct Count(AtomicUsize);
impl Wake for Count {
fn wake(self: Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
#[test]
fn wait_list_is_fifo_and_grants_by_id() {
let count = Arc::new(Count(AtomicUsize::new(0)));
let w = &Waker::from(Arc::clone(&count));
let mut l: WaitList<u8, &str> = WaitList::default();
let a = l.push(1, w);
let b = l.push(2, w);
assert_eq!(l.len(), 2);
assert_eq!(l.front(), Some(&1));
let Ok((payload, waker)) = l.grant_front("x") else {
panic!("a waiter is queued")
};
assert_eq!(payload, 1);
wake_all(vec![waker]);
assert_eq!(count.0.load(Ordering::SeqCst), 1);
assert_eq!(l.take_grant(a), Some("x"));
assert_eq!(l.take_grant(a), None);
assert!(l.refresh(b, w));
assert_eq!(l.remove(b), Some(2));
assert!(!l.refresh(b, w));
assert!(l.is_empty());
assert_eq!(l.grant_front("y").err(), Some("y"));
}
}