1use crate::{
4 FiberState, MappedStack, Resume, engine,
5 mount::{ContextSlot, CoreMount, MountGuard},
6};
7
8pub struct Fiber {
15 execution: Option<engine::Execution>,
16}
17
18impl Fiber {
19 pub fn new<F>(stack: MappedStack, entry: F) -> Self
21 where
22 F: FnOnce() + 'static,
23 {
24 unsafe { Self::borrowed(stack, entry) }
26 }
27
28 pub(crate) unsafe fn borrowed<F: FnOnce()>(stack: MappedStack, entry: F) -> Self {
30 let execution = unsafe { engine::Execution::start(stack, entry) };
32 Self {
33 execution: Some(execution),
34 }
35 }
36
37 #[inline]
41 pub fn resume(&mut self) -> FiberState {
42 self.resume_with(Resume::Continue)
43 }
44
45 #[inline]
47 pub fn resume_with(&mut self, resume: Resume) -> FiberState {
48 self.resume_mounted(resume, None)
49 }
50
51 #[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 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 pub fn is_complete(&self) -> bool {
78 self.execution
79 .as_ref()
80 .is_none_or(|execution| execution.is_complete())
81 }
82
83 pub fn into_stack(mut self) -> MappedStack {
88 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 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;