napi-rs/bench/src/async_compute.rs

34 lines
849 B
Rust
Raw Normal View History

2020-09-28 01:27:37 +09:00
use napi::{
CallContext, Env, JsBuffer, JsBufferValue, JsNumber, JsObject, Module, Ref, Result, Task,
};
#[repr(transparent)]
2020-09-28 01:27:37 +09:00
struct BufferLength(Ref<JsBufferValue>);
impl Task for BufferLength {
type Output = usize;
type JsValue = JsNumber;
fn compute(&mut self) -> Result<Self::Output> {
2020-09-28 01:27:37 +09:00
Ok((&self.0).len())
}
2020-09-28 01:27:37 +09:00
fn resolve(self, env: Env, output: Self::Output) -> Result<Self::JsValue> {
self.0.unref(env)?;
env.create_uint32(output as u32)
}
}
#[js_function(1)]
fn bench_async_task(ctx: CallContext) -> Result<JsObject> {
let n = ctx.get::<JsBuffer>(0)?;
2020-09-28 01:27:37 +09:00
let task = BufferLength(n.into_ref()?);
let async_promise = ctx.env.spawn(task)?;
Ok(async_promise.promise_object())
}
pub fn register_js(module: &mut Module) -> Result<()> {
module.create_named_method("benchAsyncTask", bench_async_task)?;
Ok(())
}