Skip to main content

vthread_stack/
fiber.rs

1//! Carrier-local stackful fiber.
2
3use crate::{
4    FiberState, MappedStack, Resume, engine,
5    mount::{ContextSlot, CoreMount, MountGuard},
6};
7
8/// One carrier-local stackful execution context.
9///
10/// ```compile_fail
11/// fn require_send<T: Send>() {}
12/// require_send::<vthread_stack::Fiber>();
13/// ```
14pub struct Fiber {
15    execution: Option<engine::Execution>,
16}
17
18impl Fiber {
19    /// Creates a fiber on an already allocated stack.
20    pub fn new<F>(stack: MappedStack, entry: F) -> Self
21    where
22        F: FnOnce() + 'static,
23    {
24        // SAFETY: a static entry has no borrowed environment to outlive.
25        unsafe { Self::borrowed(stack, entry) }
26    }
27
28    /// The caller must reclaim this fiber before the entry's borrows expire.
29    pub(crate) unsafe fn borrowed<F: FnOnce()>(stack: MappedStack, entry: F) -> Self {
30        // SAFETY: the caller owns the entry's lifetime and guarantees reclamation.
31        let execution = unsafe { engine::Execution::start(stack, entry) };
32        Self {
33            execution: Some(execution),
34        }
35    }
36
37    /// Mounts the fiber until it suspends or completes.
38    ///
39    /// Panics if the fiber has already completed, without mounting its old control block.
40    #[inline]
41    pub fn resume(&mut self) -> FiberState {
42        self.resume_with(Resume::Continue)
43    }
44
45    /// Mounts the fiber and delivers a decision to its last suspension point.
46    #[inline]
47    pub fn resume_with(&mut self, resume: Resume) -> FiberState {
48        self.resume_mounted(resume, None)
49    }
50
51    /// Mounts the fiber with typed runtime context for this resume only.
52    #[doc(hidden)]
53    #[inline]
54    pub fn resume_with_context<T>(
55        &mut self,
56        resume: Resume,
57        key: &'static crate::ContextKey<T>,
58        value: &T,
59    ) -> FiberState {
60        let context = ContextSlot::new(key, value);
61        self.resume_mounted(resume, Some(&context))
62    }
63
64    #[inline]
65    fn resume_mounted(&mut self, resume: Resume, context: Option<&ContextSlot<'_>>) -> FiberState {
66        // Reject the transition before a panic hook can observe a stale mount.
67        assert!(!self.is_complete(), "a completed fiber cannot be resumed");
68        let execution = self
69            .execution
70            .as_mut()
71            .expect("a completed fiber cannot be resumed");
72        let _mount = MountGuard::install(execution.core_ptr(), context);
73        execution.resume(resume)
74    }
75
76    /// Returns whether the entry function has completed.
77    pub fn is_complete(&self) -> bool {
78        self.execution
79            .as_ref()
80            .is_none_or(|execution| execution.is_complete())
81    }
82
83    /// Reclaims the stack after completion so it can be reused.
84    ///
85    /// Panics if incomplete; suspended frames unwind on their fiber, while an
86    /// unstarted entry is reclaimed on the caller's stack.
87    pub fn into_stack(mut self) -> MappedStack {
88        // Keep ownership here on failure so Drop selects the correct reclamation context.
89        assert!(
90            self.is_complete(),
91            "an incomplete fiber cannot be extracted"
92        );
93        self.execution
94            .take()
95            .expect("fiber stack already extracted")
96            .into_stack()
97    }
98}
99
100impl Drop for Fiber {
101    fn drop(&mut self) {
102        if let Some(execution) = self.execution.take() {
103            // An unstarted entry is dropped on the caller's stack. Its destructors
104            // must retain that caller's suspension context, if any.
105            let _mount = execution
106                .is_suspended()
107                .then(|| CoreMount::install(execution.core_ptr()));
108            drop(execution);
109        }
110    }
111}
112
113#[cfg(test)]
114#[path = "fiber_test.rs"]
115mod fiber_test;
116
117#[cfg(test)]
118#[path = "fiber_drop_test.rs"]
119mod fiber_drop_test;