use crate::{Engine, Error, Store};
pub trait AsContext {
type Data;
fn as_context(&self) -> StoreContext<'_, Self::Data>;
}
pub trait AsContextMut: AsContext {
fn as_context_mut(&mut self) -> StoreContextMut<'_, Self::Data>;
}
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct StoreContext<'a, T> {
pub(crate) store: &'a Store<T>,
}
impl<T> StoreContext<'_, T> {
pub fn engine(&self) -> &Engine {
self.store.engine()
}
pub fn data(&self) -> &T {
self.store.data()
}
pub fn get_fuel(&self) -> Result<u64, Error> {
self.store.get_fuel()
}
}
impl<'a, T: AsContext> From<&'a T> for StoreContext<'a, T::Data> {
#[inline]
fn from(ctx: &'a T) -> Self {
ctx.as_context()
}
}
impl<'a, T: AsContext> From<&'a mut T> for StoreContext<'a, T::Data> {
#[inline]
fn from(ctx: &'a mut T) -> Self {
T::as_context(ctx)
}
}
impl<'a, T: AsContextMut> From<&'a mut T> for StoreContextMut<'a, T::Data> {
#[inline]
fn from(ctx: &'a mut T) -> Self {
ctx.as_context_mut()
}
}
#[derive(Debug)]
#[repr(transparent)]
pub struct StoreContextMut<'a, T> {
pub(crate) store: &'a mut Store<T>,
}
impl<T> StoreContextMut<'_, T> {
pub fn engine(&self) -> &Engine {
self.store.engine()
}
pub fn data(&self) -> &T {
self.store.data()
}
pub fn data_mut(&mut self) -> &mut T {
self.store.data_mut()
}
pub fn get_fuel(&self) -> Result<u64, Error> {
self.store.get_fuel()
}
pub fn set_fuel(&mut self, fuel: u64) -> Result<(), Error> {
self.store.set_fuel(fuel)
}
}
impl<T> AsContext for &'_ T
where
T: AsContext,
{
type Data = T::Data;
#[inline]
fn as_context(&self) -> StoreContext<'_, T::Data> {
T::as_context(*self)
}
}
impl<T> AsContext for &'_ mut T
where
T: AsContext,
{
type Data = T::Data;
#[inline]
fn as_context(&self) -> StoreContext<'_, T::Data> {
T::as_context(*self)
}
}
impl<T> AsContextMut for &'_ mut T
where
T: AsContextMut,
{
#[inline]
fn as_context_mut(&mut self) -> StoreContextMut<'_, T::Data> {
T::as_context_mut(*self)
}
}
impl<T> AsContext for StoreContext<'_, T> {
type Data = T;
#[inline]
fn as_context(&self) -> StoreContext<'_, Self::Data> {
StoreContext { store: self.store }
}
}
impl<T> AsContext for StoreContextMut<'_, T> {
type Data = T;
#[inline]
fn as_context(&self) -> StoreContext<'_, Self::Data> {
StoreContext { store: self.store }
}
}
impl<T> AsContextMut for StoreContextMut<'_, T> {
#[inline]
fn as_context_mut(&mut self) -> StoreContextMut<'_, Self::Data> {
StoreContextMut {
store: &mut *self.store,
}
}
}
impl<T> AsContext for Store<T> {
type Data = T;
#[inline]
fn as_context(&self) -> StoreContext<'_, Self::Data> {
StoreContext { store: self }
}
}
impl<T> AsContextMut for Store<T> {
#[inline]
fn as_context_mut(&mut self) -> StoreContextMut<'_, Self::Data> {
StoreContextMut { store: self }
}
}