tengri/input/src/command.rs
2025-04-27 01:57:10 +03:00

54 lines
1.7 KiB
Rust

use crate::*;
#[macro_export] macro_rules! defcom {
([$self:ident, $app:ident:$App:ty] $(($Command:ident $((
$Variant:ident [$($($param:ident: $Param:ty),+)?] $expr:expr
))*))*) => {
$(#[derive(Clone, Debug)] pub enum $Command {
$($Variant $(($($Param),+))?),*
})*
$(command!(|$self: $Command, $app: $App|match $self {
$($Command::$Variant $(($($param),+))? => $expr),*
});)*
};
(|$self:ident, $app:ident:$App:ty| $($Command:ident { $(
$Variant:ident $(($($param:ident: $Param:ty),+))? => $expr:expr
)* $(,)? })*) => {
$(#[derive(Clone, Debug)] pub enum $Command {
$($Variant $(($($Param),+))?),*
})*
$(command!(|$self: $Command, $app: $App|match $self {
$($Command::$Variant $(($($param),+))? => $expr),*
});)*
};
}
#[macro_export] macro_rules! command {
($(<$($l:lifetime),+>)?|$self:ident:$Command:ty,$state:ident:$State:ty|$handler:expr) => {
impl$(<$($l),+>)? Command<$State> for $Command {
fn execute ($self, $state: &mut $State) -> Perhaps<Self> {
Ok($handler)
}
}
};
}
pub trait Command<S>: Send + Sync + Sized {
fn execute (self, state: &mut S) -> Perhaps<Self>;
fn delegate <T> (self, state: &mut S, wrap: impl Fn(Self)->T) -> Perhaps<T>
where Self: Sized
{
Ok(self.execute(state)?.map(wrap))
}
}
impl<S, T: Command<S>> Command<S> for Option<T> {
fn execute (self, _: &mut S) -> Perhaps<Self> {
Ok(None)
}
fn delegate <U> (self, _: &mut S, _: impl Fn(Self)->U) -> Perhaps<U>
where Self: Sized
{
Ok(None)
}
}