Clean up wasmtime caching code

This commit is contained in:
mars 2022-11-25 17:52:24 -07:00
parent 57c6275958
commit d43a62dfda
1 changed files with 11 additions and 15 deletions

View File

@ -1,25 +1,19 @@
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::collections::{hash_map::DefaultHasher, HashMap};
use std::hash::Hasher;
use std::ops::DerefMut;
use super::{Arc, Backend, Instance, PanelId};
use crate::{DrawCommand, ScriptAbi, ScriptAbiImpl};
use canary_script::{Color, CursorEventKind, Rect, Vec2};
use parking_lot::Mutex;
use prehash::{DefaultPrehasher, Prehashed, Prehasher};
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,
@ -35,34 +29,36 @@ impl WasmtimeBackend {
let engine = wasmtime::Engine::new(&config)?;
let module_cache = Default::default();
Ok(Self { engine, module_cache })
Ok(Self {
engine,
module_cache,
})
}
}
impl Backend for WasmtimeBackend {
fn load_module(&self, module: &[u8]) -> anyhow::Result<Arc<dyn Instance>> {
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 mut cache = self.module_cache.lock();
let gotten = if let Some(module) = cache.get(&prehashed){
let module = 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, gotten)?;
let instance = linker.instantiate(&mut store, module)?;
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")?;