#![allow(dead_code)]
use std::{
fmt::{self, Debug},
hash::Hash,
io,
mem::ManuallyDrop,
ops::{Deref, DerefMut},
pin::Pin,
task::Waker,
};
use compio_buf::BufResult;
use thin_cell::{Ref, ThinCell};
use crate::{Extra, OpCode, PushEntry};
#[repr(C)]
pub(crate) struct RawOp<T: ?Sized> {
extra: Extra,
cancelled: bool,
result: PushEntry<Option<Waker>, io::Result<usize>>,
pub(crate) op: T,
}
impl<T: ?Sized> RawOp<T> {
pub fn extra(&self) -> &Extra {
&self.extra
}
pub fn extra_mut(&mut self) -> &mut Extra {
&mut self.extra
}
fn pinned_op(&mut self) -> Pin<&mut T> {
unsafe { Pin::new_unchecked(&mut self.op) }
}
}
#[cfg(windows)]
impl<T: OpCode + ?Sized> RawOp<T> {
pub fn operate_blocking(&mut self) -> io::Result<usize> {
use std::task::Poll;
let optr = self.extra_mut().optr();
let op = self.pinned_op();
let res = unsafe { op.operate(optr.cast()) };
match res {
Poll::Pending => unreachable!("this operation is not overlapped"),
Poll::Ready(res) => res,
}
}
}
impl<T: ?Sized> Debug for RawOp<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RawOp")
.field("extra", &self.extra)
.field("cancelled", &self.cancelled)
.field("result", &self.result)
.field("op", &"<...>")
.finish()
}
}
#[repr(transparent)]
pub struct Key<T> {
erased: ErasedKey,
_p: std::marker::PhantomData<T>,
}
impl<T> Unpin for Key<T> {}
impl<T> Clone for Key<T> {
fn clone(&self) -> Self {
Self {
erased: self.erased.clone(),
_p: std::marker::PhantomData,
}
}
}
impl<T> Debug for Key<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Key({})", self.erased.inner.as_ptr() as usize)
}
}
impl<T> Key<T> {
pub(crate) fn into_raw(self) -> usize {
self.erased.into_raw()
}
pub(crate) fn erase(self) -> ErasedKey {
self.erased
}
pub(crate) fn take_result(self) -> BufResult<usize, T> {
unsafe { self.erased.take_result::<T>() }
}
}
impl<T: OpCode + 'static> Key<T> {
pub(crate) fn new(op: T, extra: impl Into<Extra>) -> Self {
let erased = ErasedKey::new(op, extra.into());
Self {
erased,
_p: std::marker::PhantomData,
}
}
pub(crate) fn set_extra(&self, extra: impl Into<Extra>) {
self.borrow().extra = extra.into();
}
}
impl<T> Deref for Key<T> {
type Target = ErasedKey;
fn deref(&self) -> &Self::Target {
&self.erased
}
}
impl<T> DerefMut for Key<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.erased
}
}
#[derive(Clone)]
#[repr(transparent)]
pub struct ErasedKey {
inner: ThinCell<RawOp<dyn OpCode>>,
}
impl PartialEq for ErasedKey {
fn eq(&self, other: &Self) -> bool {
self.inner.ptr_eq(&other.inner)
}
}
impl Eq for ErasedKey {}
impl Hash for ErasedKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(self.inner.as_ptr() as usize).hash(state)
}
}
impl Unpin for ErasedKey {}
impl ErasedKey {
pub(crate) fn new<T: OpCode + 'static>(op: T, extra: Extra) -> Self {
let raw_op = RawOp {
extra,
cancelled: false,
result: PushEntry::Pending(None),
op,
};
let inner = unsafe { ThinCell::new_unsize(raw_op, |p| p as _) };
Self { inner }
}
pub(crate) unsafe fn from_raw(user_data: usize) -> Self {
let inner = unsafe { ThinCell::from_raw(user_data as *mut ()) };
Self { inner }
}
#[cfg(windows)]
pub(crate) unsafe fn from_optr(optr: *mut crate::sys::Overlapped) -> Self {
let ptr = unsafe { optr.cast::<usize>().offset(-2).cast() };
let inner = unsafe { ThinCell::from_raw(ptr) };
Self { inner }
}
#[cfg(windows)]
pub(crate) fn into_optr(self) -> *mut crate::sys::Overlapped {
unsafe { self.inner.leak().cast::<usize>().add(2).cast() }
}
pub(crate) fn as_raw(&self) -> usize {
self.inner.as_ptr() as _
}
pub(crate) fn into_raw(self) -> usize {
self.inner.leak() as _
}
#[inline]
pub(crate) fn borrow(&self) -> Ref<'_, RawOp<dyn OpCode>> {
self.inner.borrow()
}
pub(crate) fn set_cancelled(&self) {
self.borrow().cancelled = true;
}
pub(crate) fn has_result(&self) -> bool {
self.borrow().result.is_ready()
}
pub(crate) fn set_result(&self, res: io::Result<usize>) {
let mut this = self.borrow();
#[cfg(io_uring)]
if let Ok(res) = res
&& this.extra.is_iour()
{
unsafe {
Pin::new_unchecked(&mut this.op).set_result(res);
}
}
if let PushEntry::Pending(Some(w)) =
std::mem::replace(&mut this.result, PushEntry::Ready(res))
{
w.wake();
}
}
pub(crate) fn swap_extra(&self, extra: Extra) -> Extra {
std::mem::replace(&mut self.borrow().extra, extra)
}
pub(crate) fn set_waker(&self, waker: &Waker) {
let PushEntry::Pending(w) = &mut self.borrow().result else {
return;
};
if w.as_ref().is_some_and(|w| w.will_wake(waker)) {
return;
}
*w = Some(waker.clone());
}
unsafe fn take_result<T>(self) -> BufResult<usize, T> {
let this = unsafe { self.inner.downcast_unchecked::<RawOp<T>>() };
let op = this.try_unwrap().map_err(|_| ()).expect("Key not unique");
let res = op.result.take_ready().expect("Result not ready");
BufResult(res, op.op)
}
pub(crate) unsafe fn freeze(self) -> FrozenKey {
FrozenKey {
inner: ManuallyDrop::new(self),
}
}
}
impl Debug for ErasedKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ErasedKey({})", self.inner.as_ptr() as usize)
}
}
#[repr(transparent)]
pub(crate) struct FrozenKey {
inner: ManuallyDrop<ErasedKey>,
}
impl FrozenKey {
pub fn as_mut(&mut self) -> &mut RawOp<dyn OpCode> {
unsafe { self.inner.inner.borrow_unchecked() }
}
pub fn pinned_op(&mut self) -> Pin<&mut dyn OpCode> {
self.as_mut().pinned_op()
}
pub fn into_inner(self) -> ErasedKey {
ManuallyDrop::into_inner(self.inner)
}
}
unsafe impl Send for FrozenKey {}
unsafe impl Sync for FrozenKey {}
pub(crate) struct BorrowedKey(ManuallyDrop<ErasedKey>);
impl BorrowedKey {
pub unsafe fn from_raw(user_data: usize) -> Self {
let key = unsafe { ErasedKey::from_raw(user_data) };
Self(ManuallyDrop::new(key))
}
pub fn upgrade(self) -> ErasedKey {
ManuallyDrop::into_inner(self.0)
}
}
impl Deref for BorrowedKey {
type Target = ErasedKey;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub trait RefExt {
fn pinned_op(&mut self) -> Pin<&mut dyn OpCode>;
}
impl RefExt for Ref<'_, RawOp<dyn OpCode>> {
fn pinned_op(&mut self) -> Pin<&mut dyn OpCode> {
self.deref_mut().pinned_op()
}
}