napi-rs/napi-derive-example/src/lib.rs

36 lines
925 B
Rust
Raw Normal View History

2020-04-21 01:20:35 +09:00
#[macro_use]
extern crate napi_rs as napi;
#[macro_use]
extern crate napi_rs_derive;
2020-04-21 01:20:35 +09:00
use napi::{Any, CallContext, Env, Error, Number, Object, Result, Status, Value};
use std::convert::TryInto;
2020-04-21 01:20:35 +09:00
register_module!(test_module, init);
2020-05-09 16:14:44 +09:00
fn init(env: &Env, exports: &mut Value<Object>) -> Result<()> {
exports.set_named_property("testThrow", env.create_function("testThrow", test_throw)?)?;
exports.set_named_property("fibonacci", env.create_function("fibonacci", fibonacci)?)?;
2020-05-09 16:14:44 +09:00
Ok(())
2020-04-21 01:20:35 +09:00
}
#[js_function]
fn test_throw(_ctx: CallContext) -> Result<Value<Any>> {
Err(Error::from_status(Status::GenericFailure))
2020-04-21 01:20:35 +09:00
}
2020-04-27 11:35:48 +09:00
#[js_function(1)]
fn fibonacci(ctx: CallContext) -> Result<Value<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),
}
}