napi-rs/examples/napi-compat-mode/src/either.rs
forehalo 2467b7139b
Introduce #[napi] procedural macro to automation development boilerplate (#696)
* napi procedural macro for basic rust/JavaScript types
* introduce the `compat-mode` for `napi` and `napi-derive` crates for backward compatible
* remove #[inline] and let compiler to decide the inline behavior
* cli now can produce the `.d.ts` file for native binding
* many tests and example for the new procedural macro

Co-authored-by: LongYinan <lynweklm@gmail.com>
2021-09-23 01:29:09 +08:00

35 lines
1.1 KiB
Rust

use std::convert::TryInto;
use napi::{CallContext, Either, JsNumber, JsObject, JsString, Result};
#[js_function(1)]
pub fn either_number_string(ctx: CallContext) -> Result<Either<JsNumber, JsString>> {
let arg = ctx.get::<Either<JsNumber, JsString>>(0)?;
match arg {
Either::A(n) => {
let n: u32 = n.try_into()?;
ctx.env.create_uint32(n + 100).map(Either::A)
}
Either::B(s) => {
let content = format!("Either::B({})", s.into_utf8()?.as_str()?);
ctx.env.create_string_from_std(content).map(Either::B)
}
}
}
#[js_function(1)]
pub fn dynamic_argument_length(ctx: CallContext) -> Result<JsNumber> {
let value: Option<JsNumber> = ctx.try_get::<JsNumber>(0)?.into();
if let Some(n) = value {
let n: u32 = n.try_into()?;
ctx.env.create_uint32(n + 100)
} else {
ctx.env.create_uint32(42)
}
}
pub fn register_js(exports: &mut JsObject) -> Result<()> {
exports.create_named_method("eitherNumberString", either_number_string)?;
exports.create_named_method("dynamicArgumentLength", dynamic_argument_length)?;
Ok(())
}