generated from napi-rs/package-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
58 lines (45 loc) · 1.29 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#![deny(clippy::all)]
#[macro_use]
extern crate napi_derive;
use std::convert::TryInto;
use napi::{CallContext, Env, JsNumber, JsObject, Result, Task};
#[cfg(all(
any(windows, unix),
target_arch = "x86_64",
not(target_env = "musl"),
not(debug_assertions)
))]
#[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
struct AsyncTask(u32);
impl Task for AsyncTask {
type Output = u32;
type JsValue = JsNumber;
fn compute(&mut self) -> Result<Self::Output> {
use std::thread::sleep;
use std::time::Duration;
sleep(Duration::from_millis(self.0 as u64));
Ok(self.0 * 2)
}
fn resolve(self, env: Env, output: Self::Output) -> Result<Self::JsValue> {
env.create_uint32(output)
}
}
#[module_exports]
fn init(mut exports: JsObject) -> Result<()> {
exports.create_named_method("sync", sync_fn)?;
exports.create_named_method("sleep", sleep)?;
Ok(())
}
#[js_function(1)]
fn sync_fn(ctx: CallContext) -> Result<JsNumber> {
let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
ctx.env.create_uint32(argument + 100)
}
#[js_function(1)]
fn sleep(ctx: CallContext) -> Result<JsObject> {
let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
let task = AsyncTask(argument);
let async_task = ctx.env.spawn(task)?;
Ok(async_task.promise_object())
}