Skip to content

Commit

Permalink
Merge pull request #1059 from neon-bindings/kv/with
Browse files Browse the repository at this point in the history
feat(neon): With wrapper for TryIntoJs
  • Loading branch information
kjvalencik authored Aug 28, 2024
2 parents dae95b1 + f25ef4d commit 471a70e
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
4 changes: 3 additions & 1 deletion crates/neon/src/types_impl/extract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ use crate::{
types::{JsValue, Value},
};

pub use self::error::Error;
pub use self::{error::Error, with::With};

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
pub use self::json::Json;
Expand All @@ -119,6 +120,7 @@ mod json;
mod private;
mod try_from_js;
mod try_into_js;
mod with;

/// Extract Rust data from a JavaScript value
pub trait TryFromJs<'cx>
Expand Down
58 changes: 58 additions & 0 deletions crates/neon/src/types_impl/extract/with.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use crate::{
context::{Context, Cx},
result::JsResult,
types::extract::TryIntoJs,
};

/// Wraps a closure that will be lazily evaluated when [`TryIntoJs::try_into_js`] is
/// called.
///
/// Useful for executing arbitrary code on the main thread before returning from a
/// function exported with [`neon::export`](crate::export).
///
/// ## Example
///
/// ```
/// # use neon::{prelude::*, types::extract::{TryIntoJs, With}};
/// use std::time::Instant;
///
/// #[neon::export(task)]
/// fn sum(nums: Vec<f64>) -> impl for<'cx> TryIntoJs<'cx> {
/// let start = Instant::now();
/// let sum = nums.into_iter().sum::<f64>();
/// let log = format!("sum took {} ms", start.elapsed().as_millis());
///
/// With(move |cx| -> NeonResult<_> {
/// cx.global::<JsObject>("console")?
/// .call_method_with(cx, "log")?
/// .arg(cx.string(log))
/// .exec(cx)?;
///
/// Ok(sum)
/// })
/// }
/// ```
pub struct With<F, O>(pub F)
where
// N.B.: We include additional required bounds to allow the compiler to infer the
// correct closure argument when using `impl for<'cx> TryIntoJs<'cx>`. Without
// these bounds, it would be necessary to write a more verbose signature:
// `With<impl for<'cx> FnOnce(&mut Cx<'cx>) -> SomeConcreteReturnType>`.
for<'cx> F: FnOnce(&mut Cx<'cx>) -> O;

impl<'cx, F, O> TryIntoJs<'cx> for With<F, O>
where
F: FnOnce(&mut Cx) -> O,
O: TryIntoJs<'cx>,
{
type Value = O::Value;

fn try_into_js<C>(self, cx: &mut C) -> JsResult<'cx, Self::Value>
where
C: Context<'cx>,
{
(self.0)(cx.cx_mut()).try_into_js(cx)
}
}

impl<F, O> super::private::Sealed for With<F, O> where for<'cx> F: FnOnce(&mut Cx<'cx>) -> O {}

0 comments on commit 471a70e

Please sign in to comment.