use crate::{
StorageType, Val,
prelude::*,
runtime::vm::{GcHeap, GcStore, VMGcRef},
store::AutoAssertNoGc,
};
use core::fmt;
use wasmtime_environ::{GcStructLayout, VMGcKind};
#[derive(Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct VMStructRef(VMGcRef);
impl fmt::Pointer for VMStructRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Pointer::fmt(&self.0, f)
}
}
impl From<VMStructRef> for VMGcRef {
#[inline]
fn from(x: VMStructRef) -> Self {
x.0
}
}
impl VMGcRef {
pub fn is_structref(&self, gc_heap: &(impl GcHeap + ?Sized)) -> bool {
if self.is_i31() {
return false;
}
match gc_heap.header(&self) {
Ok(header) => header.kind().matches(VMGcKind::StructRef),
Err(_) => false,
}
}
pub fn into_structref(self, gc_heap: &impl GcHeap) -> Result<VMStructRef, VMGcRef> {
if self.is_structref(gc_heap) {
Ok(self.into_structref_unchecked())
} else {
Err(self)
}
}
#[inline]
pub fn into_structref_unchecked(self) -> VMStructRef {
debug_assert!(!self.is_i31());
VMStructRef(self)
}
pub fn as_structref(&self, gc_heap: &(impl GcHeap + ?Sized)) -> Option<&VMStructRef> {
if self.is_structref(gc_heap) {
Some(self.as_structref_unchecked())
} else {
None
}
}
pub fn as_structref_unchecked(&self) -> &VMStructRef {
debug_assert!(!self.is_i31());
let ptr = self as *const VMGcRef;
let ret = unsafe { &*ptr.cast() };
assert!(matches!(ret, VMStructRef(VMGcRef { .. })));
ret
}
}
impl VMStructRef {
pub fn as_gc_ref(&self) -> &VMGcRef {
&self.0
}
pub fn clone(&self, gc_store: &mut GcStore) -> Self {
Self(gc_store.clone_gc_ref(&self.0))
}
pub fn drop(self, gc_store: &mut GcStore) {
gc_store.drop_gc_ref(self.0);
}
pub fn unchecked_copy(&self) -> Self {
Self(self.0.unchecked_copy())
}
pub fn read_field(
&self,
store: &mut AutoAssertNoGc,
layout: &GcStructLayout,
ty: &StorageType,
field: usize,
) -> Result<Val> {
let offset = layout.fields[field].offset;
self.as_gc_ref().read_val(store, ty, offset)
}
pub fn write_field(
&self,
store: &mut AutoAssertNoGc,
layout: &GcStructLayout,
ty: &StorageType,
field: usize,
val: Val,
) -> Result<()> {
debug_assert!(val._matches_ty(&store, &ty.unpack())?);
let offset = layout.fields[field].offset;
self.as_gc_ref().write_val(store, ty, offset, val)
}
pub fn initialize_field(
&self,
store: &mut AutoAssertNoGc,
layout: &GcStructLayout,
ty: &StorageType,
field: usize,
val: Val,
) -> Result<()> {
debug_assert!(val._matches_ty(&store, &ty.unpack())?);
let offset = layout.fields[field].offset;
self.as_gc_ref().initialize_val(store, ty, offset, val)
}
}