terrified to start testing
This commit is contained in:
60
orchid-extension/src/cmd_atom.rs
Normal file
60
orchid-extension/src/cmd_atom.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use dyn_clone::DynClone;
|
||||
use futures::future::LocalBoxFuture;
|
||||
use never::Never;
|
||||
use orchid_base::{Receipt, ReqHandle, ReqHandleExt};
|
||||
use trait_set::trait_set;
|
||||
|
||||
use crate::gen_expr::{GExpr, new_atom};
|
||||
use crate::std_reqs::RunCommand;
|
||||
use crate::{Atomic, MethodSetBuilder, OwnedAtom, OwnedVariant, Supports, ToExpr};
|
||||
|
||||
trait_set! {
|
||||
pub trait ClonableAsyncFnOnceDyn = FnOnce() -> LocalBoxFuture<'static, Option<GExpr>> + DynClone;
|
||||
}
|
||||
|
||||
pub struct CmdAtom(Box<dyn ClonableAsyncFnOnceDyn>);
|
||||
impl Clone for CmdAtom {
|
||||
fn clone(&self) -> Self { Self(dyn_clone::clone_box(&*self.0)) }
|
||||
}
|
||||
impl Atomic for CmdAtom {
|
||||
type Data = ();
|
||||
type Variant = OwnedVariant;
|
||||
fn reg_methods() -> MethodSetBuilder<Self> { MethodSetBuilder::new().handle::<RunCommand>() }
|
||||
}
|
||||
impl Supports<RunCommand> for CmdAtom {
|
||||
async fn handle<'a>(
|
||||
&self,
|
||||
hand: Box<dyn ReqHandle<'a> + '_>,
|
||||
req: RunCommand,
|
||||
) -> std::io::Result<Receipt<'a>> {
|
||||
Self(dyn_clone::clone_box(&*self.0)).handle_final(hand, req).await
|
||||
}
|
||||
async fn handle_final<'a>(
|
||||
self,
|
||||
hand: Box<dyn ReqHandle<'a> + '_>,
|
||||
req: RunCommand,
|
||||
) -> std::io::Result<Receipt<'a>> {
|
||||
let reply = (self.0)().await;
|
||||
match reply {
|
||||
None => hand.reply(&req, &None).await,
|
||||
Some(next) => hand.reply(&req, &Some(next.serialize().await)).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl OwnedAtom for CmdAtom {
|
||||
type Refs = Never;
|
||||
async fn val(&self) -> Cow<'_, Self::Data> { Cow::Owned(()) }
|
||||
}
|
||||
|
||||
pub fn cmd<R: ToExpr>(f: impl AsyncFnOnce() -> Option<R> + Clone + 'static) -> GExpr {
|
||||
new_atom(CmdAtom(Box::new(|| {
|
||||
Box::pin(async {
|
||||
match f().await {
|
||||
None => None,
|
||||
Some(r) => Some(r.to_gen().await),
|
||||
}
|
||||
})
|
||||
})))
|
||||
}
|
||||
Reference in New Issue
Block a user