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