|
|
|
@ -1,4 +1,10 @@
|
|
|
|
|
use std::ops::DerefMut;
|
|
|
|
|
use std::collections::hash_map::RandomState;
|
|
|
|
|
use std::hash::{Hash, BuildHasher};
|
|
|
|
|
use std::{ops::DerefMut, collections::hash_map};
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
|
|
|
|
|
use std::collections::hash_map::DefaultHasher;
|
|
|
|
|
use std::hash::Hasher;
|
|
|
|
|
|
|
|
|
|
use super::{Arc, Backend, Instance, PanelId};
|
|
|
|
|
use crate::{DrawCommand, ScriptAbi, ScriptAbiImpl};
|
|
|
|
@ -9,31 +15,54 @@ use parking_lot::Mutex;
|
|
|
|
|
type Caller<'a> = wasmtime::Caller<'a, ScriptAbiImpl>;
|
|
|
|
|
type Store = wasmtime::Store<ScriptAbiImpl>;
|
|
|
|
|
type Linker = wasmtime::Linker<ScriptAbiImpl>;
|
|
|
|
|
type ModuleCache = Mutex<HashMap<Prehashed<u64>, wasmtime::Module, DefaultPrehasher>>;
|
|
|
|
|
|
|
|
|
|
use prehash::{new_prehashed_set, DefaultPrehasher, Prehasher, Prehashed};
|
|
|
|
|
use wasmtime::Module;
|
|
|
|
|
|
|
|
|
|
pub struct WasmtimeBackend {
|
|
|
|
|
engine: wasmtime::Engine,
|
|
|
|
|
module_cache: ModuleCache,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl WasmtimeBackend {
|
|
|
|
|
pub fn new() -> anyhow::Result<Self> {
|
|
|
|
|
let mut config = wasmtime::Config::new();
|
|
|
|
|
config.wasm_simd(true);
|
|
|
|
|
config.wasm_bulk_memory(true);
|
|
|
|
|
config.cranelift_opt_level(wasmtime::OptLevel::Speed);
|
|
|
|
|
config.cache_config_load_default()?;
|
|
|
|
|
|
|
|
|
|
let engine = wasmtime::Engine::new(&config)?;
|
|
|
|
|
|
|
|
|
|
Ok(Self { engine })
|
|
|
|
|
let module_cache = Default::default();
|
|
|
|
|
Ok(Self { engine, module_cache })
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Backend for WasmtimeBackend {
|
|
|
|
|
fn load_module(&self, module: &[u8]) -> anyhow::Result<Arc<dyn Instance>> {
|
|
|
|
|
let module = wasmtime::Module::new(&self.engine, module)?;
|
|
|
|
|
|
|
|
|
|
let mut hasher = DefaultHasher::new();
|
|
|
|
|
hasher.write(module);
|
|
|
|
|
let hashed = hasher.finish();
|
|
|
|
|
|
|
|
|
|
let prehasher = DefaultPrehasher::new();
|
|
|
|
|
let prehashed = prehasher.prehash(hashed);
|
|
|
|
|
let mut cache = self.module_cache.lock();
|
|
|
|
|
|
|
|
|
|
let gotten = if let Some(module) = cache.get(&prehashed){
|
|
|
|
|
module
|
|
|
|
|
} else {
|
|
|
|
|
let module = wasmtime::Module::new(&self.engine, module)?;
|
|
|
|
|
cache.insert(prehashed, module);
|
|
|
|
|
cache.get(&prehashed).unwrap()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let abi = ScriptAbiImpl::default();
|
|
|
|
|
let mut store = wasmtime::Store::new(&self.engine, abi);
|
|
|
|
|
let mut linker = Linker::new(&self.engine);
|
|
|
|
|
WasmtimeInstance::link(&mut linker)?;
|
|
|
|
|
let instance = linker.instantiate(&mut store, &module)?;
|
|
|
|
|
let instance = linker.instantiate(&mut store, gotten)?;
|
|
|
|
|
let bind_panel = instance.get_typed_func(&mut store, "bind_panel")?;
|
|
|
|
|
let update = instance.get_typed_func(&mut store, "update")?;
|
|
|
|
|
let draw = instance.get_typed_func(&mut store, "draw")?;
|
|
|
|
|