From 0f28cc7bdf417a92c12021f642c47fb27c67a2ee Mon Sep 17 00:00:00 2001 From: LongYinan Date: Sun, 26 Apr 2020 16:58:11 +0800 Subject: [PATCH] doc: add napi-derive example and document --- napi-derive-example/src/lib.rs | 24 ++++++++++++++++++++++-- napi-derive/README.md | 23 +++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 napi-derive/README.md 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) + } +} +```