use anyhow::{Result, anyhow};
use rhai::AST;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock, RwLock};
const DEFAULT_CAPACITY: usize = 512;
fn content_key(code: &str) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
code.hash(&mut hasher);
hasher.finish()
}
struct CompiledCache {
entries: HashMap<u64, (String, Arc<AST>)>,
capacity: usize,
}
impl CompiledCache {
fn new(capacity: usize) -> Self {
Self {
entries: HashMap::new(),
capacity,
}
}
fn get_verified(&self, key: u64, code: &str) -> Option<Arc<AST>> {
self.entries
.get(&key)
.and_then(|(source, ast)| (source == code).then(|| Arc::clone(ast)))
}
fn get_or_compile(&mut self, key: u64, code: &str) -> Result<Arc<AST>> {
if let Some(ast) = self.get_verified(key, code) {
return Ok(ast);
}
let engine = crate::scripting::rift_rhai_engine();
let ast = Arc::new(
engine
.compile(code)
.map_err(|e| anyhow!("Failed to compile script: {e}"))?,
);
if !self.entries.contains_key(&key) && self.entries.len() >= self.capacity {
self.entries.clear();
}
self.entries
.insert(key, (code.to_string(), Arc::clone(&ast)));
Ok(ast)
}
}
fn rhai_cache() -> &'static RwLock<CompiledCache> {
static CACHE: OnceLock<RwLock<CompiledCache>> = OnceLock::new();
CACHE.get_or_init(|| RwLock::new(CompiledCache::new(DEFAULT_CAPACITY)))
}
pub(crate) fn cached_rhai_ast(code: &str) -> Result<Arc<AST>> {
let key = content_key(code);
{
let cache = rhai_cache()
.read()
.map_err(|_| anyhow!("rhai script cache lock poisoned"))?;
if let Some(ast) = cache.get_verified(key, code) {
return Ok(ast);
}
}
let mut cache = rhai_cache()
.write()
.map_err(|_| anyhow!("rhai script cache lock poisoned"))?;
cache.get_or_compile(key, code)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identical_content_shares_one_compiled_entry() {
let code = "fn respond(ctx) { pass() }";
let a = cached_rhai_ast(code).unwrap();
let b = cached_rhai_ast(code).unwrap();
assert!(
Arc::ptr_eq(&a, &b),
"byte-identical content must return the same cached AST"
);
}
#[test]
fn different_content_compiles_a_distinct_entry() {
let a = cached_rhai_ast("fn respond(ctx) { pass() }").unwrap();
let b = cached_rhai_ast("fn respond(ctx) { delay(1) }").unwrap();
assert!(
!Arc::ptr_eq(&a, &b),
"different content must not share a cache entry"
);
}
#[test]
fn editing_content_busts_the_cache_key() {
let original = cached_rhai_ast("fn respond(ctx) { pass() }").unwrap();
let edited = cached_rhai_ast("fn respond(ctx) { delay(2) }").unwrap();
assert!(!Arc::ptr_eq(&original, &edited));
}
#[test]
fn cache_does_not_grow_past_capacity() {
let cap = 8;
let mut cache = CompiledCache::new(cap);
for i in 0..(cap * 4) {
let code = format!("fn respond(ctx) {{ pass(); {i} }}");
let key = content_key(&code);
cache.get_or_compile(key, &code).unwrap();
assert!(
cache.entries.len() <= cap,
"cache size {} exceeded cap {cap} after {} inserts",
cache.entries.len(),
i + 1
);
}
}
#[test]
fn collision_guard_never_returns_wrong_ast() {
let mut cache = CompiledCache::new(16);
let src_a = "fn respond(ctx) { pass(); 1 }";
let src_b = "fn respond(ctx) { pass(); 2 }";
let forced_key = 0xC0FFEE_u64;
let a = cache.get_or_compile(forced_key, src_a).unwrap();
let b = cache.get_or_compile(forced_key, src_b).unwrap();
assert!(
!Arc::ptr_eq(&a, &b),
"collision must not return A's AST for B"
);
assert!(cache.get_verified(forced_key, src_b).is_some());
assert!(
cache.get_verified(forced_key, src_a).is_none(),
"a source that doesn't match the stored entry is a miss, not a wrong-AST hit"
);
}
}