use super::core::from_fn_with_flow;
use crate::{
di::{Asyncify, Injectable},
send::{MaybeSend, MaybeSync},
Handler, HandlerDescription, HandlerSignature,
};
use std::{collections::BTreeSet, sync::Arc};
#[must_use]
#[track_caller]
pub fn inspect<'a, F, Output, Args, Descr>(f: F) -> Handler<'a, Output, Descr>
where
Asyncify<F>: Injectable<(), Args> + MaybeSend + MaybeSync + 'a,
Output: 'a,
Descr: HandlerDescription,
{
inspect_with_description(Descr::inspect(), f)
}
#[must_use]
#[track_caller]
pub fn inspect_async<'a, F, Output, Args, Descr>(f: F) -> Handler<'a, Output, Descr>
where
F: Injectable<(), Args> + MaybeSend + MaybeSync + 'a,
Output: 'a,
Descr: HandlerDescription,
{
inspect_async_with_description(Descr::inspect_async(), f)
}
#[must_use]
#[track_caller]
pub fn inspect_with_description<'a, F, Output, Args, Descr>(
description: Descr,
f: F,
) -> Handler<'a, Output, Descr>
where
Asyncify<F>: Injectable<(), Args> + MaybeSend + MaybeSync + 'a,
Output: 'a,
{
inspect_async_with_description(description, Asyncify(f))
}
#[must_use]
#[track_caller]
pub fn inspect_async_with_description<'a, F, Output, Args, Descr>(
description: Descr,
f: F,
) -> Handler<'a, Output, Descr>
where
F: Injectable<(), Args> + MaybeSend + MaybeSync + 'a,
Output: 'a,
{
let f = Arc::new(f);
from_fn_with_flow(
description,
move |x, cont| {
let f = Arc::clone(&f);
async move {
{
let f = f.inject(&x);
f().await;
}
cont(x).await
}
},
HandlerSignature::Other {
obligations: F::obligations(),
guaranteed_outcomes: BTreeSet::default(),
conditional_outcomes: BTreeSet::default(),
continues: true,
},
false,
)
}
#[cfg(test)]
mod tests {
use std::{
ops::ControlFlow,
sync::atomic::{AtomicBool, Ordering},
};
use super::*;
use crate::{deps, help_inference};
crate::cross_test! {
async fn test_inspect() {
let value = 123;
let inspect_passed = Arc::new(AtomicBool::new(false));
let inspect_passed_cloned = Arc::clone(&inspect_passed);
let result: ControlFlow<(), _> = help_inference(inspect(move |x: i32| {
assert_eq!(x, value);
inspect_passed_cloned.swap(true, Ordering::Relaxed);
}))
.dispatch(deps![value])
.await;
assert!(matches!(result, ControlFlow::Continue(_)));
assert!(inspect_passed.load(Ordering::Relaxed));
}
}
}