use super::super::{AsContext, AsContextMut, StoreContext, StoreContextMut};
use crate::{Engine, Error, Extern, engine::Inst};
pub struct Caller<'a, T> {
ctx: StoreContextMut<'a, T>,
instance: Option<Inst>,
}
impl<'a, T> Caller<'a, T> {
pub(crate) fn new<C>(ctx: &'a mut C, instance: Option<Inst>) -> Self
where
C: AsContextMut<Data = T>,
{
Self {
ctx: ctx.as_context_mut(),
instance,
}
}
pub fn get_export(&self, name: &str) -> Option<Extern> {
let Some(instance) = &self.instance else {
return None;
};
let instance = unsafe { instance.as_ref() };
instance.get_export(name)
}
pub fn data(&self) -> &T {
self.ctx.store.data()
}
pub fn data_mut(&mut self) -> &mut T {
self.ctx.store.data_mut()
}
pub fn engine(&self) -> &Engine {
self.ctx.store.engine()
}
pub fn get_fuel(&self) -> Result<u64, Error> {
self.ctx.store.get_fuel()
}
pub fn set_fuel(&mut self, fuel: u64) -> Result<(), Error> {
self.ctx.store.set_fuel(fuel)
}
}
impl<T> AsContext for Caller<'_, T> {
type Data = T;
#[inline]
fn as_context(&self) -> StoreContext<'_, Self::Data> {
self.ctx.as_context()
}
}
impl<T> AsContextMut for Caller<'_, T> {
#[inline]
fn as_context_mut(&mut self) -> StoreContextMut<'_, Self::Data> {
self.ctx.as_context_mut()
}
}
impl<'a, T: AsContextMut> From<&'a mut T> for Caller<'a, T::Data> {
#[inline]
fn from(ctx: &'a mut T) -> Self {
Self {
ctx: ctx.as_context_mut(),
instance: None,
}
}
}