use std::{cell::Cell, error::Error, fmt, ptr, rc::Rc, time::Instant};
use corosensei::{Coroutine, CoroutineResult, Yielder, stack::DefaultStack};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ParkToken {
wait: u64,
generation: u64,
}
impl ParkToken {
pub fn new(wait: u64, generation: u64) -> Self {
Self { wait, generation }
}
pub fn wait(self) -> u64 {
self.wait
}
pub fn generation(self) -> u64 {
self.generation
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParkRequest {
token: ParkToken,
deadline: Option<Instant>,
}
impl ParkRequest {
pub fn new(token: ParkToken, deadline: Option<Instant>) -> Self {
Self { token, deadline }
}
pub fn token(&self) -> ParkToken {
self.token
}
pub fn deadline(&self) -> Option<Instant> {
self.deadline
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Suspension {
YieldNow,
Park(ParkRequest),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FiberState {
Suspended(Suspension),
Complete,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SuspendError;
impl fmt::Display for SuspendError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("no virtual-thread stack is mounted on this carrier")
}
}
impl Error for SuspendError {}
type RawYielder = Yielder<(), Suspension>;
thread_local! {
static CURRENT_YIELDER: Cell<*const RawYielder> = const { Cell::new(ptr::null()) };
}
pub struct Fiber {
coroutine: Option<Coroutine<(), Suspension, ()>>,
yielder: Rc<Cell<*const RawYielder>>,
}
impl Fiber {
pub fn new<F>(stack: DefaultStack, entry: F) -> Self
where
F: FnOnce() + 'static,
{
unsafe { Self::borrowed(stack, entry) }
}
pub(crate) unsafe fn borrowed<F: FnOnce()>(stack: DefaultStack, entry: F) -> Self {
let yielder = Rc::new(Cell::new(ptr::null()));
let body_yielder = Rc::clone(&yielder);
let coroutine = unsafe {
Coroutine::with_stack_unchecked(stack, move |current, ()| {
let pointer = current as *const RawYielder;
body_yielder.set(pointer);
let _mount = MountGuard::install(pointer);
entry();
})
};
Self {
coroutine: Some(coroutine),
yielder,
}
}
pub fn resume(&mut self) -> FiberState {
assert!(!self.is_complete(), "a completed fiber cannot be resumed");
let _mount = MountGuard::install(self.yielder.get());
let coroutine = self
.coroutine
.as_mut()
.expect("a completed fiber cannot be resumed");
match coroutine.resume(()) {
CoroutineResult::Yield(reason) => FiberState::Suspended(reason),
CoroutineResult::Return(()) => FiberState::Complete,
}
}
pub fn is_complete(&self) -> bool {
self.coroutine
.as_ref()
.is_none_or(|coroutine| coroutine.done())
}
pub fn into_stack(mut self) -> DefaultStack {
assert!(
self.is_complete(),
"an incomplete fiber cannot be extracted"
);
self.coroutine
.take()
.expect("fiber stack already extracted")
.into_stack()
}
}
impl Drop for Fiber {
fn drop(&mut self) {
let _mount = MountGuard::install(self.yielder.get());
drop(self.coroutine.take());
}
}
pub fn suspend(reason: Suspension) -> Result<(), SuspendError> {
CURRENT_YIELDER.with(|current| {
let pointer = current.get();
if pointer.is_null() {
return Err(SuspendError);
}
unsafe {
(&*pointer).suspend(reason);
}
Ok(())
})
}
struct MountGuard {
previous: *const RawYielder,
}
impl MountGuard {
fn install(pointer: *const RawYielder) -> Self {
let previous = CURRENT_YIELDER.with(|current| current.replace(pointer));
Self { previous }
}
}
impl Drop for MountGuard {
fn drop(&mut self) {
CURRENT_YIELDER.with(|current| current.set(self.previous));
}
}
#[cfg(test)]
#[path = "fiber_test.rs"]
mod fiber_test;