1use crate::{
4 Fiber, FiberLease, MappedStack,
5 panic_payload::{self, CapturedPanic},
6};
7use std::{
8 cell::{Cell, RefCell},
9 io,
10 marker::PhantomData,
11 rc::Rc,
12};
13
14pub struct FiberScope<'scope, 'env: 'scope> {
16 registry: Rc<Registry>,
17 scope: PhantomData<&'scope mut &'scope ()>,
18 env: PhantomData<&'env mut &'env ()>,
19}
20
21struct Registry {
22 fibers: RefCell<Vec<FiberLease>>,
23 capacity: usize,
24 closed: Cell<bool>,
25}
26
27struct ScopeGuard(Rc<Registry>);
28
29impl<'scope, 'env> FiberScope<'scope, 'env> {
30 pub fn spawn(
32 &'scope self,
33 stack: MappedStack,
34 entry: impl FnOnce() + 'scope,
35 ) -> io::Result<FiberLease> {
36 let mut fibers = self.registry.fibers.borrow_mut();
37 fibers.retain(FiberLease::live);
38 if self.registry.closed.get() || fibers.len() >= self.registry.capacity {
39 return Err(io::Error::other("borrowed fiber scope closed or full"));
40 }
41 let fiber = unsafe { Fiber::borrowed(stack, entry) };
44 let lease = FiberLease::new(fiber);
45 fibers.push(lease.clone());
46 Ok(lease)
47 }
48}
49
50impl ScopeGuard {
51 fn drain(&self) -> Option<CapturedPanic> {
52 self.0.closed.set(true);
53 let fibers = self.0.fibers.take();
54 let mut failure = None;
55 for fiber in fibers {
56 for _ in 0..2 {
57 if !fiber.live() {
58 break;
59 }
60 if let Err(payload) =
61 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| fiber.reclaim()))
62 {
63 panic_payload::retain(&mut failure, payload);
64 }
65 }
66 if fiber.live() {
69 std::process::abort();
70 }
71 }
72 failure
73 }
74}
75
76impl Drop for ScopeGuard {
77 fn drop(&mut self) {
78 self.drain();
79 }
80}
81
82pub fn fiber_scope<'env, R>(
84 capacity: usize,
85 body: impl for<'scope> FnOnce(&'scope FiberScope<'scope, 'env>) -> R,
86) -> R {
87 let registry = Rc::new(Registry {
88 fibers: RefCell::new(Vec::new()),
89 capacity,
90 closed: Cell::new(false),
91 });
92 let scope = FiberScope {
93 registry,
94 scope: PhantomData,
95 env: PhantomData,
96 };
97 let guard = ScopeGuard(Rc::clone(&scope.registry));
100 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| body(&scope)));
102 let cleanup = guard.drain();
103 match result {
104 Err(payload) => {
105 drop(cleanup);
108 std::panic::resume_unwind(payload)
109 }
110 Ok(value) => {
111 if let Some(failure) = cleanup {
112 std::panic::resume_unwind(Box::new(failure));
113 }
114 value
115 }
116 }
117}
118
119#[cfg(test)]
120#[path = "scoped_test.rs"]
121mod scoped_test;