lib.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #![deny(clippy::all)]
  2. #[macro_use]
  3. extern crate napi_derive;
  4. use std::convert::TryInto;
  5. use napi::{CallContext, Env, JsNumber, JsObject, Result, Task};
  6. #[cfg(all(
  7. any(windows, unix),
  8. target_arch = "x86_64",
  9. not(target_env = "musl"),
  10. not(debug_assertions)
  11. ))]
  12. #[global_allocator]
  13. static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
  14. struct AsyncTask(u32);
  15. impl Task for AsyncTask {
  16. type Output = u32;
  17. type JsValue = JsNumber;
  18. fn compute(&mut self) -> Result<Self::Output> {
  19. use std::thread::sleep;
  20. use std::time::Duration;
  21. sleep(Duration::from_millis(self.0 as u64));
  22. Ok(self.0 * 2)
  23. }
  24. fn resolve(self, env: Env, output: Self::Output) -> Result<Self::JsValue> {
  25. env.create_uint32(output)
  26. }
  27. }
  28. #[module_exports]
  29. fn init(mut exports: JsObject) -> Result<()> {
  30. exports.create_named_method("sync", sync_fn)?;
  31. exports.create_named_method("sleep", sleep)?;
  32. Ok(())
  33. }
  34. #[js_function(1)]
  35. fn sync_fn(ctx: CallContext) -> Result<JsNumber> {
  36. let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
  37. ctx.env.create_uint32(argument + 100)
  38. }
  39. #[js_function(1)]
  40. fn sleep(ctx: CallContext) -> Result<JsObject> {
  41. let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
  42. let task = AsyncTask(argument);
  43. let async_task = ctx.env.spawn(task)?;
  44. Ok(async_task.promise_object())
  45. }