Skip to content

Commit

Permalink
Fixed minor safety issue, added AsyncContext::with function
Browse files Browse the repository at this point in the history
  • Loading branch information
DelSkayn committed Jun 5, 2023
1 parent 2b4723f commit 5b6a03d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
22 changes: 17 additions & 5 deletions core/src/context/async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,21 +207,18 @@ impl AsyncContext {
}

/// A entry point for manipulating and using javascript objects and scripts.
/// The api is structured this way to avoid repeated locking the runtime when ever
/// any function is called. This way the runtime is locked once before executing the callback.
/// Furthermore, this way it is impossible to use values from different runtimes in this
/// context which would otherwise be undefined behaviour.
///
/// This function is rather limited in what environment it can capture. If you need to borrow
/// the environment in the closure use the [`async_with!`] macro.
///
/// Unfortunatly it is currently impossible to have closures return a generic future which has a higher
/// rank trait bound lifetime. So, to allow closures to work, the closure must return a boxed
/// future.
pub async fn async_with<'a, F, R: 'a>(&'a self, f: F) -> R
pub async fn async_with<F, R>(&self, f: F) -> R
where
F: for<'js> FnOnce(Ctx<'js>) -> Pin<Box<dyn Future<Output = R> + 'js + Send>>
+ ParallelSend,
R: ParallelSend,
{
let future = {
let guard = self.rt.inner.lock().await;
Expand All @@ -236,6 +233,21 @@ impl AsyncContext {
}
.await
}

/// A entry point for manipulating and using javascript objects and scripts.
///
/// This closure can't return a future, if you need to await javascript promises prefer the
/// [`async_with!`] macro.
pub async fn with<F, R>(&self, f: F) -> R
where
F: for<'js> FnOnce(Ctx<'js>) -> R + ParallelSend,
R: ParallelSend,
{
let guard = self.rt.inner.lock().await;
guard.update_stack_top();
let ctx = unsafe { Ctx::new_async(self) };
f(ctx)
}
}

impl Drop for AsyncContext {
Expand Down
5 changes: 1 addition & 4 deletions core/src/runtime/async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ use async_lock::Mutex;
use crate::allocator::Allocator;
#[cfg(feature = "loader")]
use crate::loader::{RawLoader, Resolver};
use crate::{
context::AsyncContext, markers::ParallelSend, result::AsyncJobException, Ctx, Error, Exception,
Result,
};
use crate::{context::AsyncContext, result::AsyncJobException, Ctx, Error, Exception, Result};

use super::{
raw::{Opaque, RawRuntime},
Expand Down

0 comments on commit 5b6a03d

Please sign in to comment.