2020-07-18 03:00:48 +09:00
|
|
|
use std::convert::TryInto;
|
|
|
|
|
2020-11-25 18:42:14 +09:00
|
|
|
use napi::{CallContext, Either, JsNumber, JsObject, JsString, Result};
|
2020-07-18 03:00:48 +09:00
|
|
|
|
|
|
|
#[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) => {
|
2020-09-28 01:27:37 +09:00
|
|
|
let content = format!("Either::B({})", s.into_utf8()?.as_str()?);
|
2020-07-18 03:00:48 +09:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
2020-09-02 18:05:53 +09:00
|
|
|
|
2020-11-25 18:42:14 +09:00
|
|
|
pub fn register_js(exports: &mut JsObject) -> Result<()> {
|
|
|
|
exports.create_named_method("eitherNumberString", either_number_string)?;
|
|
|
|
exports.create_named_method("dynamicArgumentLength", dynamic_argument_length)?;
|
2020-09-02 18:05:53 +09:00
|
|
|
Ok(())
|
|
|
|
}
|