Lines
100 %
Functions
18.6 %
Branches
//! Checked downcasts of a guest `anyref`. wasmtime's `unwrap_*` accessors
//! panic on a kind mismatch; a malformed guest value must surface as an error
//! instead of aborting the host.
use wasmtime::{AnyRef, ArrayRef, AsContext, I31, Rooted, StructRef};
pub trait CheckedAnyRef {
/// # Errors
/// Fails when the reference is unrooted or is not an `i31`.
fn checked_i31(&self, store: impl AsContext) -> wasmtime::Result<I31>;
/// Fails when the reference is unrooted or is not a struct.
fn checked_struct(&self, store: impl AsContext) -> wasmtime::Result<Rooted<StructRef>>;
/// Fails when the reference is unrooted or is not an array.
fn checked_array(&self, store: impl AsContext) -> wasmtime::Result<Rooted<ArrayRef>>;
}
impl CheckedAnyRef for Rooted<AnyRef> {
fn checked_i31(&self, store: impl AsContext) -> wasmtime::Result<I31> {
self.as_i31(store)?.ok_or_else(|| kind_mismatch("i31"))
fn checked_struct(&self, store: impl AsContext) -> wasmtime::Result<Rooted<StructRef>> {
self.as_struct(store)?
.ok_or_else(|| kind_mismatch("struct"))
fn checked_array(&self, store: impl AsContext) -> wasmtime::Result<Rooted<ArrayRef>> {
self.as_array(store)?.ok_or_else(|| kind_mismatch("array"))
fn kind_mismatch(expected: &str) -> wasmtime::Error {
wasmtime::Error::msg(format!("guest anyref is not the expected {expected} ref"))
#[cfg(test)]
mod tests;