Skip to main content

wasmtime/runtime/gc/enabled/
i31.rs

1//! Unboxed 31-bit integers.
2//!
3//! Note that ideally, we would just re-export `wasmtime_runtime::I31` here, but
4//! in order to get doc comments with example code that shows the use of `I31`
5//! with typed functions and such, we need to wrap it in a newtype.
6
7use crate::prelude::*;
8use crate::runtime::vm::{VMGcRef, ValRaw};
9use crate::{
10    HeapType, RefType, Result, ValType, WasmTy,
11    store::{AutoAssertNoGc, StoreOpaque},
12};
13use core::fmt;
14use core::mem::MaybeUninit;
15
16/// A 31-bit integer.
17///
18/// Represents WebAssembly's `(ref i31)` and `(ref null i31)` (aka `i31ref`)
19/// references.
20///
21/// You can convert this into any of the `(ref i31)` supertypes such as `(ref
22/// eq)` or `(ref any)`, and their nullable equivalents. After conversion, the
23/// resulting reference does not actually point at a GC object in the heap,
24/// instead it is a 31-bit integer that is stored unboxed/inline in the
25/// reference itself.
26///
27/// # Example
28///
29/// ```
30/// # use wasmtime::*;
31/// # fn _foo() -> Result<()> {
32/// // Enable the Wasm GC proposal for Wasm to use i31 references.
33/// let mut config = Config::new();
34/// config.wasm_gc(true);
35///
36/// let engine = Engine::new(&config)?;
37/// let mut store = Store::new(&engine, ());
38///
39/// // A Wasm module that exports a function that increments an i31.
40/// let module = Module::new(&engine, r#"
41///     (module
42///         (func (export "inc_i31") (param (ref i31)) (result (ref i31))
43///             local.get 0
44///             i31.get_u
45///             i32.const 1
46///             i32.add
47///             ref.i31
48///         )
49/// "#)?;
50///
51/// // Instantiate the module.
52/// let instance = Instance::new(&mut store, &module, &[])?;
53///
54/// // Get the exported `inc_i31` function.
55/// let inc_i31 = instance.get_func(&mut store, "inc_i31").unwrap();
56///
57/// // Call the function using the untyped functions API, meaning we need to
58/// // pack our `I31` argument into an `AnyRef` that is packed into a `Val`, and
59/// // then we need to do the opposite unpacking to extract the result.
60/// let i31 = I31::wrapping_u32(0x1234);
61/// let anyref = AnyRef::from_i31(&mut store, i31);
62/// let val = Val::from(anyref);
63/// let mut results = [Val::null_any_ref()];
64/// inc_i31.call(&mut store, &[val], &mut results)?;
65/// let nullable_anyref = results[0].unwrap_anyref();
66/// let anyref = nullable_anyref.unwrap().unwrap_unrooted();
67/// let i31 = anyref.as_i31(&store)?.unwrap();
68/// assert_eq!(i31.get_u32(), 0x1235);
69///
70/// // Alternatively, we can use the typed function API to make this all a lot
71/// // more ergonomic.
72/// let inc_i31 = inc_i31.typed::<I31, I31>(&mut store)?;
73/// let i31 = I31::wrapping_u32(0x5678);
74/// let result = inc_i31.call(&mut store, i31)?;
75/// assert_eq!(result.get_u32(), 0x5679);
76/// # Ok(())
77/// # }
78/// ```
79#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
80pub struct I31(crate::runtime::vm::I31);
81
82impl fmt::Debug for I31 {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.debug_struct("I31")
85            .field("as_u32", &self.get_u32())
86            .field("as_i32", &self.get_i32())
87            .finish()
88    }
89}
90
91impl From<crate::runtime::vm::I31> for I31 {
92    #[inline]
93    fn from(value: crate::runtime::vm::I31) -> Self {
94        Self(value)
95    }
96}
97
98impl From<I31> for crate::runtime::vm::I31 {
99    #[inline]
100    fn from(value: I31) -> Self {
101        value.0
102    }
103}
104
105impl I31 {
106    /// Get this `wasmtime::I31`'s internal `crate::runtime::vm::I31`.
107    pub(crate) fn runtime_i31(self) -> crate::runtime::vm::I31 {
108        self.0
109    }
110
111    /// Construct a new `I31` from the given unsigned value.
112    ///
113    /// Returns `None` if the value does not fit in the bottom 31 bits.
114    ///
115    /// # Example
116    ///
117    /// ```
118    /// # use wasmtime::*;
119    /// // This value does not fit into 31 bits.
120    /// assert!(I31::new_u32(0x8000_0000).is_none());
121    ///
122    /// // This value does fit into 31 bits.
123    /// let x = I31::new_u32(5).unwrap();
124    /// assert_eq!(x.get_u32(), 5);
125    /// ```
126    #[inline]
127    pub fn new_u32(value: u32) -> Option<Self> {
128        crate::runtime::vm::I31::new_u32(value).map(Self)
129    }
130
131    /// Construct a new `I31` from the given signed value.
132    ///
133    /// Returns `None` if the value does not fit in the bottom 31 bits.
134    ///
135    /// # Example
136    ///
137    /// ```
138    /// # use wasmtime::*;
139    /// // This value does not fit into 31 bits.
140    /// assert!(I31::new_i32(-2147483648).is_none());
141    ///
142    /// // This value does fit into 31 bits.
143    /// let x = I31::new_i32(-5).unwrap();
144    /// assert_eq!(x.get_i32(), -5);
145    /// ```
146    #[inline]
147    pub fn new_i32(value: i32) -> Option<Self> {
148        crate::runtime::vm::I31::new_i32(value).map(Self)
149    }
150
151    /// Construct a new `I31` from the given unsigned value.
152    ///
153    /// If the value doesn't fit in the bottom 31 bits, it is wrapped such that
154    /// the wrapped value does.
155    ///
156    /// # Example
157    ///
158    /// ```
159    /// # use wasmtime::*;
160    /// // Values that fit in 31 bits are preserved.
161    /// let x = I31::wrapping_u32(5);
162    /// assert_eq!(x.get_u32(), 5);
163    ///
164    /// // Values that do not fit in 31 bits are wrapped to 31 bits.
165    /// let y = I31::wrapping_u32(0xffff_ffff);
166    /// assert_eq!(y.get_u32(), 0x7fff_ffff);
167    /// ```
168    #[inline]
169    pub fn wrapping_u32(value: u32) -> Self {
170        Self(crate::runtime::vm::I31::wrapping_u32(value))
171    }
172
173    /// Construct a new `I31` from the given signed value.
174    ///
175    /// If the value doesn't fit in the bottom 31 bits, it is wrapped such that
176    /// the wrapped value does.
177    ///
178    /// # Example
179    ///
180    /// ```
181    /// # use wasmtime::*;
182    /// // Values that fit in 31 bits are preserved.
183    /// let x = I31::wrapping_i32(-5);
184    /// assert_eq!(x.get_i32(), -5);
185    ///
186    /// // Values that do not fit in 31 bits are wrapped to 31 bits.
187    /// let y = I31::wrapping_i32(-1073741825); // 0xbfffffff
188    /// assert_eq!(y.get_i32(), 1073741823);    // 0x3fffffff
189    /// ```
190    #[inline]
191    pub fn wrapping_i32(value: i32) -> Self {
192        Self(crate::runtime::vm::I31::wrapping_i32(value))
193    }
194
195    /// Get this `I31`'s value as an unsigned integer.
196    ///
197    /// # Example
198    ///
199    /// ```
200    /// # use wasmtime::*;
201    /// let x = I31::new_i32(-1).unwrap();
202    /// assert_eq!(x.get_u32(), 0x7fff_ffff);
203    /// ```
204    #[inline]
205    pub fn get_u32(&self) -> u32 {
206        self.0.get_u32()
207    }
208
209    /// Get this `I31`'s value as a signed integer.
210    ///
211    /// # Example
212    ///
213    /// ```
214    /// # use wasmtime::*;
215    /// let x = I31::new_u32(0x7fff_ffff).unwrap();
216    /// assert_eq!(x.get_i32(), -1);
217    /// ```
218    #[inline]
219    pub fn get_i32(&self) -> i32 {
220        self.0.get_i32()
221    }
222}
223
224unsafe impl WasmTy for I31 {
225    #[inline]
226    fn valtype() -> ValType {
227        ValType::Ref(RefType::new(false, HeapType::I31))
228    }
229
230    #[inline]
231    fn compatible_with_store(&self, _store: &StoreOpaque) -> bool {
232        true
233    }
234
235    fn dynamic_concrete_type_check(
236        &self,
237        _store: &StoreOpaque,
238        _nullable: bool,
239        actual: &HeapType,
240    ) -> Result<()> {
241        // The only concrete types in the `any` hierarchy are struct and array
242        // types, and an `i31` is never an instance of either.
243        bail!("argument type mismatch: expected (ref {actual}), found (ref i31)")
244    }
245
246    fn store(self, _store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
247        let gc_ref = VMGcRef::from_i31(self.into()).as_raw_u32();
248        ptr.write(ValRaw::anyref(gc_ref));
249        Ok(())
250    }
251
252    unsafe fn load(_store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
253        let raw = ptr.get_anyref();
254        let gc_ref = VMGcRef::from_raw_u32(raw).expect("non-null");
255        gc_ref.unwrap_i31().into()
256    }
257}
258
259unsafe impl WasmTy for Option<I31> {
260    #[inline]
261    fn valtype() -> ValType {
262        ValType::Ref(RefType::new(true, HeapType::I31))
263    }
264
265    #[inline]
266    fn compatible_with_store(&self, _store: &StoreOpaque) -> bool {
267        true
268    }
269
270    fn dynamic_concrete_type_check(
271        &self,
272        store: &StoreOpaque,
273        nullable: bool,
274        actual: &HeapType,
275    ) -> Result<()> {
276        match self {
277            Some(i) => i.dynamic_concrete_type_check(store, nullable, actual),
278            None => {
279                ensure!(
280                    nullable,
281                    "argument type mismatch: expected non-nullable (ref {actual}), found null reference"
282                );
283                Ok(())
284            }
285        }
286    }
287
288    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
289        match self {
290            Some(i) => i.store(store, ptr),
291            None => {
292                ptr.write(ValRaw::anyref(0));
293                Ok(())
294            }
295        }
296    }
297
298    unsafe fn load(_store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
299        let raw = ptr.get_anyref();
300        let gc_ref = VMGcRef::from_raw_u32(raw)?;
301        Some(I31(gc_ref.unwrap_i31()))
302    }
303}