Miri doesn't complain when I use this code even if the HashMap gets reallocated, but there might be some caveat that I missed.
Is this safe ?
use std::collections::HashMap;
use std::sync::LazyLock;
use std::sync::Mutex;
static MAP: LazyLock<Mutex<HashMap<u64, Vec<u8>>>> = LazyLock::new(|| {
Mutex::new(HashMap::new())
});
pub fn insert(code: u64, bytes: Vec<u8>) -> bool {
let mut map = MAP.lock().unwrap();
if map.contains_key(&code) {
return false;
}
map.insert(code, bytes);
true
}
pub fn get(code: u64) -> Option<&'static [u8]> {
let map = MAP.lock().unwrap();
let val = map.get(&code)?.as_slice();
let val: &[u8] = val;
let val: &'static [u8] = unsafe {
// SAFETY: MAP is static and append-only,
// so this value lives until the end of the program.
&*(val as *const [u8])
};
Some(val)
}