use std::marker;
use dope_sys::{
io::{Close, Retry},
memory,
memory::{Error, Failure, buffer::provided},
};
use o3::mem::Rejected;
use crate::reactor::{buffers, mappings};
#[derive(Debug)]
pub struct Cleanup {
current: mappings::Unmap,
context: Option<mappings::Region>,
}
#[derive(Debug)]
pub struct Create {
primary: Error,
cleanup: Option<Cleanup>,
}
#[derive(Debug)]
pub struct Open<L> {
state: mappings::Open,
layout: marker::PhantomData<fn(L) -> L>,
}
#[derive(Debug)]
pub struct Pending {
pub(super) current: mappings::Region,
pub(super) context: Option<mappings::Region>,
}
impl Failure for Cleanup {
fn failure(&self) -> Error {
self.current.failure()
}
}
impl Retry for Cleanup {
type Failure = Error;
type Owner = Pending;
fn recover(self) -> Rejected<Self::Owner, Error> {
let (current, cause) = self.current.recover().into_parts();
Rejected::new(
Pending {
current,
context: self.context,
},
cause,
)
}
}
impl Close for Pending {
type State = Cleanup;
fn try_close(self) -> Result<(), Self::State> {
let Self { current, context } = self;
match current.try_close() {
Ok(()) => match context {
Some(context) => context.try_close().map_err(Cleanup::region),
None => Ok(()),
},
Err(current) => Err(Cleanup { current, context }),
}
}
}
impl Cleanup {
pub(in crate::reactor) fn region(current: mappings::Unmap) -> Self {
Self {
current,
context: None,
}
}
}
impl<L> From<mappings::Open> for Open<L> {
fn from(state: mappings::Open) -> Self {
Self {
state,
layout: marker::PhantomData,
}
}
}
impl<L: memory::raw::Receive> provided::Failure for Open<L> {
type Cleanup = Cleanup;
fn into_parts(self) -> (Error, Option<Self::Cleanup>) {
provided::Failure::into_parts(Create::from(self.state))
}
}
impl<L: memory::raw::Receive> provided::Open for Open<L> {
type Context = buffers::raw::Context<L>;
fn close(self, context: buffers::raw::Context<L>) -> Create {
let context = context.into_region();
match self.state {
mappings::Open::Failure(primary) => Create {
primary,
cleanup: context.try_close().err().map(Cleanup::region),
},
mappings::Open::Cleanup { primary, current } => Create {
primary,
cleanup: Some(Cleanup {
current,
context: Some(context),
}),
},
}
}
}
impl From<mappings::Open> for Create {
fn from(state: mappings::Open) -> Self {
match state {
mappings::Open::Failure(primary) => Self {
primary,
cleanup: None,
},
mappings::Open::Cleanup { primary, current } => Self {
primary,
cleanup: Some(Cleanup::region(current)),
},
}
}
}
impl provided::Failure for Create {
type Cleanup = Cleanup;
fn into_parts(self) -> (Error, Option<Cleanup>) {
(self.primary, self.cleanup)
}
}