Fix use of prehash so that the RAM cache actually hits

This commit is contained in:
mars 2022-12-05 21:26:05 -07:00
parent 03e596b219
commit 4b46142f90
1 changed files with 8 additions and 11 deletions

View File

@ -2,7 +2,7 @@
// SPDX-License-Identifier: LGPL-3.0-or-later
use std::collections::{hash_map::DefaultHasher, HashMap};
use std::hash::Hasher;
use std::hash::{Hasher, BuildHasherDefault};
use std::ops::DerefMut;
use std::time::Instant;
@ -11,12 +11,12 @@ use crate::DrawCommand;
use canary_script::{Color, CursorEventKind, Rect, Vec2};
use parking_lot::Mutex;
use prehash::{DefaultPrehasher, Prehashed, Prehasher};
use prehash::Passthru;
type Caller<'a> = wasmtime::Caller<'a, Arc<ScriptAbi>>;
type Store = wasmtime::Store<Arc<ScriptAbi>>;
type Linker = wasmtime::Linker<Arc<ScriptAbi>>;
type ModuleCache = Mutex<HashMap<Prehashed<u64>, wasmtime::Module, DefaultPrehasher>>;
type ModuleCache = Mutex<HashMap<u64, wasmtime::Module, BuildHasherDefault<Passthru>>>;
pub struct WasmtimeBackend {
engine: wasmtime::Engine,
@ -52,25 +52,22 @@ impl Backend for WasmtimeBackend {
let mut hasher = DefaultHasher::new();
hasher.write(module);
let hashed = hasher.finish();
let fmt_hash = format!("{:x}", hashed);
let hash = hasher.finish();
let fmt_hash = format!("{:x}", hash);
log::debug!("Loading module (hash: {})", fmt_hash);
let prehasher = DefaultPrehasher::new();
let prehashed = prehasher.prehash(hashed);
let mut cache = self.module_cache.lock();
let module = if let Some(module) = cache.get(&prehashed) {
let module = if let Some(module) = cache.get(&hash) {
log::debug!("Module load cache hit (hash: {})", fmt_hash);
module
} else {
log::debug!("Module load cache miss; building (hash: {})", fmt_hash);
let start = Instant::now();
let module = wasmtime::Module::new(&self.engine, module)?;
cache.insert(prehashed, module);
cache.insert(hash, module);
log::debug!("Built module in {:?} (hash: {})", start.elapsed(), fmt_hash);
cache.get(&prehashed).unwrap()
cache.get(&hash).unwrap()
};
let mut store = wasmtime::Store::new(&self.engine, abi);