linera_wasmer_vm/
extern_ref.rs

1use derivative::Derivative;
2use std::any::Any;
3use wasmer_types::RawValue;
4
5use crate::store::InternalStoreHandle;
6
7/// Underlying object referenced by a `VMExternRef`.
8#[derive(Derivative)]
9#[derivative(Debug)]
10pub struct VMExternObj {
11    #[derivative(Debug = "ignore")]
12    contents: Box<dyn Any + Send + Sync + 'static>,
13}
14
15impl VMExternObj {
16    /// Wraps the given value to expose it to Wasm code as an externref.
17    pub fn new(val: impl Any + Send + Sync + 'static) -> Self {
18        Self {
19            contents: Box::new(val),
20        }
21    }
22
23    #[allow(clippy::should_implement_trait)]
24    /// Returns a reference to the underlying value.
25    pub fn as_ref(&self) -> &(dyn Any + Send + Sync + 'static) {
26        &*self.contents
27    }
28}
29
30/// Represents an opaque reference to any data within WebAssembly.
31#[repr(transparent)]
32#[derive(Debug, Clone, Copy)]
33pub struct VMExternRef(pub InternalStoreHandle<VMExternObj>);
34
35impl VMExternRef {
36    /// Converts the `VMExternRef` into a `RawValue`.
37    pub fn into_raw(self) -> RawValue {
38        RawValue {
39            funcref: self.0.index(),
40        }
41    }
42
43    /// Extracts a `VMExternRef` from a `RawValue`.
44    ///
45    /// # Safety
46    /// `raw` must be a valid `VMExternRef` instance.
47    pub unsafe fn from_raw(raw: RawValue) -> Option<Self> {
48        InternalStoreHandle::from_index(raw.externref).map(Self)
49    }
50}