2020-09-28 01:27:37 +09:00
|
|
|
use napi::{
|
|
|
|
CallContext, Env, JsBuffer, JsBufferValue, JsNumber, JsObject, Module, Ref, Result, Task,
|
|
|
|
};
|
2020-09-30 15:34:26 +09:00
|
|
|
|
|
|
|
#[repr(transparent)]
|
2020-09-28 01:27:37 +09:00
|
|
|
struct BufferLength(Ref<JsBufferValue>);
|
2020-09-30 15:34:26 +09:00
|
|
|
|
|
|
|
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-30 15:34:26 +09:00
|
|
|
}
|
|
|
|
|
2020-09-28 01:27:37 +09:00
|
|
|
fn resolve(self, env: Env, output: Self::Output) -> Result<Self::JsValue> {
|
|
|
|
self.0.unref(env)?;
|
2020-09-30 15:34:26 +09:00
|
|
|
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()?);
|
2020-09-30 15:34:26 +09:00
|
|
|
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(())
|
|
|
|
}
|