lib.rs 1.4 KB

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