Skip to content

Instantly share code, notes, and snippets.

@andelf
Created May 14, 2020 10:31
Show Gist options
  • Save andelf/61574d03353998a7b16a358a6fd5a097 to your computer and use it in GitHub Desktop.
Save andelf/61574d03353998a7b16a358a6fd5a097 to your computer and use it in GitHub Desktop.
Embed Deno in Rust
use deno_core::Op;
use deno_core::ZeroCopyBuf;
use deno_core::{CoreIsolate, StartupData};
use std::str;
fn main() {
println!("v8 version: {}", deno_core::v8_version());
let mut isolate = CoreIsolate::new(StartupData::None, false);
isolate.register_op(
"op_rust_hello",
|_isolate: &mut CoreIsolate, control: &[u8], zero_copy_buf: Option<ZeroCopyBuf>| -> Op {
assert!(zero_copy_buf.is_none());
println!("DEBUG: => {:?}", str::from_utf8(control));
let ret = b"hello".to_vec();
Op::Sync(ret.into_boxed_slice())
},
);
let source = r#"
const opName = "op_rust_hello";
const ops = Deno.core.ops();
const opId = ops[opName];
if (!opId) {
throw new Error(`Unknown op: ${opName}`);
}
function encode(str) {
const charCodes = str.split("").map((c) => c.charCodeAt(0));
const ui8 = new Uint8Array(charCodes);
return ui8;
}
function decodeAscii(ui8) {
let out = "";
if (!ui8) {
return out;
}
for (let i = 0; i < ui8.length; i++) {
out += String.fromCharCode(ui8[i]);
}
return out;
}
const msg = encode("calling a rust function from deno");
const resUi8 = Deno.core.dispatch(opId, msg);
console.log(resUi8);
throw new Error(`result: ${decodeAscii(resUi8)}`);
"#;
let ret = isolate.execute("<anon>", source);
println!("ret => {:?}", ret);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment