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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
//! `Resource` type.
use ;
use crate::;
/// Host resource exposed to WASM.
///
/// Internally, a resource is just an index into the `externref`s table; thus, it is completely
/// valid to store `Resource`s on heap (in a `Vec`, thread-local storage, etc.). The type param
/// can be used for type safety.
///
/// # Equality
///
/// `Resource` implements [`PartialEq`], [`Eq`] and [`Hash`] traits from the standard library,
/// in which it has pointer semantics (i.e., two `Resource`s are equal if they point to the same data,
/// which, since `Resource` [cannot be cloned](#cloning), means they are the same object). If you want to compare
/// the pointed-to content, it can be accomplished by wrapping a `Resource` into a higher-level abstraction
/// and implementing `PartialEq` / `Eq` / `Hash` / other traits e.g. by reading data from the host
/// or delegating comparison to the host.
///
/// # Cloning
///
/// By default, resources may have [configurable logic executed on drop](crate::processor::Processor::set_drop_fn())
/// (e.g., to have RAII-style resource management on the host side). Dropping the resource also cleans up the resource slot
/// in the `externref` table.
/// Thus, `Resource` intentionally doesn't implement [`Clone`] or [`Copy`]. To clone such a resource,
/// you may use [`Rc`](std::rc::Rc), [`Arc`](std::sync::Arc) or another smart pointer.
///
/// As an alternative, you may use [`ResourceCopy`]. This is a version of `Resource` that does not
/// execute *any* logic on drop (not even cleaning up the `externref` table entry!). As a consequence,
/// `ResourceCopy` may be copied across the app.
///
/// # Memory layout
///
/// `Resource` with any type params is guaranteed to have the same layout as `usize`. When cast to `usize`
/// (e.g., by passing a `Resource` value to a WASM import fn), the value is the index of the externref
/// in the corresponding WASM table (see [*How it works*](crate#how-it-works) in the crate level-docs for details).
///
/// # Examples
///
/// ## Cloning
///
/// In this scenario, the `Resource` is cloneable by wrapping it in an `Arc`. This retains RAII
/// resource management capabilities.
///
/// ```no_run
/// use externref::{externref, Resource};
/// use std::sync::Arc;
///
/// #[externref]
/// #[link(wasm_import_module = "data")]
/// unsafe extern "C" {
/// fn alloc_data(capacity: usize) -> Resource<SmartData>;
///
/// fn data_len(handle: &Resource<SmartData>) -> usize;
/// }
///
/// #[derive(Debug, Clone)]
/// pub struct SmartData {
/// // `Resource<Self>` is completely valid (doesn't lead to type size errors),
/// // and in fact is encouraged.
/// handle: Arc<Resource<Self>>,
/// }
///
/// impl SmartData {
/// fn new(capacity: usize) -> Self {
/// Self {
/// handle: Arc::new(unsafe { alloc_data(capacity) }),
/// }
/// }
///
/// fn len(&self) -> usize {
/// unsafe { data_len(&self.handle) }
/// }
/// }
/// ```
///
/// ## Implementing comparisons
///
/// This implements `Eq`, `Ord` and `Hash` traits for the *pointee* based on host imports.
///
/// ```no_run
/// use externref::{externref, Resource};
/// use core::{cmp, hash::{Hash, Hasher}};
///
/// #[externref]
/// #[link(wasm_import_module = "data")]
/// unsafe extern "C" {
/// /// Compares pointed-to data and returns -1 / 0 / 1.
/// fn compare(
/// lhs: &Resource<ComparableData>,
/// rhs: &Resource<ComparableData>,
/// ) -> isize;
///
/// /// Hashes the pointed-to data.
/// fn hash(data: &Resource<ComparableData>) -> u64;
/// }
///
/// #[derive(Debug)]
/// pub struct ComparableData {
/// handle: Resource<Self>,
/// }
///
/// impl PartialEq for ComparableData {
/// fn eq(&self, other: &Self) -> bool {
/// unsafe { compare(&self.handle, &other.handle) == 0 }
/// }
/// }
///
/// impl Eq for ComparableData {}
///
/// impl PartialOrd for ComparableData {
/// fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
/// Some(self.cmp(other))
/// }
/// }
///
/// impl Ord for ComparableData {
/// fn cmp(&self, other: &Self) -> cmp::Ordering {
/// let ordering = unsafe { compare(&self.handle, &other.handle) };
/// ordering.cmp(&0)
/// }
/// }
///
/// impl Hash for ComparableData {
/// fn hash<H: Hasher>(&self, hasher: &mut H) {
/// unsafe { hash(&self.handle) }.hash(hasher)
/// }
/// }
/// ```
/// [`Resource`] variation that can be copied.
///
/// # Cleanup
///
/// `ResourceCopy` **does not** clean up the `externref` table entry on drop. It can only be cleaned up
/// by the host side, or by implementing custom `Drop` logic for a higher-level `Resource` wrapper.
/// In the extreme case, when the WASM module is short-lived, garbage collection of dead `externref`s may
/// be summarily ignored.
///
/// For custom `Drop` logic, it may be useful to pass `ResourceCopy<_>` by value as a non-resource
/// (see the [`externref`](macro@crate::externref) macro docs) as follows.
///
/// ```no_run
/// use externref::{externref, ResourceCopy};
///
/// #[externref]
/// // ^ In this particular case, this attribute may be skipped.
/// #[link(wasm_import_module = "data")]
/// unsafe extern "C" {
/// fn custom_drop(#[resource = false] data: ResourceCopy<CustomDrop>);
/// // The host will receive `data: usize` - the 0-based index
/// // of `externref` table entry the resource points to.
/// }
///
/// struct CustomDrop(ResourceCopy<Self>);
///
/// impl Drop for CustomDrop {
/// fn drop(&mut self) {
/// unsafe { custom_drop(self.0); }
/// }
/// }
/// ```
///
/// This relies on the fact that `ResourceCopy<_>` is guaranteed to have the identical layout as `usize`.
pub type ResourceCopy<T> = ;
// should only be used by macro-generated code
// should only be used by macro-generated code
/// Compares resources by their pointers, similar to [`ptr::eq()`].
/// Hashes the resource based on its pointer, consistently with the [`PartialEq`] / [`Eq`] implementation.