2020-04-21 01:20:35 +09:00
|
|
|
#[macro_use]
|
|
|
|
extern crate napi_rs as napi;
|
|
|
|
#[macro_use]
|
2020-04-26 21:21:45 +09:00
|
|
|
extern crate napi_rs_derive;
|
2020-04-21 01:20:35 +09:00
|
|
|
|
2020-04-26 19:46:56 +09:00
|
|
|
use napi::{Any, CallContext, Env, Error, Number, Object, Result, Status, Value};
|
2020-04-26 17:58:11 +09:00
|
|
|
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>>> {
|
2020-04-26 19:46:56 +09:00
|
|
|
exports.set_named_property("testThrow", env.create_function("testThrow", test_throw)?)?;
|
2020-04-26 17:58:11 +09:00
|
|
|
|
2020-04-26 19:46:56 +09:00
|
|
|
exports.set_named_property("fibonacci", env.create_function("fibonacci", fibonacci)?)?;
|
2020-04-21 01:20:35 +09:00
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[js_function]
|
2020-05-02 01:21:38 +09:00
|
|
|
fn test_throw(_ctx: CallContext) -> Result<Value<Any>> {
|
2020-04-21 01:20:35 +09:00
|
|
|
Err(Error::new(Status::GenericFailure))
|
|
|
|
}
|
2020-04-26 17:58:11 +09:00
|
|
|
|
2020-04-27 11:35:48 +09:00
|
|
|
#[js_function(1)]
|
2020-05-02 01:21:38 +09:00
|
|
|
fn fibonacci(ctx: CallContext) -> Result<Value<Number>> {
|
2020-04-26 17:58:11 +09:00
|
|
|
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,
|
2020-04-26 19:46:56 +09:00
|
|
|
_ => fibonacci_native(n - 1) + fibonacci_native(n - 2),
|
2020-04-26 17:58:11 +09:00
|
|
|
}
|
|
|
|
}
|