use std::iter::repeat_with;
use std::sync::{RwLock, RwLockReadGuard};
pub struct FunnyBot<'a, A, R>
where
A: Send + Sync + Clone,
R: Send + Sync + 'a,
{
arguments: RwLock<Vec<A>>,
returns: RwLock<Box<dyn Iterator<Item = R> + Send + Sync + 'a>>,
}
impl<'a, A, R> FunnyBot<'a, A, R>
where
A: Send + Sync + Clone,
R: Send + Sync + 'a + Clone,
{
pub fn repeat(elt: R) -> Self {
FunnyBot::new(Box::new(std::iter::repeat(elt)))
}
}
impl<'a, A, R> FunnyBot<'a, A, R>
where
A: Send + Sync + Clone,
R: Send + Sync + 'a,
{
#[must_use]
pub fn new(returns: Box<dyn Iterator<Item = R> + Send + Sync + 'a>) -> Self {
FunnyBot {
arguments: RwLock::new(Vec::new()),
returns: RwLock::new(returns),
}
}
#[must_use]
pub fn from_single(returns: R) -> Self {
Self::from_list(vec![returns])
}
#[must_use]
pub fn from_list(returns: Vec<R>) -> Self {
Self::new(Box::new(returns.into_iter()))
}
pub fn repeat_with<F: 'a + Sync + Send + FnMut() -> R>(repeater: F) -> Self {
Self::new(Box::new(repeat_with(repeater)))
}
pub fn call(&self, a: A) -> R {
self.arguments.write().unwrap().push(a);
self.returns
.write()
.unwrap()
.next()
.expect("missing pre-programmed value for call")
}
pub fn into_args(self) -> Vec<A> {
self.arguments.into_inner().unwrap()
}
pub fn args(&self) -> RwLockReadGuard<Vec<A>> {
self.arguments.read().unwrap()
}
}