1use std::{cell::Cell, error::Error, fmt, ptr, rc::Rc, time::Instant};
4
5use corosensei::{Coroutine, CoroutineResult, Yielder, stack::DefaultStack};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct ParkToken {
10 wait: u64,
11 generation: u64,
12}
13
14impl ParkToken {
15 pub fn new(wait: u64, generation: u64) -> Self {
17 Self { wait, generation }
18 }
19
20 pub fn wait(self) -> u64 {
22 self.wait
23 }
24
25 pub fn generation(self) -> u64 {
27 self.generation
28 }
29}
30
31#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct ParkRequest {
34 token: ParkToken,
35 deadline: Option<Instant>,
36}
37
38impl ParkRequest {
39 pub fn new(token: ParkToken, deadline: Option<Instant>) -> Self {
41 Self { token, deadline }
42 }
43
44 pub fn token(&self) -> ParkToken {
46 self.token
47 }
48
49 pub fn deadline(&self) -> Option<Instant> {
51 self.deadline
52 }
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
57pub enum Suspension {
58 YieldNow,
60 Park(ParkRequest),
62}
63
64#[derive(Clone, Debug, PartialEq, Eq)]
66pub enum FiberState {
67 Suspended(Suspension),
69 Complete,
71}
72
73#[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
91pub struct Fiber {
98 coroutine: Option<Coroutine<(), Suspension, ()>>,
99 yielder: Rc<Cell<*const RawYielder>>,
100}
101
102impl Fiber {
103 pub fn new<F>(stack: DefaultStack, entry: F) -> Self
105 where
106 F: FnOnce() + 'static,
107 {
108 unsafe { Self::borrowed(stack, entry) }
110 }
111
112 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 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 pub fn resume(&mut self) -> FiberState {
135 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 pub fn is_complete(&self) -> bool {
150 self.coroutine
151 .as_ref()
152 .is_none_or(|coroutine| coroutine.done())
153 }
154
155 pub fn into_stack(mut self) -> DefaultStack {
159 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
178pub 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 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;