#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RealmScope<R> {
realm: R,
generation: u64,
}
impl<R> RealmScope<R> {
pub const fn new(realm: R, generation: u64) -> Self {
Self { realm, generation }
}
pub const fn realm(&self) -> &R {
&self.realm
}
pub const fn generation(&self) -> u64 {
self.generation
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RetainedCallback<R, C> {
realm: R,
generation: u64,
callback: C,
}
impl<R, C> RetainedCallback<R, C> {
pub const fn new(realm: R, generation: u64, callback: C) -> Self {
Self {
realm,
generation,
callback,
}
}
pub const fn realm(&self) -> &R {
&self.realm
}
pub const fn generation(&self) -> u64 {
self.generation
}
pub const fn callback(&self) -> &C {
&self.callback
}
pub fn is_current_in(&self, scope: &RealmScope<R>) -> bool
where
R: PartialEq,
{
self.realm == scope.realm && self.generation == scope.generation
}
}
pub trait NativeGuest {
type Value;
type RealmId: Clone + PartialEq;
type CallbackId: Clone;
type Error;
fn scope(&self) -> RealmScope<Self::RealmId>;
fn retain_callback(
&mut self,
callback: &Self::Value,
) -> Result<RetainedCallback<Self::RealmId, Self::CallbackId>, Self::Error>;
fn release_callback(
&mut self,
callback: &RetainedCallback<Self::RealmId, Self::CallbackId>,
) -> Result<(), Self::Error>;
fn register_intrinsic(
&mut self,
name: &'static str,
arity: u8,
callback: NativeIntrinsic<Self>,
) -> Result<(), Self::Error>
where
Self: Sized;
fn invoke_retained_callback(
&mut self,
callback: &RetainedCallback<Self::RealmId, Self::CallbackId>,
arguments: &[Self::Value],
) -> Result<Self::Value, Self::Error>;
}
pub type NativeIntrinsic<G> = fn(
&mut G,
&[<G as NativeGuest>::Value],
) -> Result<<G as NativeGuest>::Value, <G as NativeGuest>::Error>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NativeCallbackError<E> {
StaleCallback,
Guest(E),
}
pub trait NativeHost {
type Guest: NativeGuest;
fn guest(&self) -> &Self::Guest;
fn guest_mut(&mut self) -> &mut Self::Guest;
fn invoke_retained_callback(
&mut self,
callback: &RetainedCallback<
<Self::Guest as NativeGuest>::RealmId,
<Self::Guest as NativeGuest>::CallbackId,
>,
arguments: &[<Self::Guest as NativeGuest>::Value],
) -> Result<
<Self::Guest as NativeGuest>::Value,
NativeCallbackError<<Self::Guest as NativeGuest>::Error>,
> {
let guest = self.guest_mut();
if !callback.is_current_in(&guest.scope()) {
return Err(NativeCallbackError::StaleCallback);
}
guest
.invoke_retained_callback(callback, arguments)
.map_err(NativeCallbackError::Guest)
}
}