lib.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #[macro_use]
  2. extern crate napi;
  3. #[macro_use]
  4. extern crate napi_derive;
  5. use std::convert::TryInto;
  6. use napi::{CallContext, Env, JsNumber, JsObject, Module, Result, Task};
  7. #[cfg(all(unix, not(target_env = "musl")))]
  8. #[global_allocator]
  9. static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
  10. #[cfg(windows)]
  11. #[global_allocator]
  12. static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
  13. register_module!(example, init);
  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: &mut Env, output: Self::Output) -> Result<Self::JsValue> {
  25. env.create_uint32(output)
  26. }
  27. }
  28. fn init(module: &mut Module) -> Result<()> {
  29. module.create_named_method("sync", sync_fn)?;
  30. module.create_named_method("sleep", sleep)?;
  31. Ok(())
  32. }
  33. #[js_function(1)]
  34. fn sync_fn(ctx: CallContext) -> Result<JsNumber> {
  35. let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
  36. ctx.env.create_uint32(argument + 100)
  37. }
  38. #[js_function(1)]
  39. fn sleep(ctx: CallContext) -> Result<JsObject> {
  40. let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
  41. let task = AsyncTask(argument);
  42. ctx.env.spawn(task)
  43. }