Created
May 18, 2021 09:43
-
-
Save mizchi/0a33f6a8cf419933a7ade99c35168d8c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rusty_v8 as v8; | |
use std::mem::forget; | |
fn main() { | |
let platform = v8::new_default_platform().unwrap(); | |
v8::V8::initialize_platform(platform); | |
v8::V8::initialize(); | |
let snapshot; | |
// --- create snapshot --- | |
{ | |
let mut creator = v8::SnapshotCreator::new(None); | |
let mut isolate = unsafe { creator.get_owned_isolate() }; | |
{ | |
let scope = &mut v8::HandleScope::new(&mut isolate); | |
let context = v8::Context::new(scope); | |
let src = r#" | |
function add1(n) { return n + 1; } | |
x = 1; | |
y = 2; | |
add1(x + y); | |
"#; | |
{ | |
let scope = &mut v8::ContextScope::new(scope, context); | |
let code = v8::String::new(scope, src).unwrap(); | |
let script = v8::Script::compile(scope, code, None).unwrap(); | |
let result = script.run(scope).unwrap(); | |
assert_eq!(result.to_rust_string_lossy(scope), "4"); | |
} | |
creator.set_default_context(context); | |
} | |
snapshot = creator.create_blob(v8::FunctionCodeHandling::Keep).unwrap(); | |
let snapshot_slice: &[u8] = &*snapshot; | |
println!("Snapshot size: {} kb", snapshot_slice.len() / 1024); | |
forget(isolate); | |
} | |
// --- restore snapshot --- | |
{ | |
let mut isolate = v8::Isolate::new(v8::Isolate::create_params().snapshot_blob(snapshot)); | |
let scope = &mut v8::HandleScope::new(&mut isolate); | |
let context = v8::Context::new(scope); | |
{ | |
let scope = &mut v8::ContextScope::new(scope, context); | |
let code = v8::String::new(scope, "add1(x + y)").unwrap(); | |
let script = v8::Script::compile(scope, code, None).unwrap(); | |
let result = script.run(scope).unwrap(); | |
assert_eq!(result.to_rust_string_lossy(scope), "4"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment