doc: add napi-derive example and document

This commit is contained in:
LongYinan 2020-04-26 16:58:11 +08:00
parent 0b2561225f
commit 0f28cc7bdf
No known key found for this signature in database
GPG key ID: A3FFE134A3E20881
2 changed files with 45 additions and 2 deletions

View file

@ -3,7 +3,8 @@ extern crate napi_rs as napi;
#[macro_use] #[macro_use]
extern crate napi_derive; 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); register_module!(test_module, init);
@ -15,12 +16,31 @@ fn init<'env>(
"testThrow", "testThrow",
env.create_function("testThrow", test_throw)?, env.create_function("testThrow", test_throw)?,
)?; )?;
exports.set_named_property(
"fibonacci",
env.create_function("fibonacci", fibonacci)?,
)?;
Ok(None) Ok(None)
} }
#[js_function] #[js_function]
fn test_throw<'a>( fn test_throw<'a>(
ctx: CallContext, _ctx: CallContext,
) -> Result<Value<'a, Any>> { ) -> Result<Value<'a, Any>> {
Err(Error::new(Status::GenericFailure)) Err(Error::new(Status::GenericFailure))
} }
#[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)
}
}

23
napi-derive/README.md Normal file
View file

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