-
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathmod.rs
More file actions
85 lines (73 loc) · 2.43 KB
/
Copy pathmod.rs
File metadata and controls
85 lines (73 loc) · 2.43 KB
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
79
80
81
82
83
84
85
use std::collections::HashMap;
use deno_core::{extension, op2, serde_json, v8, Extension, OpState};
use super::ExtensionTrait;
use crate::{error::Error, RsAsyncFunction, RsFunction};
type FnCache = HashMap<String, Box<dyn RsFunction>>;
type AsyncFnCache = HashMap<String, Box<dyn RsAsyncFunction>>;
mod callbacks;
/// Registers a JS function with the runtime as being the entrypoint for the module
///
/// # Arguments
/// * `state` - The runtime's state, into which the function will be put
/// * `callback` - The function to register
#[op2(fast)]
fn op_register_entrypoint<'s>(
scope: &mut v8::PinScope<'s, '_>,
state: &mut OpState,
callback: v8::Local<'s, v8::Function>,
) {
state.put(v8::Global::new(scope, callback));
}
#[op2]
#[serde]
#[allow(clippy::needless_pass_by_value)]
fn call_registered_function(
#[string] name: &str,
#[serde] args: Vec<serde_json::Value>,
state: &mut OpState,
) -> Result<serde_json::Value, Error> {
if state.has::<FnCache>() {
let table = state.borrow_mut::<FnCache>();
if let Some(callback) = table.get(name) {
return callback(&args);
}
}
Err(Error::ValueNotCallable(name.to_string()))
}
#[op2]
#[serde]
fn call_registered_function_async(
#[string] name: String,
#[serde] args: Vec<serde_json::Value>,
state: &mut OpState,
) -> impl std::future::Future<Output = Result<serde_json::Value, Error>> {
if state.has::<AsyncFnCache>() {
let table = state.borrow_mut::<AsyncFnCache>();
if let Some(callback) = table.get(&name) {
return callback(args);
}
}
Box::pin(std::future::ready(Err(Error::ValueNotCallable(name))))
}
#[op2(fast)]
fn op_panic2(#[string] msg: &str) -> Result<(), Error> {
Err(Error::Runtime(msg.to_string()))
}
extension!(
rustyscript,
ops = [op_register_entrypoint, call_registered_function, call_registered_function_async],
esm_entry_point = "ext:rustyscript/rustyscript.js",
esm = [ dir "src/ext/rustyscript", "rustyscript.js" ],
middleware = |op| match op.name {
"op_panic" => op.with_implementation_from(&op_panic2()),
_ => op,
}
);
impl ExtensionTrait<()> for rustyscript {
fn init(options: ()) -> Extension {
rustyscript::init()
}
}
pub fn extensions(is_snapshot: bool) -> Vec<Extension> {
vec![rustyscript::build((), is_snapshot)]
}