use crate::vmcontext::VMCallerCheckedAnyfunc;
use std::collections::HashMap;
use std::sync::Mutex;
#[derive(Debug)]
pub struct FuncDataRegistry {
inner: Mutex<Inner>,
}
unsafe impl Send for FuncDataRegistry {}
unsafe impl Sync for FuncDataRegistry {}
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct VMFuncRef(pub(crate) *const VMCallerCheckedAnyfunc);
impl unc_vm_types::NativeWasmType for VMFuncRef {
const WASM_TYPE: unc_vm_types::Type = unc_vm_types::Type::FuncRef;
type Abi = Self;
#[inline]
fn from_abi(abi: Self::Abi) -> Self {
abi
}
#[inline]
fn into_abi(self) -> Self::Abi {
self
}
#[inline]
fn to_binary(self) -> i128 {
self.0 as _
}
#[inline]
fn from_binary(bits: i128) -> Self {
Self(bits as _)
}
}
impl VMFuncRef {
pub fn is_null(&self) -> bool {
self.0.is_null()
}
pub const fn null() -> Self {
Self(std::ptr::null())
}
}
impl std::ops::Deref for VMFuncRef {
type Target = *const VMCallerCheckedAnyfunc;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for VMFuncRef {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
unsafe impl Send for VMFuncRef {}
unsafe impl Sync for VMFuncRef {}
#[derive(Debug, Default)]
struct Inner {
func_data: Vec<VMCallerCheckedAnyfunc>,
anyfunc_to_index: HashMap<VMCallerCheckedAnyfunc, usize>,
}
impl FuncDataRegistry {
pub fn new() -> Self {
Self { inner: Default::default() }
}
pub fn register(&self, anyfunc: VMCallerCheckedAnyfunc) -> VMFuncRef {
let mut inner = self.inner.lock().unwrap();
let data = if let Some(&idx) = inner.anyfunc_to_index.get(&anyfunc) {
&inner.func_data[idx]
} else {
let idx = inner.func_data.len();
inner.func_data.push(anyfunc);
inner.anyfunc_to_index.insert(anyfunc, idx);
&inner.func_data[idx]
};
VMFuncRef(data)
}
}