use crate::{
Fiber, FiberLease, MappedStack,
panic_payload::{self, CapturedPanic},
};
use std::{
cell::{Cell, RefCell},
io,
marker::PhantomData,
rc::Rc,
};
pub struct FiberScope<'scope, 'env: 'scope> {
registry: Rc<Registry>,
scope: PhantomData<&'scope mut &'scope ()>,
env: PhantomData<&'env mut &'env ()>,
}
struct Registry {
fibers: RefCell<Vec<FiberLease>>,
capacity: usize,
closed: Cell<bool>,
}
struct ScopeGuard(Rc<Registry>);
impl<'scope, 'env> FiberScope<'scope, 'env> {
pub fn spawn(
&'scope self,
stack: MappedStack,
entry: impl FnOnce() + 'scope,
) -> io::Result<FiberLease> {
let mut fibers = self.registry.fibers.borrow_mut();
fibers.retain(FiberLease::live);
if self.registry.closed.get() || fibers.len() >= self.registry.capacity {
return Err(io::Error::other("borrowed fiber scope closed or full"));
}
let fiber = unsafe { Fiber::borrowed(stack, entry) };
let lease = FiberLease::new(fiber);
fibers.push(lease.clone());
Ok(lease)
}
}
impl ScopeGuard {
fn drain(&self) -> Option<CapturedPanic> {
self.0.closed.set(true);
let fibers = self.0.fibers.take();
let mut failure = None;
for fiber in fibers {
for _ in 0..2 {
if !fiber.live() {
break;
}
if let Err(payload) =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| fiber.reclaim()))
{
panic_payload::retain(&mut failure, payload);
}
}
if fiber.live() {
std::process::abort();
}
}
failure
}
}
impl Drop for ScopeGuard {
fn drop(&mut self) {
self.drain();
}
}
pub fn fiber_scope<'env, R>(
capacity: usize,
body: impl for<'scope> FnOnce(&'scope FiberScope<'scope, 'env>) -> R,
) -> R {
let registry = Rc::new(Registry {
fibers: RefCell::new(Vec::new()),
capacity,
closed: Cell::new(false),
});
let scope = FiberScope {
registry,
scope: PhantomData,
env: PhantomData,
};
let guard = ScopeGuard(Rc::clone(&scope.registry));
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| body(&scope)));
let cleanup = guard.drain();
match result {
Err(payload) => {
drop(cleanup);
std::panic::resume_unwind(payload)
}
Ok(value) => {
if let Some(failure) = cleanup {
std::panic::resume_unwind(Box::new(failure));
}
value
}
}
}
#[cfg(test)]
#[path = "scoped_test.rs"]
mod scoped_test;