use super::anybox::{AnyExit, unbox};
use super::cause::ExitKind;
use super::effect::Effect;
use super::runloop::{Instr, MaskOp};
use crate::failure::Cause;
use crate::failure::Never;
fn then_finalize(fin: Instr, exit: AnyExit) -> Instr {
Instr::Fold(
Box::new(fin),
Box::new(move |fin_exit| match fin_exit {
Ok(_) => Instr::Pure(exit),
Err(fc) => Instr::Pure(Err(match exit {
Ok(_) => fc,
Err(c) => Cause::then(c, fc),
})),
}),
)
}
impl<A, E, R> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
pub fn ensuring(self, fin: Effect<(), Never, R>) -> Self {
Self::from_instr(Instr::WithFiber(Box::new(move |_, fiber| {
let m = fiber.mask();
Instr::Mask(
Box::new(Instr::Fold(
Box::new(Instr::Mask(Box::new(self.into_instr()), MaskOp::Set(m))),
Box::new(move |exit| then_finalize(fin.into_instr(), exit)),
)),
MaskOp::Inc,
)
})))
}
pub fn uninterruptible(self) -> Self {
Self::from_instr(Instr::Mask(Box::new(self.into_instr()), MaskOp::Inc))
}
pub fn interruptible(self) -> Self {
Self::from_instr(Instr::Mask(Box::new(self.into_instr()), MaskOp::Set(0)))
}
}
pub fn uninterruptible_mask<A, E, R>(
f: impl FnOnce(Restore) -> Effect<A, E, R> + Send + 'static,
) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
Effect::from_instr(Instr::WithFiber(Box::new(move |_, fiber| {
let m = fiber.mask();
Instr::Mask(Box::new(f(Restore(m)).into_instr()), MaskOp::Inc)
})))
}
#[derive(Clone, Copy, Debug)]
pub struct Restore(u32);
impl Restore {
pub fn apply<A, E, R>(self, eff: Effect<A, E, R>) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
Effect::from_instr(Instr::Mask(Box::new(eff.into_instr()), MaskOp::Set(self.0)))
}
}
pub fn acquire_use_release<T, B, E, R>(
acquire: Effect<T, E, R>,
use_: impl FnOnce(T) -> Effect<B, E, R> + Send + 'static,
release: impl FnOnce(T, ExitKind) -> Effect<(), Never, R> + Send + 'static,
) -> Effect<B, E, R>
where
T: Clone + Send + 'static,
B: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
Effect::from_instr(Instr::WithFiber(Box::new(move |_, fiber| {
let m = fiber.mask();
Instr::Mask(
Box::new(Instr::FlatMap(
Box::new(acquire.into_instr()),
Box::new(move |t| {
let t: T = unbox(t);
let t2 = t.clone();
Instr::Fold(
Box::new(Instr::Mask(
Box::new(Instr::Sync(Box::new(move |_| use_(t).into_instr()))),
MaskOp::Set(m),
)),
Box::new(move |exit| {
let kind = ExitKind::of_result(&exit);
let fin = Instr::Sync(Box::new(move |_| release(t2, kind).into_instr()));
then_finalize(fin, exit)
}),
)
}),
)),
MaskOp::Inc,
)
})))
}