napi-rs/napi-derive
2020-04-26 19:57:31 +08:00
..
src refactor(napi-rs): impl TryFrom instead of TryInto 2020-04-26 18:46:56 +08:00
Cargo.toml chore: version patch 2020-04-26 19:57:31 +08:00
README.md doc: add napi-derive example and document 2020-04-26 16:58:11 +08:00

napi-derive

js_function

use napi_rs::{Result, Value, CallContext, Number};
use napi_derive::js_function;
use std::convert::TryInto;

#[js_function]
fn fibonacci<'env>(ctx: CallContext<'env>) -> Result<Value<'env, 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)
  }
}