pub trait Task<M = ()>: Send + Sync {
fn is_locked(&self, _memory: &M) -> bool {
false
}
fn on_enter(&mut self, _memory: &mut M) {}
fn on_exit(&mut self, _memory: &mut M) {}
fn on_update(&mut self, _memory: &mut M) {}
fn on_process(&mut self, _memory: &mut M) -> bool {
false
}
}
#[derive(Debug, Default, Copy, Clone)]
pub struct NoTask;
impl<M> Task<M> for NoTask {}
#[allow(clippy::type_complexity)]
pub struct ClosureTask<M = ()> {
locked: Option<Box<dyn Fn(&M) -> bool + Send + Sync>>,
enter: Option<Box<dyn FnMut(&mut M) + Send + Sync>>,
exit: Option<Box<dyn FnMut(&mut M) + Send + Sync>>,
update: Option<Box<dyn FnMut(&mut M) + Send + Sync>>,
process: Option<Box<dyn FnMut(&mut M) -> bool + Send + Sync>>,
}
impl<M> Default for ClosureTask<M> {
fn default() -> Self {
Self {
locked: None,
enter: None,
exit: None,
update: None,
process: None,
}
}
}
impl<M> ClosureTask<M> {
pub fn locked<F>(mut self, f: F) -> Self
where
F: Fn(&M) -> bool + 'static + Send + Sync,
{
self.locked = Some(Box::new(f));
self
}
pub fn enter<F>(mut self, f: F) -> Self
where
F: FnMut(&mut M) + 'static + Send + Sync,
{
self.enter = Some(Box::new(f));
self
}
pub fn exit<F>(mut self, f: F) -> Self
where
F: FnMut(&mut M) + 'static + Send + Sync,
{
self.exit = Some(Box::new(f));
self
}
pub fn update<F>(mut self, f: F) -> Self
where
F: FnMut(&mut M) + 'static + Send + Sync,
{
self.update = Some(Box::new(f));
self
}
pub fn process<F>(mut self, f: F) -> Self
where
F: FnMut(&mut M) -> bool + 'static + Send + Sync,
{
self.process = Some(Box::new(f));
self
}
}
impl<M> Task<M> for ClosureTask<M> {
fn is_locked(&self, memory: &M) -> bool {
self.locked.as_ref().map(|f| f(memory)).unwrap_or_default()
}
fn on_enter(&mut self, memory: &mut M) {
if let Some(f) = &mut self.enter {
f(memory)
}
}
fn on_exit(&mut self, memory: &mut M) {
if let Some(f) = &mut self.exit {
f(memory)
}
}
fn on_update(&mut self, memory: &mut M) {
if let Some(f) = &mut self.update {
f(memory)
}
}
fn on_process(&mut self, memory: &mut M) -> bool {
self.process.as_mut().map(|f| f(memory)).unwrap_or_default()
}
}
impl<M> std::fmt::Debug for ClosureTask<M> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ClosureTask").finish()
}
}