use crate::AsContextMut;
use crate::component::func::{LiftContext, LowerContext};
use crate::component::matching::InstanceType;
use crate::component::resources::host::{HostResource, HostResourceType};
use crate::component::{ComponentType, Lift, Lower, ResourceAny, ResourceType};
use crate::prelude::*;
use core::fmt;
use core::mem::MaybeUninit;
use wasmtime_environ::component::{CanonicalAbiInfo, InterfaceType};
pub struct ResourceDynamic(HostResource<Dynamic, u32>);
struct Dynamic;
impl HostResourceType<u32> for Dynamic {
fn resource_type(ty: u32) -> ResourceType {
ResourceType::host_dynamic(ty)
}
fn typecheck(ty: ResourceType) -> Option<u32> {
ty.as_host_dynamic()
}
}
impl ResourceDynamic {
pub fn new_own(rep: u32, ty: u32) -> ResourceDynamic {
ResourceDynamic(HostResource::new_own(rep, ty))
}
pub fn new_borrow(rep: u32, ty: u32) -> ResourceDynamic {
ResourceDynamic(HostResource::new_borrow(rep, ty))
}
pub fn rep(&self) -> u32 {
self.0.rep()
}
pub fn ty(&self) -> u32 {
self.0.ty()
}
pub fn owned(&self) -> bool {
self.0.owned()
}
pub fn try_from_resource_any(resource: ResourceAny, store: impl AsContextMut) -> Result<Self> {
Ok(ResourceDynamic(resource.try_into_host_resource(store)?))
}
pub fn try_into_resource_any(self, store: impl AsContextMut) -> Result<ResourceAny> {
self.0.try_into_resource_any(store)
}
}
unsafe impl ComponentType for ResourceDynamic {
const ABI: CanonicalAbiInfo = HostResource::<Dynamic, u32>::ABI;
type Lower = crate::ValRaw;
fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
HostResource::<Dynamic, u32>::typecheck(ty, types)
}
}
unsafe impl Lower for ResourceDynamic {
fn linear_lower_to_flat<U>(
&self,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()> {
self.0.linear_lower_to_flat(cx, ty, dst)
}
fn linear_lower_to_memory<U>(
&self,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
offset: usize,
) -> Result<()> {
self.0.linear_lower_to_memory(cx, ty, offset)
}
}
unsafe impl Lift for ResourceDynamic {
fn linear_lift_from_flat(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
src: &Self::Lower,
) -> Result<Self> {
let host_resource = HostResource::linear_lift_from_flat(cx, ty, src)?;
Ok(ResourceDynamic(host_resource))
}
fn linear_lift_from_memory(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
bytes: &[u8],
) -> Result<Self> {
let host_resource = HostResource::linear_lift_from_memory(cx, ty, bytes)?;
Ok(ResourceDynamic(host_resource))
}
}
impl fmt::Debug for ResourceDynamic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}