2020-04-26 17:58:11 +09:00
|
|
|
# napi-derive
|
|
|
|
|
|
|
|
## js_function
|
|
|
|
|
|
|
|
```rust
|
2020-04-26 21:21:45 +09:00
|
|
|
#[macro_use]
|
2020-06-21 20:10:06 +09:00
|
|
|
extern crate napi_rs as napi;
|
|
|
|
#[macro_use]
|
2020-04-26 21:21:45 +09:00
|
|
|
extern crate napi_rs_derive;
|
|
|
|
|
2020-06-21 20:10:06 +09:00
|
|
|
use napi::{CallContext, Error, JsNumber, JsUnknown, Module, Result, Status};
|
2020-04-26 17:58:11 +09:00
|
|
|
use std::convert::TryInto;
|
|
|
|
|
2020-06-21 20:10:06 +09:00
|
|
|
register_module!(napi_derive_example, init);
|
|
|
|
|
|
|
|
fn init(module: &mut Module) -> Result<()> {
|
|
|
|
module.create_named_method("testThrow", test_throw)?;
|
|
|
|
|
|
|
|
module.create_named_method("fibonacci", fibonacci)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[js_function]
|
|
|
|
fn test_throw(_ctx: CallContext) -> Result<JsUnknown> {
|
|
|
|
Err(Error::from_status(Status::GenericFailure))
|
|
|
|
}
|
|
|
|
|
2020-04-27 11:35:48 +09:00
|
|
|
#[js_function(1)]
|
2020-06-21 20:10:06 +09:00
|
|
|
fn fibonacci(ctx: CallContext) -> Result<JsNumber> {
|
|
|
|
let n = ctx.get::<JsNumber>(0)?.try_into()?;
|
2020-04-26 17:58:11 +09:00
|
|
|
ctx.env.create_int64(fibonacci_native(n))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn fibonacci_native(n: i64) -> i64 {
|
|
|
|
match n {
|
|
|
|
1 | 2 => 1,
|
2020-06-21 20:10:06 +09:00
|
|
|
_ => fibonacci_native(n - 1) + fibonacci_native(n - 2),
|
2020-04-26 17:58:11 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|