napi-rs/napi-derive
LongYinan 8497479c7a
chore(release): publish
- napi@0.4.2
- napi-derive@0.4.1
2020-07-18 11:05:20 +08:00
..
src feat(napi): implement either type 2020-07-18 02:11:49 +08:00
Cargo.toml chore(release): publish 2020-07-18 11:05:20 +08:00
README.md refactor(napi): redesign the JavaScript values API 2020-06-28 23:29:04 +08:00

napi-derive

js_function

#[macro_use]
extern crate napi_rs as napi;
#[macro_use]
extern crate napi_rs_derive;

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

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))
}

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