-
Notifications
You must be signed in to change notification settings - Fork 286
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1059 from neon-bindings/kv/with
feat(neon): With wrapper for TryIntoJs
- Loading branch information
Showing
2 changed files
with
61 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |