use std::sync::Arc;
use super::StopTarget;
use crate::error::Error;
type Action = Arc<dyn Fn(&StopTarget<'_>) -> Result<(), Error> + Send + Sync>;
#[cfg(feature = "tokio")]
type AsyncAction = Arc<dyn for<'t, 'c> Fn(&'t StopTarget<'c>) -> crate::tokio::StopFuture<'t> + Send + Sync>;
#[derive(Clone, Default)]
pub(crate) enum StopAction {
#[default]
Default,
Sync(Action),
#[cfg(feature = "tokio")]
Async(AsyncAction),
}
impl StopAction {
pub(crate) fn sync(action: impl Fn(&StopTarget<'_>) -> Result<(), Error> + Send + Sync + 'static) -> StopAction {
StopAction::Sync(Arc::new(action))
}
#[cfg(feature = "tokio")]
pub(crate) fn asynchronous(
action: impl for<'t, 'c> Fn(&'t StopTarget<'c>) -> crate::tokio::StopFuture<'t> + Send + Sync + 'static,
) -> StopAction {
StopAction::Async(Arc::new(action))
}
pub(crate) fn run(&self, target: &StopTarget<'_>) -> Result<(), Error> {
match self {
StopAction::Default => super::default(target),
StopAction::Sync(action) => action(target),
#[cfg(feature = "tokio")]
StopAction::Async(_) => {
unreachable!("a sync child never holds an async action: each Command accepts only its own kind")
}
}
}
#[cfg(feature = "tokio")]
pub(crate) async fn run_async(&self, target: &StopTarget<'_>) -> Result<(), Error> {
match self {
StopAction::Default => crate::tokio::stop::default(target).await,
StopAction::Async(action) => action(target).await,
StopAction::Sync(_) => {
unreachable!("an async child never holds a sync action: each Command accepts only its own kind")
}
}
}
}
impl std::fmt::Debug for StopAction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
StopAction::Default => f.write_str("StopAction::Default"),
StopAction::Sync(_) => f.write_str("StopAction::Sync(..)"),
#[cfg(feature = "tokio")]
StopAction::Async(_) => f.write_str("StopAction::Async(..)"),
}
}
}