use super::{Cmd, Handover, Inner};
use std::sync::Arc;
type Wrap<M, N> = Arc<dyn Fn(M) -> N + Send + Sync>;
impl<M: Send + 'static> Cmd<M> {
#[must_use]
pub fn map<N: Send + 'static>(self, wrap: impl Fn(M) -> N + Send + Sync + 'static) -> Cmd<N> {
let wrap: Wrap<M, N> = Arc::new(wrap);
map_with(self, &wrap)
}
}
fn map_with<M: Send + 'static, N: Send + 'static>(cmd: Cmd<M>, wrap: &Wrap<M, N>) -> Cmd<N> {
let inner = match cmd.0 {
Inner::None => Inner::None,
Inner::Quit => Inner::Quit,
Inner::Interrupt => Inner::Interrupt,
Inner::Batch(cmds) => Inner::Batch(map_all(cmds, wrap)),
Inner::Sequence(cmds) => Inner::Sequence(map_all(cmds, wrap)),
Inner::Output(output) => Inner::Output(output),
Inner::Handover(handover) => Inner::Handover(map_handover(handover, wrap)),
work @ (Inner::Task(_) | Inner::Tick(..) | Inner::Every(..)) => map_work(work, wrap),
};
Cmd(inner)
}
fn map_all<M: Send + 'static, N: Send + 'static>(
cmds: Vec<Cmd<M>>,
wrap: &Wrap<M, N>,
) -> Vec<Cmd<N>> {
cmds.into_iter().map(|c| map_with(c, wrap)).collect()
}
fn map_work<M: Send + 'static, N: Send + 'static>(work: Inner<M>, wrap: &Wrap<M, N>) -> Inner<N> {
let wrap = Arc::clone(wrap);
match work {
Inner::Task(work) => Inner::Task(Box::new(move || wrap(work()))),
Inner::Tick(delay, fire) => Inner::Tick(delay, Box::new(move |now| wrap(fire(now)))),
Inner::Every(period, fire) => Inner::Every(period, Box::new(move |now| wrap(fire(now)))),
_ => unreachable!("map_with sends only tasks and timers here"),
}
}
fn map_handover<M: Send + 'static, N: Send + 'static>(
handover: Handover<M>,
wrap: &Wrap<M, N>,
) -> Handover<N> {
match handover {
Handover::Exec(done) => {
let wrap = Arc::clone(wrap);
Handover::Exec(Box::new(move |failed| wrap(done(failed))))
}
Handover::Suspend => Handover::Suspend,
Handover::Release => Handover::Release,
Handover::Restore => Handover::Restore,
Handover::Continue => Handover::Continue,
}
}