1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-22 23:34:47 -05:00
denoland-deno/core/examples/eval_js_value.rs
Matt Mastracci 0b4770fa7d
perf(core) Reduce script name and script code copies (#18298)
Reduce the number of copies and allocations of script code by carrying
around ownership/reference information from creation time.

As an advantage, this allows us to maintain the identity of `&'static
str`-based scripts and use v8's external 1-byte strings (to avoid
incorrectly passing non-ASCII strings, debug `assert!`s gate all string
reference paths).

Benchmark results:

Perf improvements -- ~0.1 - 0.2ms faster, but should reduce garbage
w/external strings and reduces data copies overall. May also unlock some
more interesting optimizations in the future.

This requires adding some generics to functions, but manual
monomorphization has been applied (outer/inner function) to avoid code
bloat.
2023-03-21 22:33:12 +00:00

48 lines
1.4 KiB
Rust

// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
//! This example shows you how to evaluate JavaScript expression and deserialize
//! return value into a Rust object.
// NOTE:
// Here we are deserializing to `serde_json::Value` but you can
// deserialize to any other type that implementes the `Deserialize` trait.
use deno_core::v8;
use deno_core::JsRuntime;
use deno_core::RuntimeOptions;
fn main() {
let mut runtime = JsRuntime::new(RuntimeOptions::default());
// Evaluate some code
let code = "let a = 1+4; a*2";
let output: serde_json::Value =
eval(&mut runtime, code).expect("Eval failed");
println!("Output: {output:?}");
let expected_output = serde_json::json!(10);
assert_eq!(expected_output, output);
}
fn eval(
context: &mut JsRuntime,
code: &'static str,
) -> Result<serde_json::Value, String> {
let res = context.execute_script("<anon>", code);
match res {
Ok(global) => {
let scope = &mut context.handle_scope();
let local = v8::Local::new(scope, global);
// Deserialize a `v8` object into a Rust type using `serde_v8`,
// in this case deserialize to a JSON `Value`.
let deserialized_value =
serde_v8::from_v8::<serde_json::Value>(scope, local);
match deserialized_value {
Ok(value) => Ok(value),
Err(err) => Err(format!("Cannot deserialize value: {err:?}")),
}
}
Err(err) => Err(format!("Evaling error: {err:?}")),
}
}