use crate::reactor::{Held, mappings};
use dope_sys::{
engine::shutdown,
io::{self, Cleanup},
memory::{self, Failure as _},
ring::map,
};
use o3::mem::Rejected;
#[repr(transparent)]
pub struct Closing<P: io::Close, R>(pub(crate) Cleanup<(R, P), P::State>);
pub struct Pending<P: io::Close, R>(Cleanup<(R, P), <P::State as io::Retry>::Owner>);
impl<P: io::Close, R> Closing<P, R> {
pub(crate) fn close(result: Result<(), R>, storage: P) -> Result<(), Self> {
match result {
Ok(()) => storage
.try_close()
.map_err(|state| Self(Cleanup::Storage(state))),
Err(owner) => Err(Self(Cleanup::Owner((owner, storage)))),
}
}
}
impl<P: io::Close, R: io::Retry> io::Retry for Closing<P, R> {
type Failure = Cleanup<R::Failure, <P::State as io::Retry>::Failure>;
type Owner = Pending<P, R::Owner>;
fn recover(self) -> Rejected<Self::Owner, Self::Failure> {
match self.0 {
Cleanup::Owner((owner, storage)) => {
let (owner, error) = owner.recover().into_parts();
Rejected::new(
Pending(Cleanup::Owner((owner, storage))),
Cleanup::Owner(error),
)
}
Cleanup::Storage(state) => {
let (state, error) = state.recover().into_parts();
Rejected::new(Pending(Cleanup::Storage(state)), Cleanup::Storage(error))
}
}
}
}
impl<P: io::Close, R: io::Close> io::Close for Pending<P, R> {
type State = Closing<P, R::State>;
fn try_close(self) -> Result<(), Self::State> {
match self.0 {
Cleanup::Owner((owner, storage)) => Closing::close(owner.try_close(), storage),
Cleanup::Storage(state) => state
.try_close()
.map_err(|state| Closing(Cleanup::Storage(state))),
}
}
}
impl<P, R> Closing<P, R>
where
P: io::Close<State: memory::Failure>,
R: map::Unmap,
{
fn cause(&self) -> Cleanup<map::Storage<R::Error>, memory::Error> {
match &self.0 {
Cleanup::Owner((owner, _)) => Cleanup::Owner(owner.failure()),
Cleanup::Storage(state) => Cleanup::Storage(state.failure()),
}
}
}
impl<P, R> map::Unmap for Closing<P, R>
where
P: io::Close<State: memory::Failure + io::Retry<Failure: Into<memory::Error>>>,
R: map::Unmap,
{
type Error = R::Error;
fn failure(&self) -> map::Storage<Self::Error> {
self.cause().into()
}
}
impl<R: map::Unmap, K> shutdown::Cleanup for Closing<mappings::Region, Held<R, K>> {
type Error = R::Error;
fn failure(&self) -> shutdown::Failure<Self::Error> {
self.cause().into()
}
}