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
use super::{AsContext, AsContextMut, Stored};
use crate::{
collections::arena::ArenaIndex,
core::CoreGlobal,
errors::GlobalError,
GlobalType,
Mutability,
Val,
};
/// A raw index to a global variable entity.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct GlobalIdx(u32);
impl ArenaIndex for GlobalIdx {
fn into_usize(self) -> usize {
self.0 as usize
}
fn from_usize(value: usize) -> Self {
let value = value.try_into().unwrap_or_else(|error| {
panic!("index {value} is out of bounds as global index: {error}")
});
Self(value)
}
}
/// A Wasm global variable reference.
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct Global(Stored<GlobalIdx>);
impl Global {
/// Creates a new stored global variable reference.
///
/// # Note
///
/// This API is primarily used by the [`Store`] itself.
///
/// [`Store`]: [`crate::Store`]
pub(super) fn from_inner(stored: Stored<GlobalIdx>) -> Self {
Self(stored)
}
/// Returns the underlying stored representation.
pub(super) fn as_inner(&self) -> &Stored<GlobalIdx> {
&self.0
}
/// Creates a new global variable to the store.
pub fn new(mut ctx: impl AsContextMut, initial_value: Val, mutability: Mutability) -> Self {
ctx.as_context_mut()
.store
.inner
.alloc_global(CoreGlobal::new(initial_value.into(), mutability))
}
/// Returns the [`GlobalType`] of the global variable.
///
/// # Panics
///
/// Panics if `ctx` does not own this [`Global`].
pub fn ty(&self, ctx: impl AsContext) -> GlobalType {
ctx.as_context().store.inner.resolve_global(self).ty()
}
/// Sets a new value to the global variable.
///
/// # Errors
///
/// - If the global variable is immutable.
/// - If there is a type mismatch between the global variable and the new value.
///
/// # Panics
///
/// Panics if `ctx` does not own this [`Global`].
pub fn set(&self, mut ctx: impl AsContextMut, new_value: Val) -> Result<(), GlobalError> {
ctx.as_context_mut()
.store
.inner
.resolve_global_mut(self)
.set(new_value.into())
}
/// Returns the current value of the global variable.
///
/// # Panics
///
/// Panics if `ctx` does not own this [`Global`].
pub fn get(&self, ctx: impl AsContext) -> Val {
ctx.as_context()
.store
.inner
.resolve_global(self)
.get()
.into()
}
}