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

36 lines
822 B
Rust
Raw Normal View History

2020-04-21 01:20:35 +09:00
#[macro_use]
extern crate napi;
2020-04-21 01:20:35 +09:00
#[macro_use]
extern crate napi_derive;
2020-04-21 01:20:35 +09:00
use napi::{CallContext, Error, JsNumber, JsUnknown, Module, Result, Status};
use std::convert::TryInto;
2020-04-21 01:20:35 +09:00
register_module!(napi_derive_example, init);
2020-04-21 01:20:35 +09:00
fn init(module: &mut Module) -> Result<()> {
module.create_named_method("testThrow", test_throw)?;
module.create_named_method("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<JsUnknown> {
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<JsNumber> {
let n = ctx.get::<JsNumber>(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),
}
}