doc: add napi-derive example and document
This commit is contained in:
parent
0b2561225f
commit
0f28cc7bdf
2 changed files with 45 additions and 2 deletions
|
@ -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
23
napi-derive/README.md
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
Loading…
Reference in a new issue