use dope_sys::{
engine::{self, admit},
io::reactor::{
self,
event::{Entry, kind},
},
};
use o3::mem::slot;
use std::{
mem::{self, MaybeUninit},
ptr,
};
use crate::{
Backend,
driver::{self, retained::flight, route::kind::Flight},
io::fd::handles::Descriptor,
};
#[must_use = "a pending establishment owns its descriptor and completion authority"]
#[repr(C)]
pub struct Owner<'d, K: Flight, P = <Backend as admit::Native>::Permit> {
fd: Descriptor<'d>,
flight: flight::Flight<'d, K>,
permit: P,
}
use crate::io::socket::Completion;
impl<'d, K: Flight, P> Owner<'d, K, P> {
pub const fn fd(&self) -> &Descriptor<'d> {
&self.fd
}
pub fn complete<'slot, V: Copy>(
owner: slot::Occupied<'slot, Self>,
done: &Entry<flight::Complete<'d>, K, V>,
) -> Completion<'slot, 'd, Self, V>
where
P: Copy,
{
if !owner.flight.matches(done.token()) {
return Err(owner);
}
let result = done.outcome();
let value = owner.into_uninit().get_mut().as_mut_ptr();
unsafe {
ptr::drop_in_place(&raw mut (*value).flight);
Ok((
slot::raw::Vacant::new(&mut *value.cast::<MaybeUninit<Descriptor<'d>>>())
.assume_init(),
result,
))
}
}
}
impl<'d, P> Owner<'d, kind::Tuning, P> {
pub(in crate::io::socket) fn new(
fd: Descriptor<'d>,
flight: flight::Flight<'d, kind::Tuning>,
permit: P,
) -> Self {
Self { fd, flight, permit }
}
}
impl<'d> Owner<'d, kind::Tuning> {
pub fn try_cancel(&mut self, driver: &mut driver::Local<'d>) -> Result<(), reactor::Full> {
if !self.flight.is_pending() {
return Ok(());
}
engine::Cancel::cancel(&mut *driver.backend, &self.permit, self.fd.index())
}
}
impl<'d> Owner<'d, kind::Connect, ()> {
pub fn try_cancel(
&mut self,
driver: &mut driver::Local<'d>,
) -> Result<(), admit::Error<crate::CancelRejection>> {
driver.try_stop_at(&mut self.flight, &self.fd)?;
Ok(())
}
pub unsafe fn install<'slot>(
slot: &'slot mut MaybeUninit<Self>,
flight: flight::Flight<'d, kind::Connect>,
) -> slot::Occupied<'slot, Self> {
let value = slot.as_mut_ptr();
unsafe {
(&raw mut (*value).flight).write(flight);
(&raw mut (*value).permit).write(());
slot::raw::Vacant::new(slot).assume_init()
}
}
}
const _: () = {
assert!(
mem::size_of::<Owner<'_, kind::Tuning>>()
== mem::size_of::<(Descriptor<'_>, flight::Flight<'_, kind::Tuning>)>()
);
assert!(
mem::align_of::<Owner<'_, kind::Tuning>>()
== mem::align_of::<(Descriptor<'_>, flight::Flight<'_, kind::Tuning>)>()
);
assert!(mem::offset_of!(Owner<'_, kind::Tuning>, fd) == 0);
assert!(
mem::size_of::<Owner<'_, kind::Connect, ()>>()
== mem::size_of::<(Descriptor<'_>, flight::Flight<'_, kind::Connect>)>()
);
assert!(mem::offset_of!(Owner<'_, kind::Connect, ()>, fd) == 0);
};