Skip to main content

vthread_stack/
mount.rs

1//! One carrier-local mount for suspension and runtime-owned typed context.
2
3use std::{cell::Cell, marker::PhantomData, ptr, sync::atomic::AtomicU8};
4
5use crate::{Resume, SuspendError, Suspension, context::FiberCore, engine};
6
7/// A typed identity for context supplied while a fiber is mounted.
8///
9/// This is a private runtime integration hook and has no compatibility contract.
10#[doc(hidden)]
11pub struct ContextKey<T> {
12    // Interior mutability gives every static key distinct, non-mergeable storage.
13    _identity: AtomicU8,
14    // Invariance prevents one key from being coerced to a different context type.
15    marker: PhantomData<fn(T) -> T>,
16}
17
18impl<T> ContextKey<T> {
19    /// Creates a unique context identity when stored in a static.
20    #[doc(hidden)]
21    pub const fn new() -> Self {
22        Self {
23            _identity: AtomicU8::new(0),
24            marker: PhantomData,
25        }
26    }
27
28    /// Runs `body` with the matching context from the current fiber mount.
29    ///
30    /// Suspending this fiber inside `body` returns [`SuspendError`], keeping the
31    /// borrowed context within its resume. Nested fibers may still suspend themselves.
32    #[doc(hidden)]
33    #[inline]
34    pub fn with<R>(&'static self, body: impl for<'context> FnOnce(&'context T) -> R) -> Option<R> {
35        CURRENT_MOUNT.with(|current| {
36            let context = current.get().context;
37            if context.is_null() {
38                return None;
39            }
40            // SAFETY: the mount guard keeps its stack-local slot alive while installed.
41            let slot = unsafe { &*context };
42            if slot.key != ptr::from_ref(self).cast() {
43                return None;
44            }
45            let _borrow = CoreMount::install(ptr::null());
46            // SAFETY: the key identifies a live T, and suspension is disabled until body returns.
47            // The higher-ranked callback also prevents the reference from escaping its result.
48            Some(body(unsafe { &*slot.value.cast::<T>() }))
49        })
50    }
51}
52
53impl<T> Default for ContextKey<T> {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59pub(crate) struct ContextSlot<'context> {
60    key: *const (),
61    value: *const (),
62    lifetime: PhantomData<&'context ()>,
63}
64
65impl<'context> ContextSlot<'context> {
66    pub(crate) fn new<T>(key: &'static ContextKey<T>, value: &'context T) -> Self {
67        Self {
68            key: ptr::from_ref(key).cast(),
69            value: ptr::from_ref(value).cast(),
70            lifetime: PhantomData,
71        }
72    }
73}
74
75#[derive(Clone, Copy)]
76struct CurrentMount {
77    core: *const FiberCore,
78    context: *const ContextSlot<'static>,
79}
80
81impl CurrentMount {
82    const EMPTY: Self = Self {
83        core: ptr::null(),
84        context: ptr::null(),
85    };
86}
87
88thread_local! {
89    static CURRENT_MOUNT: Cell<CurrentMount> = const { Cell::new(CurrentMount::EMPTY) };
90}
91
92/// Mounts one fiber's control block and optional typed context for one resume.
93pub(crate) struct MountGuard<'mount> {
94    previous: CurrentMount,
95    lifetime: PhantomData<&'mount ()>,
96}
97
98impl MountGuard<'_> {
99    #[inline]
100    pub(crate) fn install<'mount>(
101        core: *const FiberCore,
102        context: Option<&'mount ContextSlot<'_>>,
103    ) -> MountGuard<'mount> {
104        let mounted = CurrentMount {
105            core,
106            context: context.map_or(ptr::null(), |slot| ptr::from_ref(slot).cast()),
107        };
108        let previous = CURRENT_MOUNT.with(|current| current.replace(mounted));
109        MountGuard {
110            previous,
111            lifetime: PhantomData,
112        }
113    }
114}
115
116impl Drop for MountGuard<'_> {
117    #[inline]
118    fn drop(&mut self) {
119        CURRENT_MOUNT.with(|current| current.set(self.previous));
120    }
121}
122
123/// Mounts only a control block, leaving any typed context in place; used for reclamation.
124pub(crate) struct CoreMount {
125    previous: *const FiberCore,
126}
127
128impl CoreMount {
129    pub(crate) fn install(core: *const FiberCore) -> Self {
130        let previous = CURRENT_MOUNT.with(|current| {
131            let mut mounted = current.get();
132            let previous = mounted.core;
133            mounted.core = core;
134            current.set(mounted);
135            previous
136        });
137        Self { previous }
138    }
139}
140
141impl Drop for CoreMount {
142    fn drop(&mut self) {
143        CURRENT_MOUNT.with(|current| {
144            let mut mounted = current.get();
145            mounted.core = self.previous;
146            current.set(mounted);
147        });
148    }
149}
150
151pub(crate) fn mounted_core() -> *const FiberCore {
152    CURRENT_MOUNT.with(|current| current.get().core)
153}
154
155fn suspendable_core() -> Result<*const FiberCore, SuspendError> {
156    let core = mounted_core();
157    if core.is_null() {
158        return Err(SuspendError::NotMounted);
159    }
160    if std::thread::panicking() {
161        return Err(SuspendError::Panicking);
162    }
163    Ok(core)
164}
165
166/// Checks whether the current carrier can safely suspend its mounted fiber.
167#[doc(hidden)]
168#[inline]
169pub fn check_suspend() -> Result<(), SuspendError> {
170    suspendable_core().map(|_| ())
171}
172
173/// Suspends the currently mounted fiber.
174#[inline]
175pub fn suspend(reason: Suspension) -> Result<Resume, SuspendError> {
176    let core = suspendable_core()?;
177    // The pointer is carrier-local and restored before leaving this mount.
178    // SAFETY: it belongs to the currently mounted, non-Send execution.
179    unsafe { Ok(engine::suspend(core, reason)) }
180}
181
182#[cfg(test)]
183#[path = "mount_test.rs"]
184mod mount_test;
185
186#[cfg(test)]
187#[path = "mount_borrow_test.rs"]
188mod mount_borrow_test;