Skip to main content

vthread_stack/
fiber.rs

1//! Carrier-local stackful fiber wrapper.
2
3use std::{cell::Cell, error::Error, fmt, ptr, rc::Rc, time::Instant};
4
5use corosensei::{Coroutine, CoroutineResult, Yielder, stack::DefaultStack};
6
7/// Identity for one generation of a parking operation.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct ParkToken {
10    wait: u64,
11    generation: u64,
12}
13
14impl ParkToken {
15    /// Creates a scheduler-visible token.
16    pub fn new(wait: u64, generation: u64) -> Self {
17        Self { wait, generation }
18    }
19
20    /// Returns the stable parking-object identity.
21    pub fn wait(self) -> u64 {
22        self.wait
23    }
24
25    /// Returns the monotonically increasing wait generation.
26    pub fn generation(self) -> u64 {
27        self.generation
28    }
29}
30
31/// Scheduler data supplied when a task parks.
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct ParkRequest {
34    token: ParkToken,
35    deadline: Option<Instant>,
36}
37
38impl ParkRequest {
39    /// Creates a parking request with an optional monotonic deadline.
40    pub fn new(token: ParkToken, deadline: Option<Instant>) -> Self {
41        Self { token, deadline }
42    }
43
44    /// Returns the wait token.
45    pub fn token(&self) -> ParkToken {
46        self.token
47    }
48
49    /// Returns the monotonic deadline, if one exists.
50    pub fn deadline(&self) -> Option<Instant> {
51        self.deadline
52    }
53}
54
55/// A reason a mounted fiber returned control to its carrier.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub enum Suspension {
58    /// The virtual thread cooperatively yielded its turn.
59    YieldNow,
60    /// The virtual thread parked on a modeled wait generation.
61    Park(ParkRequest),
62}
63
64/// The outcome of mounting a fiber once.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub enum FiberState {
67    /// Execution suspended with the supplied reason.
68    Suspended(Suspension),
69    /// The fiber returned from its entry function.
70    Complete,
71}
72
73/// Suspension was requested without a mounted fiber.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub struct SuspendError;
76
77impl fmt::Display for SuspendError {
78    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79        formatter.write_str("no virtual-thread stack is mounted on this carrier")
80    }
81}
82
83impl Error for SuspendError {}
84
85type RawYielder = Yielder<(), Suspension>;
86
87thread_local! {
88    static CURRENT_YIELDER: Cell<*const RawYielder> = const { Cell::new(ptr::null()) };
89}
90
91/// One carrier-local stackful execution context.
92///
93/// ```compile_fail
94/// fn require_send<T: Send>() {}
95/// require_send::<vthread_stack::Fiber>();
96/// ```
97pub struct Fiber {
98    coroutine: Option<Coroutine<(), Suspension, ()>>,
99    yielder: Rc<Cell<*const RawYielder>>,
100}
101
102impl Fiber {
103    /// Creates a fiber on an already allocated stack.
104    pub fn new<F>(stack: DefaultStack, entry: F) -> Self
105    where
106        F: FnOnce() + 'static,
107    {
108        // SAFETY: a static entry has no borrowed environment to outlive.
109        unsafe { Self::borrowed(stack, entry) }
110    }
111
112    /// The caller must reclaim this fiber before the entry's borrows expire.
113    pub(crate) unsafe fn borrowed<F: FnOnce()>(stack: DefaultStack, entry: F) -> Self {
114        let yielder = Rc::new(Cell::new(ptr::null()));
115        let body_yielder = Rc::clone(&yielder);
116        // SAFETY: the caller owns the entry's lifetime and guarantees reclamation.
117        let coroutine = unsafe {
118            Coroutine::with_stack_unchecked(stack, move |current, ()| {
119                let pointer = current as *const RawYielder;
120                body_yielder.set(pointer);
121                let _mount = MountGuard::install(pointer);
122                entry();
123            })
124        };
125        Self {
126            coroutine: Some(coroutine),
127            yielder,
128        }
129    }
130
131    /// Mounts the fiber until it suspends or completes.
132    ///
133    /// Panics if the fiber has already completed, without mounting its old yielder.
134    pub fn resume(&mut self) -> FiberState {
135        // Reject the transition before a panic hook can observe a stale mount.
136        assert!(!self.is_complete(), "a completed fiber cannot be resumed");
137        let _mount = MountGuard::install(self.yielder.get());
138        let coroutine = self
139            .coroutine
140            .as_mut()
141            .expect("a completed fiber cannot be resumed");
142        match coroutine.resume(()) {
143            CoroutineResult::Yield(reason) => FiberState::Suspended(reason),
144            CoroutineResult::Return(()) => FiberState::Complete,
145        }
146    }
147
148    /// Returns whether the entry function has completed.
149    pub fn is_complete(&self) -> bool {
150        self.coroutine
151            .as_ref()
152            .is_none_or(|coroutine| coroutine.done())
153    }
154
155    /// Reclaims the stack after completion so it can be reused.
156    ///
157    /// Panics if incomplete; the fiber is still reclaimed with its yielder mounted.
158    pub fn into_stack(mut self) -> DefaultStack {
159        // Keep ownership here on failure so Drop mounts the fiber for unwinding.
160        assert!(
161            self.is_complete(),
162            "an incomplete fiber cannot be extracted"
163        );
164        self.coroutine
165            .take()
166            .expect("fiber stack already extracted")
167            .into_stack()
168    }
169}
170
171impl Drop for Fiber {
172    fn drop(&mut self) {
173        let _mount = MountGuard::install(self.yielder.get());
174        drop(self.coroutine.take());
175    }
176}
177
178/// Suspends the currently mounted fiber.
179pub fn suspend(reason: Suspension) -> Result<(), SuspendError> {
180    CURRENT_YIELDER.with(|current| {
181        let pointer = current.get();
182        if pointer.is_null() {
183            return Err(SuspendError);
184        }
185
186        // The pointer is carrier-local and restored before leaving this mount.
187        // SAFETY: it belongs to the currently mounted, non-Send coroutine.
188        unsafe {
189            (&*pointer).suspend(reason);
190        }
191        Ok(())
192    })
193}
194
195struct MountGuard {
196    previous: *const RawYielder,
197}
198
199impl MountGuard {
200    fn install(pointer: *const RawYielder) -> Self {
201        let previous = CURRENT_YIELDER.with(|current| current.replace(pointer));
202        Self { previous }
203    }
204}
205
206impl Drop for MountGuard {
207    fn drop(&mut self) {
208        CURRENT_YIELDER.with(|current| current.set(self.previous));
209    }
210}
211
212#[cfg(test)]
213#[path = "fiber_test.rs"]
214mod fiber_test;