use crate::{Ctx, Result};
use futures::future::BoxFuture;
use std::{future::Future, sync::Arc};
#[derive(Clone)]
pub struct Handler {
inner: Arc<dyn Fn(Ctx) -> BoxFuture<'static, Result<()>> + Send + Sync + 'static>,
}
impl Handler {
pub fn new<F, Fut>(f: F) -> Self
where
F: Fn(Ctx) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
Self {
inner: Arc::new(move |ctx| {
let fut = f(ctx);
Box::pin(fut)
}),
}
}
pub async fn call(&self, ctx: Ctx) -> Result<()> {
(self.inner)(ctx).await
}
}
#[derive(Clone)]
pub struct Command {
pub name: String,
pub handler: Handler,
}
impl Command {
pub fn new(name: impl Into<String>, handler: Handler) -> Self {
Self {
name: name.into(),
handler,
}
}
}
impl std::fmt::Debug for Command {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Command")
.field("name", &self.name)
.finish_non_exhaustive()
}
}