Skip to content

Instantly share code, notes, and snippets.

@alshdavid
Created March 5, 2024 09:21
Show Gist options
  • Save alshdavid/c9e5bc0d794e3ec9dba6afaa689b704e to your computer and use it in GitHub Desktop.
Save alshdavid/c9e5bc0d794e3ec9dba6afaa689b704e to your computer and use it in GitHub Desktop.
Deno in rust
function echo(value) {
Deno.core.print("called with " + value)
}
Deno.core.ops.op_register_func(echo)
use std::{env, rc::Rc};
use deno_core::v8::Global;
use deno_core::{resolve_path, v8, serde_v8, Extension, FsModuleLoader, JsRuntime, Op, PollEventLoopOptions, RuntimeOptions};
use deno_core::op2;
#[derive(Default)]
pub struct FunctionsState {
pub echo_func: Option<v8::Global<v8::Function>>,
}
#[op2]
pub fn op_register_func(
#[state] function_state: &mut FunctionsState,
#[global] f: v8::Global<v8::Function>,
) {
function_state.echo_func.replace(f);
}
async fn main_async() {
let main_module = resolve_path(
"./index.js",
env::current_dir().unwrap().join("src").as_path()
).unwrap();
let ext = Extension {
name: "my_ext",
ops: std::borrow::Cow::Borrowed(&[op_register_func::DECL]),
op_state_fn: Some(Box::new(|state| {
state.put(FunctionsState::default());
})),
..Default::default()
};
let mut runtime = JsRuntime::new(RuntimeOptions {
module_loader: Some(Rc::new(FsModuleLoader)),
extensions: vec![ext],
..Default::default()
});
let mod_id = runtime.load_main_module(&main_module, None).await.unwrap();
let result = runtime.mod_evaluate(mod_id);
runtime.run_event_loop(PollEventLoopOptions::default()).await.unwrap();
result.await.unwrap();
let state: FunctionsState = runtime.op_state().borrow_mut().take();
let function = state.echo_func.unwrap();
let request = {
let mut scope = &mut runtime.handle_scope();
let request = serde_v8::to_v8(scope, "asdsd").unwrap();
Global::new(&mut scope, request)
};
let call = runtime.call_with_args(&function, &[request]);
runtime
.with_event_loop_promise(call, PollEventLoopOptions::default())
.await.unwrap();
}
fn main() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(main_async())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment