use core::{future::Future, marker, mem, pin, ptr, task};
use o3::base::marker::ThreadBound;
use crate::{
executor::task::context::{self, Context},
executor::task::{Fiber, future},
};
pub(super) struct Frame<'call, 'turn, 'd: 'turn, I> {
context: &'call mut Context<'turn, 'd>,
first: bool,
scope: marker::PhantomData<fn(&mut I) -> &mut I>,
}
const _: () = {
assert!(mem::size_of::<Frame<'static, 'static, 'static, ()>>() == 2 * mem::size_of::<usize>());
};
impl<'call, 'turn, 'd: 'turn, I> Frame<'call, 'turn, 'd, I> {
pub(super) fn new(context: &'call mut Context<'turn, 'd>) -> Self {
Self {
context,
first: true,
scope: marker::PhantomData,
}
}
}
impl<'call, 'turn, 'd: 'turn, I> Frame<'call, 'turn, 'd, I> {
pub(super) fn poll<F, const REPEAT: bool>(
&mut self,
fiber: pin::Pin<&mut F>,
) -> task::Poll<F::Output>
where
F: Fiber<'d>,
{
let first = mem::replace(&mut self.first, false);
if REPEAT && !first {
let context::Continue::Permit(_permit) = self.context.try_continue() else {
return task::Poll::Pending;
};
}
F::poll(context::PollCall {
fiber,
context: &mut *self.context,
})
}
}
pub struct Brand<'d, I> {
scope: marker::PhantomData<fn(&'d mut I) -> &'d mut I>,
thread: marker::PhantomData<ThreadBound>,
}
impl<'d, I> Brand<'d, I> {
pub const unsafe fn scope() -> Self {
Self {
scope: marker::PhantomData,
thread: marker::PhantomData,
}
}
pub fn awaitable<'a, F, const REPEAT: bool>(
fiber: F,
_: &'a mut Self,
) -> future::Awaitable<'a, 'd, I, F, REPEAT> {
future::Awaitable {
fiber,
marker: marker::PhantomData,
}
}
}
impl<'d, I, F> FiberAdapter<'d, I, F> {
pub fn input<'a, S, A, T, M>(_: &'a S, maker: M) -> M
where
M: FnOnce((A, &'a S, T)) -> F,
{
maker
}
pub unsafe fn new(future: F) -> Self {
Self {
future,
scope: marker::PhantomData,
thread: marker::PhantomData,
}
}
}
static BORROWED_VTABLE: task::RawWakerVTable =
task::RawWakerVTable::new(clone_inert, noop, noop, noop);
unsafe fn clone_inert(data: *const ()) -> task::RawWaker {
task::RawWaker::new(data, &BORROWED_VTABLE)
}
unsafe fn noop(_: *const ()) {}
#[pin_project::pin_project]
#[repr(transparent)]
#[doc(hidden)]
#[must_use = "a fiber does nothing unless it is driven"]
pub struct FiberAdapter<'d, I, F> {
#[pin]
future: F,
scope: marker::PhantomData<fn(&'d mut I) -> &'d mut I>,
thread: marker::PhantomData<ThreadBound>,
}
impl<'d, I, F> Fiber<'d> for FiberAdapter<'d, I, F>
where
F: Future,
{
type Output = F::Output;
fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<Self::Output> {
use core::task::{RawWaker, Waker};
let (this, context) = call.into_parts();
let mut frame = Frame::<I>::new(context);
let data = ptr::from_mut(&mut frame).cast_const().cast();
let raw = RawWaker::new(data, &BORROWED_VTABLE);
let waker = mem::ManuallyDrop::new(unsafe { Waker::from_raw(raw) });
let mut cx = task::Context::from_waker(&waker);
Future::poll(this.project().future, &mut cx)
}
}