2020-04-21 01:20:35 +09:00
|
|
|
#[macro_use]
|
|
|
|
extern crate napi_rs as napi;
|
|
|
|
#[macro_use]
|
|
|
|
extern crate napi_derive;
|
|
|
|
|
2020-04-26 17:58:11 +09:00
|
|
|
use napi::{Any, Env, Error, Object, Result, Status, Value, CallContext, Number};
|
|
|
|
use std::convert::TryInto;
|
2020-04-21 01:20:35 +09:00
|
|
|
|
|
|
|
register_module!(test_module, init);
|
|
|
|
|
|
|
|
fn init<'env>(
|
|
|
|
env: &'env Env,
|
|
|
|
exports: &'env mut Value<'env, Object>,
|
|
|
|
) -> Result<Option<Value<'env, Object>>> {
|
|
|
|
exports.set_named_property(
|
|
|
|
"testThrow",
|
|
|
|
env.create_function("testThrow", test_throw)?,
|
|
|
|
)?;
|
2020-04-26 17:58:11 +09:00
|
|
|
|
|
|
|
exports.set_named_property(
|
|
|
|
"fibonacci",
|
|
|
|
env.create_function("fibonacci", fibonacci)?,
|
|
|
|
)?;
|
2020-04-21 01:20:35 +09:00
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[js_function]
|
|
|
|
fn test_throw<'a>(
|
2020-04-26 17:58:11 +09:00
|
|
|
_ctx: CallContext,
|
2020-04-21 01:20:35 +09:00
|
|
|
) -> Result<Value<'a, Any>> {
|
|
|
|
Err(Error::new(Status::GenericFailure))
|
|
|
|
}
|
2020-04-26 17:58:11 +09:00
|
|
|
|
|
|
|
#[js_function]
|
|
|
|
fn fibonacci<'env>(ctx: CallContext<'env>) -> Result<Value<'env, Number>> {
|
|
|
|
let n = ctx.get::<Number>(0)?.try_into()?;
|
|
|
|
ctx.env.create_int64(fibonacci_native(n))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn fibonacci_native(n: i64) -> i64 {
|
|
|
|
match n {
|
|
|
|
1 | 2 => 1,
|
|
|
|
_ => fibonacci_native(n - 1) + fibonacci_native(n - 2)
|
|
|
|
}
|
|
|
|
}
|