use super::LocalScope;
use crate::{
Error, Result, context, control::Shared, error::ScopeRunError, local_carrier::LocalCarrier,
};
use std::{
cell::RefCell,
panic::{AssertUnwindSafe, catch_unwind},
rc::Rc,
time::Instant,
};
struct BorrowedScopeExit(Rc<LocalCarrier>);
impl Drop for BorrowedScopeExit {
fn drop(&mut self) {
self.0.publish_borrowed_scope_exit();
}
}
pub fn local_scope<'env, R>(
body: impl for<'scope> FnOnce(&LocalScope<'scope, 'env>) -> Result<R>,
) -> Result<R> {
run_local(None, body, crate::ScopeFailure::finish)?
}
pub fn local_scope_with_deadline<'env, R>(
deadline: Instant,
body: impl for<'scope> FnOnce(&LocalScope<'scope, 'env>) -> Result<R>,
) -> Result<R> {
run_local(Some(deadline), body, crate::ScopeFailure::finish)?
}
pub fn try_local_scope<'env, R, E>(
body: impl for<'scope> FnOnce(&LocalScope<'scope, 'env>) -> std::result::Result<R, E>,
) -> std::result::Result<R, ScopeRunError<E>> {
run_local(None, body, crate::ScopeFailure::finish_generic).map_err(ScopeRunError::Runtime)?
}
pub fn try_local_scope_with_deadline<'env, R, E>(
deadline: Instant,
body: impl for<'scope> FnOnce(&LocalScope<'scope, 'env>) -> std::result::Result<R, E>,
) -> std::result::Result<R, ScopeRunError<E>> {
run_local(Some(deadline), body, crate::ScopeFailure::finish_generic)
.map_err(ScopeRunError::Runtime)?
}
fn run_local<'env, R, E, O>(
deadline: Option<Instant>,
body: impl for<'scope> FnOnce(&LocalScope<'scope, 'env>) -> std::result::Result<R, E>,
finish: impl FnOnce(crate::ScopeFailure, std::result::Result<R, E>, Result<()>, &Shared) -> O,
) -> Result<O> {
let mounted = context::current().ok_or(Error::OutsideVThread)?;
let execution = std::rc::Rc::clone(mounted.execution()?);
execution.data.check()?;
let options = execution.data.options().child(deadline);
let _scope_exit = BorrowedScopeExit(Rc::clone(execution.local()));
Ok(vthread_stack::fiber_scope(
execution.shared().config.max_vthreads(),
|fibers| {
let scope = LocalScope {
fibers,
execution,
options,
records: RefCell::new(Vec::new()),
};
let outcome = catch_unwind(AssertUnwindSafe(|| body(&scope)));
let policy = scope.options.check();
if !matches!(&outcome, Ok(Ok(_))) || policy.is_err() {
scope.cancel();
}
let failures = scope.drain();
let policy = if matches!(&outcome, Ok(Ok(_))) {
policy.and_then(|()| scope.options.check())
} else {
policy
};
match outcome {
Err(payload) => failures.unwind(payload, policy, scope.execution.shared()),
Ok(result) => finish(failures, result, policy, scope.execution.shared()),
}
},
))
}
#[cfg(test)]
#[path = "local_scope_run_test.rs"]
mod local_scope_run_test;