1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use crate::{
collections::arena::ArenaIndex,
core::{ReadAs, UntypedVal, WriteAs},
store::Stored,
AsContextMut,
Func,
StoreContext,
};
use alloc::boxed::Box;
use core::{any::Any, mem, num::NonZeroU32};
/// A nullable reference type.
#[derive(Debug, Default, Copy, Clone)]
pub enum Ref<T> {
/// The [`Ref`] is a non-`null` value.
Val(T),
/// The [`Ref`] is `null`.
#[default]
Null,
}
impl<T> Ref<T> {
/// Returns `true` is `self` is null.
pub fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
/// Returns `Some` if `self` is a non-`null` value.
///
/// Otherwise returns `None`.
pub fn val(&self) -> Option<&T> {
match self {
Ref::Val(val) => Some(val),
Ref::Null => None,
}
}
/// Converts from `&Ref<T>` to `Ref<&T>`.
pub fn as_ref(&self) -> Ref<&T> {
match self {
Ref::Val(val) => Ref::Val(val),
Ref::Null => Ref::Null,
}
}
}
impl<T> From<T> for Ref<T> {
fn from(value: T) -> Self {
Self::Val(value)
}
}
/// A raw index to an external entity.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ExternRefIdx(NonZeroU32);
impl ArenaIndex for ExternRefIdx {
fn into_usize(self) -> usize {
self.0.get().wrapping_sub(1) as usize
}
fn from_usize(index: usize) -> Self {
index
.try_into()
.ok()
.map(|index: u32| index.wrapping_add(1))
.and_then(NonZeroU32::new)
.map(Self)
.unwrap_or_else(|| panic!("out of bounds extern object index {index}"))
}
}
/// An externally defined object.
#[derive(Debug)]
pub struct ExternRefEntity {
inner: Box<dyn 'static + Any + Send + Sync>,
}
impl ExternRefEntity {
/// Creates a new instance of `ExternRef` wrapping the given value.
pub fn new<T>(object: T) -> Self
where
T: 'static + Any + Send + Sync,
{
Self {
inner: Box::new(object),
}
}
/// Returns a shared reference to the external object.
pub fn data(&self) -> &dyn Any {
&*self.inner
}
}
/// Represents an opaque reference to any data within WebAssembly.
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct ExternRef(Stored<ExternRefIdx>);
impl ExternRef {
/// Creates a new [`ExternRef`] reference from its raw representation.
pub(crate) fn from_inner(stored: Stored<ExternRefIdx>) -> Self {
Self(stored)
}
/// Returns the raw representation of the [`ExternRef`].
pub(crate) fn as_inner(&self) -> &Stored<ExternRefIdx> {
&self.0
}
/// Creates a new instance of `ExternRef` wrapping the given value.
pub fn new<T>(mut ctx: impl AsContextMut, object: T) -> Self
where
T: 'static + Any + Send + Sync,
{
ctx.as_context_mut()
.store
.inner
.alloc_extern_object(ExternRefEntity::new(object))
}
/// Returns a shared reference to the underlying data for this [`ExternRef`].
///
/// # Panics
///
/// Panics if `ctx` does not own this [`ExternRef`].
pub fn data<'a, T: 'a>(&self, ctx: impl Into<StoreContext<'a, T>>) -> &'a dyn Any {
ctx.into().store.inner.resolve_externref(self).data()
}
}
#[test]
fn externref_sizeof() {
// These assertions are important in order to convert `FuncRef`
// from and to 64-bit `UntypedValue` instances.
//
// The following equation must be true:
// size_of(ExternRef) == size_of(ExternObject) == size_of(UntypedValue)
use core::mem::size_of;
assert_eq!(size_of::<ExternRef>(), size_of::<u64>());
assert_eq!(size_of::<ExternRef>(), size_of::<ExternRef>());
}
#[test]
fn externref_null_to_zero() {
assert_eq!(
UntypedVal::from(<Ref<ExternRef>>::Null),
UntypedVal::from(0)
);
assert!(<Ref<ExternRef>>::from(UntypedVal::from(0)).is_null());
}
#[test]
fn funcref_sizeof() {
// These assertions are important in order to convert `FuncRef`
// from and to 64-bit `UntypedValue` instances.
//
// The following equation must be true:
// size_of(Func) == size_of(UntypedValue) == size_of(FuncRef)
use crate::Func;
use core::mem::size_of;
assert_eq!(size_of::<Func>(), size_of::<u64>());
assert_eq!(size_of::<Func>(), size_of::<Ref<Func>>());
}
#[test]
fn funcref_null_to_zero() {
use crate::Func;
assert_eq!(UntypedVal::from(<Ref<Func>>::Null), UntypedVal::from(0));
assert!(<Ref<Func>>::from(UntypedVal::from(0)).is_null());
}
macro_rules! impl_conversions {
( $( $reftype:ty ),* $(,)? ) => {
$(
impl ReadAs<$reftype> for UntypedVal {
fn read_as(&self) -> $reftype {
let bits = u64::from(*self);
unsafe { mem::transmute::<u64, $reftype>(bits) }
}
}
impl ReadAs<Ref<$reftype>> for UntypedVal {
fn read_as(&self) -> Ref<$reftype> {
let bits = u64::from(*self);
if bits == 0 {
return <Ref<$reftype>>::Null;
}
<Ref<$reftype>>::Val(<Self as ReadAs<$reftype>>::read_as(self))
}
}
impl WriteAs<$reftype> for UntypedVal {
fn write_as(&mut self, value: $reftype) {
let bits = unsafe { mem::transmute::<$reftype, u64>(value) };
self.write_as(bits)
}
}
impl WriteAs<Ref<$reftype>> for UntypedVal {
fn write_as(&mut self, value: Ref<$reftype>) {
match value {
Ref::Null => self.write_as(0_u64),
Ref::Val(value) => self.write_as(value),
}
}
}
impl From<UntypedVal> for Ref<$reftype> {
fn from(untyped: UntypedVal) -> Self {
if u64::from(untyped) == 0 {
return <Ref<$reftype>>::Null;
}
// Safety: This operation is safe since there are no invalid
// bit patterns for [`ExternRef`] instances. Therefore
// this operation cannot produce invalid [`ExternRef`]
// instances even though the input [`UntypedVal`]
// was modified arbitrarily.
unsafe { mem::transmute::<u64, Self>(untyped.into()) }
}
}
impl From<$reftype> for UntypedVal {
fn from(reftype: $reftype) -> Self {
// Safety: This operation is safe since there are no invalid
// bit patterns for [`UntypedVal`] instances. Therefore
// this operation cannot produce invalid [`UntypedVal`]
// instances even if it was possible to arbitrarily modify
// the input `$reftype` instance.
let bits = unsafe { mem::transmute::<$reftype, u64>(reftype) };
UntypedVal::from(bits)
}
}
impl From<Ref<$reftype>> for UntypedVal {
fn from(reftype: Ref<$reftype>) -> Self {
match reftype {
Ref::Val(reftype) => UntypedVal::from(reftype),
Ref::Null => UntypedVal::from(0_u64),
}
}
}
)*
};
}
impl_conversions! {
ExternRef,
Func,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Engine, Store};
#[test]
fn it_works() {
let engine = Engine::default();
let mut store = <Store<()>>::new(&engine, ());
let value = 42_i32;
let obj = ExternRef::new::<i32>(&mut store, value);
assert_eq!(obj.data(&store).downcast_ref::<i32>(), Some(&value),);
}
}