1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
//! Traits and utilities for extract Rust data from JavaScript values.
//!
//! The full list of included extractors can be found on [`TryFromJs`].
//!
//! ## Extracting Handles
//!
//! JavaScript arguments may be extracted into a Rust tuple.
//!
//! ```
//! # use neon::{prelude::*, types::extract::*};
//! fn greet(mut cx: FunctionContext) -> JsResult<JsString> {
//! let (greeting, name): (Handle<JsString>, Handle<JsString>) = cx.args()?;
//! let message = format!("{}, {}!", greeting.value(&mut cx), name.value(&mut cx));
//!
//! Ok(cx.string(message))
//! }
//! ```
//!
//! ## Extracting Native Types
//!
//! It's also possible to extract directly into native Rust types instead of a [`Handle`].
//!
//! ```
//! # use neon::{prelude::*, types::extract::*};
//! fn add(mut cx: FunctionContext) -> JsResult<JsNumber> {
//! let (a, b): (f64, f64) = cx.args()?;
//!
//! Ok(cx.number(a + b))
//! }
//! ```
//!
//! ## Extracting [`Option`]
//!
//! It's also possible to mix [`Handle`], Rust types, and even [`Option`] for
//! handling `null` and `undefined`.
//!
//! ```
//! # use neon::{prelude::*, types::extract::*};
//! fn get_or_default(mut cx: FunctionContext) -> JsResult<JsValue> {
//! let (n, default_value): (Option<f64>, Handle<JsValue>) = cx.args()?;
//!
//! if let Some(n) = n {
//! return Ok(cx.number(n).upcast());
//! }
//!
//! Ok(default_value)
//! }
//! ```
//!
//! ## Additional Extractors
//!
//! In some cases, the expected JavaScript type is ambiguous. For example, when
//! trying to extract an [`f64`], the argument may be a `Date` instead of a `number`.
//! Newtype extractors are provided to help.
//!
//! ```
//! # use neon::{prelude::*, types::extract::*};
//! # #[cfg(feature = "napi-5")]
//! # use neon::types::JsDate;
//!
//! # #[cfg(feature = "napi-5")]
//! fn add_hours(mut cx: FunctionContext) -> JsResult<JsDate> {
//! const MS_PER_HOUR: f64 = 60.0 * 60.0 * 1000.0;
//!
//! let (Date(date), hours): (Date, f64) = cx.args()?;
//! let date = date + hours * MS_PER_HOUR;
//!
//! cx.date(date).or_throw(&mut cx)
//! }
//! ```
//!
//! ## Overloaded Functions
//!
//! It's common in JavaScript to overload function signatures. This can be implemented with
//! [`FunctionContext::args_opt`] or [`Context::try_catch`].
//!
//! ```
//! # use neon::{prelude::*, types::extract::*};
//!
//! fn add(mut cx: FunctionContext, a: f64, b: f64) -> Handle<JsNumber> {
//! cx.number(a + b)
//! }
//!
//! fn concat(mut cx: FunctionContext, a: String, b: String) -> Handle<JsString> {
//! cx.string(a + &b)
//! }
//!
//! fn combine(mut cx: FunctionContext) -> JsResult<JsValue> {
//! if let Some((a, b)) = cx.args_opt()? {
//! return Ok(add(cx, a, b).upcast());
//! }
//!
//! let (a, b) = cx.args()?;
//!
//! Ok(concat(cx, a, b).upcast())
//! }
//! ```
//!
//! Note well, in this example, type annotations are not required on the tuple because
//! Rust is able to infer it from the type arguments on `add` and `concat`.
use crate::{
context::{Context, FunctionContext},
handle::Handle,
result::NeonResult,
types::JsValue,
};
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
pub use self::json::*;
pub use self::types::*;
#[cfg(feature = "serde")]
mod json;
mod types;
/// Extract Rust data from a JavaScript value
pub trait TryFromJs<'cx>
where
Self: private::Sealed + Sized,
{
// Consider adding a trait bound prior to unsealing `TryFromjs`
// https://github.com/neon-bindings/neon/issues/1026
type Error;
fn try_from_js<C>(cx: &mut C, v: Handle<'cx, JsValue>) -> NeonResult<Result<Self, Self::Error>>
where
C: Context<'cx>;
fn from_js<C>(cx: &mut C, v: Handle<'cx, JsValue>) -> NeonResult<Self>
where
C: Context<'cx>;
}
/// Trait specifying values that may be extracted from function arguments.
///
/// **Note:** This trait is implemented for tuples of up to 32 values, but for
/// the sake of brevity, only tuples up to size 8 are shown in this documentation.
pub trait FromArgs<'cx>: private::FromArgsInternal<'cx> {}
// Convenience implementation for single arguments instead of needing a single element tuple
impl<'cx, T> private::FromArgsInternal<'cx> for T
where
T: TryFromJs<'cx>,
{
fn from_args(cx: &mut FunctionContext<'cx>) -> NeonResult<Self> {
let (v,) = private::FromArgsInternal::from_args(cx)?;
Ok(v)
}
fn from_args_opt(cx: &mut FunctionContext<'cx>) -> NeonResult<Option<Self>> {
if let Some((v,)) = private::FromArgsInternal::from_args_opt(cx)? {
Ok(Some(v))
} else {
Ok(None)
}
}
}
impl<'cx, T> FromArgs<'cx> for T where T: TryFromJs<'cx> {}
// N.B.: `FromArgs` _could_ have a blanket impl for `T` where `T: FromArgsInternal`.
// However, it is explicitly implemented in the macro in order for it to be included in docs.
macro_rules! from_args_impl {
($(#[$attrs:meta])? [$($ty:ident),*]) => {
$(#[$attrs])?
impl<'cx, $($ty,)*> FromArgs<'cx> for ($($ty,)*)
where
$($ty: TryFromJs<'cx>,)*
{}
#[allow(non_snake_case)]
impl<'cx, $($ty,)*> private::FromArgsInternal<'cx> for ($($ty,)*)
where
$($ty: TryFromJs<'cx>,)*
{
fn from_args(cx: &mut FunctionContext<'cx>) -> NeonResult<Self> {
let [$($ty,)*] = cx.argv();
Ok(($($ty::from_js(cx, $ty)?,)*))
}
fn from_args_opt(cx: &mut FunctionContext<'cx>) -> NeonResult<Option<Self>> {
let [$($ty,)*] = cx.argv();
Ok(Some((
$(match $ty::try_from_js(cx, $ty)? {
Ok(v) => v,
Err(_) => return Ok(None),
},)*
)))
}
}
}
}
macro_rules! from_args_expand {
($(#[$attrs:meta])? [$($head:ident),*], []) => {};
($(#[$attrs:meta])? [$($head:ident),*], [$cur:ident $(, $tail:ident)*]) => {
from_args_impl!($(#[$attrs])? [$($head,)* $cur]);
from_args_expand!($(#[$attrs])? [$($head,)* $cur], [$($tail),*]);
};
}
macro_rules! from_args {
([$($show:ident),*], [$($hide:ident),*]) => {
from_args_expand!([], [$($show),*]);
from_args_expand!(#[doc(hidden)] [$($show),*], [$($hide),*]);
};
}
// Implement `FromArgs` for tuples up to length `32`. The first list is included
// in docs and the second list is `#[doc(hidden)]`.
from_args!(
[T1, T2, T3, T4, T5, T6, T7, T8],
[
T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26,
T27, T28, T29, T30, T31, T32
]
);
mod private {
use crate::{context::FunctionContext, result::NeonResult};
pub trait Sealed {}
pub trait FromArgsInternal<'cx>: Sized {
fn from_args(cx: &mut FunctionContext<'cx>) -> NeonResult<Self>;
fn from_args_opt(cx: &mut FunctionContext<'cx>) -> NeonResult<Option<Self>>;
}
}