diff --git a/napi-derive-example/src/lib.rs b/napi-derive-example/src/lib.rs index 832a60b9..c1696b0d 100644 --- a/napi-derive-example/src/lib.rs +++ b/napi-derive-example/src/lib.rs @@ -3,7 +3,8 @@ extern crate napi_rs as napi; #[macro_use] extern crate napi_derive; -use napi::{Any, Env, Error, Object, Result, Status, Value, CallContext}; +use napi::{Any, Env, Error, Object, Result, Status, Value, CallContext, Number}; +use std::convert::TryInto; register_module!(test_module, init); @@ -15,12 +16,31 @@ fn init<'env>( "testThrow", env.create_function("testThrow", test_throw)?, )?; + + exports.set_named_property( + "fibonacci", + env.create_function("fibonacci", fibonacci)?, + )?; Ok(None) } #[js_function] fn test_throw<'a>( - ctx: CallContext, + _ctx: CallContext, ) -> Result> { Err(Error::new(Status::GenericFailure)) } + +#[js_function] +fn fibonacci<'env>(ctx: CallContext<'env>) -> Result> { + let n = ctx.get::(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) + } +} diff --git a/napi-derive/README.md b/napi-derive/README.md new file mode 100644 index 00000000..8c04b96d --- /dev/null +++ b/napi-derive/README.md @@ -0,0 +1,23 @@ +# napi-derive + +## js_function + +```rust +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> { + let n = ctx.get::(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) + } +} +```