napi-rs/napi-derive
2021-03-22 13:38:42 +08:00
..
src Add a way to convert _stateful_ (Rust) closures into JsFunctions. 2021-03-18 21:09:55 +01:00
Cargo.toml napi-derive@1.0.1 2021-03-22 13:38:42 +08:00
README.md Remove deprecated register_module from example in README.md 2021-03-14 11:17:19 +03:00

napi-derive

js_function

#[macro_use]
extern crate napi_derive;

use napi::{CallContext, Error, JsNumber, JsUnknown, Module, Result, Status};
use std::convert::TryInto;

#[module_exports]
fn init(mut exports: JsObject) -> Result<()> {
  exports.create_named_method("testThrow", test_throw)?;
  exports.create_named_method("fibonacci", fibonacci)?;
  Ok(())
}

#[js_function]
fn test_throw(_ctx: CallContext) -> Result<JsUnknown> {
  Err(Error::from_status(Status::GenericFailure))
}

#[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),
  }
}