napi/
task.rs

1use crate::{
2  bindgen_runtime::{ToNapiValue, TypeName},
3  Env, Error, Result,
4};
5
6pub trait Task: Send + Sized {
7  type Output: Send + Sized + 'static;
8  type JsValue: ToNapiValue + TypeName;
9
10  /// Compute logic in libuv thread
11  fn compute(&mut self) -> Result<Self::Output>;
12
13  /// Into this method if `compute` return `Ok`
14  fn resolve(&mut self, env: Env, output: Self::Output) -> Result<Self::JsValue>;
15
16  #[allow(unused_variables)]
17  /// Into this method if `compute` return `Err`
18  fn reject(&mut self, env: Env, err: Error) -> Result<Self::JsValue> {
19    Err(err)
20  }
21
22  #[allow(unused_variables)]
23  /// after resolve or reject
24  fn finally(self, env: Env) -> Result<()> {
25    Ok(())
26  }
27}
28
29impl<'a, T: Task> ScopedTask<'a> for T {
30  type Output = T::Output;
31  type JsValue = T::JsValue;
32
33  fn compute(&mut self) -> Result<Self::Output> {
34    T::compute(self)
35  }
36
37  fn resolve(&mut self, env: &'a Env, output: Self::Output) -> Result<Self::JsValue> {
38    T::resolve(self, Env::from_raw(env.raw()), output)
39  }
40
41  fn reject(&mut self, env: &'a Env, err: Error) -> Result<Self::JsValue> {
42    T::reject(self, Env::from_raw(env.raw()), err)
43  }
44
45  fn finally(self, env: Env) -> Result<()> {
46    T::finally(self, env)
47  }
48}
49
50/// Basically it's the same as the `Task` trait
51///
52/// The difference is it can be resolve or reject a `JsValue` with lifetime
53pub trait ScopedTask<'task>: Send + Sized {
54  type Output: Send + Sized + 'static;
55  type JsValue: ToNapiValue + TypeName;
56
57  /// Compute logic in libuv thread
58  fn compute(&mut self) -> Result<Self::Output>;
59
60  /// Into this method if `compute` return `Ok`
61  fn resolve(&mut self, env: &'task Env, output: Self::Output) -> Result<Self::JsValue>;
62
63  #[allow(unused_variables)]
64  /// Into this method if `compute` return `Err`
65  fn reject(&mut self, env: &'task Env, err: Error) -> Result<Self::JsValue> {
66    Err(err)
67  }
68
69  #[allow(unused_variables)]
70  /// after resolve or reject
71  fn finally(self, env: Env) -> Result<()> {
72    Ok(())
73  }
74}