lib.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. register_module!(example, init);
  11. struct AsyncTask(u32);
  12. impl Task for AsyncTask {
  13. type Output = u32;
  14. type JsValue = JsNumber;
  15. fn compute(&mut self) -> Result<Self::Output> {
  16. use std::thread::sleep;
  17. use std::time::Duration;
  18. sleep(Duration::from_millis(self.0 as u64));
  19. Ok(self.0 * 2)
  20. }
  21. fn resolve(&self, env: &mut Env, output: Self::Output) -> Result<Self::JsValue> {
  22. env.create_uint32(output)
  23. }
  24. }
  25. fn init(module: &mut Module) -> Result<()> {
  26. module.create_named_method("sync", sync_fn)?;
  27. module.create_named_method("sleep", sleep)?;
  28. Ok(())
  29. }
  30. #[js_function(1)]
  31. fn sync_fn(ctx: CallContext) -> Result<JsNumber> {
  32. let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
  33. ctx.env.create_uint32(argument + 100)
  34. }
  35. #[js_function(1)]
  36. fn sleep(ctx: CallContext) -> Result<JsObject> {
  37. let argument: u32 = ctx.get::<JsNumber>(0)?.try_into()?;
  38. let task = AsyncTask(argument);
  39. ctx.env.spawn(task)
  40. }