use super::TQueueLike;
use crate::test_queue_mod;
use crate::{retry, Stm, TVar};
use std::any::Any;
type TVarList<T> = TVar<TList<T>>;
#[derive(Clone)]
enum TList<T> {
TNil,
TCons(T, TVarList<T>),
}
#[derive(Clone)]
pub struct TChan<T> {
read: TVar<TVarList<T>>,
write: TVar<TVarList<T>>,
}
impl<T> TChan<T>
where
T: Any + Sync + Send + Clone,
{
pub fn new() -> TChan<T> {
let hole = TVar::new(TList::TNil);
TChan {
read: TVar::new(hole.clone()),
write: TVar::new(hole),
}
}
fn is_empty_list(tvl: &TVar<TVarList<T>>) -> Stm<bool> {
let list_var = tvl.read()?;
let list = list_var.read()?;
match list.as_ref() {
TList::TNil => Ok(true),
_ => Ok(false),
}
}
}
impl<T: Any + Send + Sync + Clone> Default for TChan<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> TQueueLike<T> for TChan<T>
where
T: Any + Sync + Send + Clone,
{
fn read(&self) -> Stm<T> {
let var_list = self.read.read()?;
let list = var_list.read_clone()?;
match list {
TList::TNil => retry(),
TList::TCons(value, tail) => {
self.read.write(tail)?;
Ok(value)
}
}
}
fn write(&self, value: T) -> Stm<()> {
let new_list_end = TVar::new(TList::TNil);
let var_list = self.write.read()?;
var_list.write(TList::TCons(value, new_list_end.clone()))?;
self.write.write(new_list_end)?;
Ok(())
}
fn is_empty(&self) -> Stm<bool> {
if TChan::<T>::is_empty_list(&self.read)? {
TChan::<T>::is_empty_list(&self.write)
} else {
Ok(false)
}
}
}
test_queue_mod!(|| { crate::queues::tchan::TChan::<i32>::new() });