summaryrefslogtreecommitdiff
path: root/cli/napi/async.rs
blob: 8cbdb22204c866cb3be772e47a4dd9e90cd27ce0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.

use deno_runtime::deno_napi::*;

#[repr(C)]
pub struct AsyncWork {
  pub data: *mut c_void,
  pub execute: napi_async_execute_callback,
  pub complete: napi_async_complete_callback,
}

#[napi_sym::napi_sym]
fn napi_create_async_work(
  _env: *mut Env,
  _async_resource: napi_value,
  _async_resource_name: napi_value,
  execute: napi_async_execute_callback,
  complete: napi_async_complete_callback,
  data: *mut c_void,
  result: *mut napi_async_work,
) -> Result {
  let mut work = AsyncWork {
    data,
    execute,
    complete,
  };
  *result = transmute::<Box<AsyncWork>, _>(Box::new(work));
  Ok(())
}

#[napi_sym::napi_sym]
fn napi_cancel_async_work(
  _env: &mut Env,
  _async_work: napi_async_work,
) -> Result {
  Ok(())
}

/// Frees a previously allocated work object.
#[napi_sym::napi_sym]
fn napi_delete_async_work(_env: &mut Env, work: napi_async_work) -> Result {
  let work = Box::from_raw(work as *mut AsyncWork);
  drop(work);

  Ok(())
}

#[napi_sym::napi_sym]
fn napi_queue_async_work(env_ptr: *mut Env, work: napi_async_work) -> Result {
  let work: &AsyncWork = &*(work as *const AsyncWork);
  let env: &mut Env = env_ptr.as_mut().ok_or(Error::InvalidArg)?;

  let fut = Box::new(move || {
    (work.execute)(env_ptr as napi_env, work.data);
    // Note: Must be called from the loop thread.
    (work.complete)(env_ptr as napi_env, napi_ok, work.data);
  });
  env.add_async_work(fut);

  Ok(())
}

// TODO: Custom async operations.

#[napi_sym::napi_sym]
fn napi_async_init(
  _env: *mut Env,
  _async_resource: napi_value,
  _async_resource_name: napi_value,
  _result: *mut *mut (),
) -> Result {
  todo!()
}

#[napi_sym::napi_sym]
fn napi_async_destroy(_env: *mut Env, _async_context: *mut ()) -> Result {
  todo!()
}