numcodecs_wasm_host_reproducible/
engine.rs

1use wasm_runtime_layer::{
2    ExportType, ExternType, FuncType, GlobalType, ImportType, MemoryType, TableType,
3    backend::{
4        AsContext, AsContextMut, Export, Extern, Imports, Value, WasmEngine, WasmExternRef,
5        WasmFunc, WasmGlobal, WasmInstance, WasmMemory, WasmModule, WasmStore, WasmStoreContext,
6        WasmStoreContextMut, WasmTable,
7    },
8};
9
10use crate::transform::{
11    instcnt::{InstructionCounterInjecter, PerfWitInterfaces},
12    nan::NaNCanonicaliser,
13};
14
15#[derive(Clone)]
16#[repr(transparent)]
17pub struct ReproducibleEngine<E: WasmEngine>(E);
18
19impl<E: WasmEngine> WasmEngine for ReproducibleEngine<E> {
20    type ExternRef = ReproducibleExternRef<E>;
21    type Func = ReproducibleFunc<E>;
22    type Global = ReproducibleGlobal<E>;
23    type Instance = ReproducibleInstance<E>;
24    type Memory = ReproducibleMemory<E>;
25    type Module = ReproducibleModule<E>;
26    type Store<T> = ReproducibleStore<T, E>;
27    type StoreContext<'a, T: 'a> = ReproducibleStoreContext<'a, T, E>;
28    type StoreContextMut<'a, T: 'a> = ReproducibleStoreContextMut<'a, T, E>;
29    type Table = ReproducibleTable<E>;
30}
31
32impl<E: WasmEngine> ReproducibleEngine<E> {
33    pub const fn new(engine: E) -> Self {
34        Self(engine)
35    }
36
37    const fn as_ref(&self) -> &E {
38        &self.0
39    }
40
41    const fn from_ref(engine: &E) -> &Self {
42        // Safety: Self is a transparent newtype around E
43        #[expect(unsafe_code)]
44        unsafe {
45            &*std::ptr::from_ref(engine).cast()
46        }
47    }
48}
49
50#[derive(Clone)]
51#[repr(transparent)]
52pub struct ReproducibleExternRef<E: WasmEngine>(E::ExternRef);
53
54impl<E: WasmEngine> WasmExternRef<ReproducibleEngine<E>> for ReproducibleExternRef<E> {
55    fn new<T: 'static + Send + Sync>(
56        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
57        object: T,
58    ) -> Self {
59        Self(<E::ExternRef as WasmExternRef<E>>::new(
60            ctx.as_context_mut().as_inner_context_mut(),
61            object,
62        ))
63    }
64
65    fn downcast<'a, 's: 'a, T: 'static, S: 'a>(
66        &'a self,
67        store: ReproducibleStoreContext<'s, S, E>,
68    ) -> anyhow::Result<&'a T> {
69        WasmExternRef::downcast(&self.0, store.0)
70    }
71}
72
73#[derive(Clone)]
74#[repr(transparent)]
75pub struct ReproducibleFunc<E: WasmEngine>(E::Func);
76
77impl<E: WasmEngine> WasmFunc<ReproducibleEngine<E>> for ReproducibleFunc<E> {
78    fn new<T>(
79        mut ctx: impl AsContextMut<ReproducibleEngine<E>, UserState = T>,
80        ty: FuncType,
81        func: impl 'static
82        + Send
83        + Sync
84        + Fn(
85            ReproducibleStoreContextMut<T, E>,
86            &[Value<ReproducibleEngine<E>>],
87            &mut [Value<ReproducibleEngine<E>>],
88        ) -> anyhow::Result<()>,
89    ) -> Self {
90        Self(<E::Func as WasmFunc<E>>::new(
91            ctx.as_context_mut().as_inner_context_mut(),
92            ty,
93            move |ctx, args, results| {
94                func(
95                    ReproducibleStoreContextMut(ctx),
96                    from_values(args),
97                    from_values_mut(results),
98                )
99            },
100        ))
101    }
102
103    fn ty(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> FuncType {
104        WasmFunc::ty(&self.0, ctx.as_context().as_inner_context())
105    }
106
107    fn call<T>(
108        &self,
109        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
110        args: &[Value<ReproducibleEngine<E>>],
111        results: &mut [Value<ReproducibleEngine<E>>],
112    ) -> anyhow::Result<()> {
113        WasmFunc::call::<T>(
114            &self.0,
115            ctx.as_context_mut().as_inner_context_mut(),
116            as_values(args),
117            as_values_mut(results),
118        )
119    }
120}
121
122#[derive(Clone)]
123#[repr(transparent)]
124pub struct ReproducibleGlobal<E: WasmEngine>(E::Global);
125
126impl<E: WasmEngine> WasmGlobal<ReproducibleEngine<E>> for ReproducibleGlobal<E> {
127    fn new(
128        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
129        value: Value<ReproducibleEngine<E>>,
130        mutable: bool,
131    ) -> Self {
132        Self(<E::Global as WasmGlobal<E>>::new(
133            ctx.as_context_mut().as_inner_context_mut(),
134            into_value(value),
135            mutable,
136        ))
137    }
138
139    fn ty(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> GlobalType {
140        WasmGlobal::ty(&self.0, ctx.as_context().as_inner_context())
141    }
142
143    fn set(
144        &self,
145        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
146        new_value: Value<ReproducibleEngine<E>>,
147    ) -> anyhow::Result<()> {
148        WasmGlobal::set(
149            &self.0,
150            ctx.as_context_mut().as_inner_context_mut(),
151            into_value(new_value),
152        )
153    }
154
155    fn get(
156        &self,
157        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
158    ) -> Value<ReproducibleEngine<E>> {
159        from_value(WasmGlobal::get(
160            &self.0,
161            ctx.as_context_mut().as_inner_context_mut(),
162        ))
163    }
164}
165
166#[derive(Clone)]
167#[repr(transparent)]
168pub struct ReproducibleInstance<E: WasmEngine>(E::Instance);
169
170impl<E: WasmEngine> WasmInstance<ReproducibleEngine<E>> for ReproducibleInstance<E> {
171    fn new(
172        mut store: impl AsContextMut<ReproducibleEngine<E>>,
173        module: &ReproducibleModule<E>,
174        imports: &Imports<ReproducibleEngine<E>>,
175    ) -> anyhow::Result<Self> {
176        let mut new_imports = Imports::new();
177        new_imports.extend(
178            imports
179                .into_iter()
180                .map(|((module, name), value)| ((module, name), into_extern(value))),
181        );
182
183        let PerfWitInterfaces {
184            perf: perf_interface,
185            instruction_counter,
186        } = PerfWitInterfaces::get();
187        new_imports.define(
188            &format!("{perf_interface}"),
189            instruction_counter,
190            Extern::Global(
191                store
192                    .as_context_mut()
193                    .get_instruction_counter_global()
194                    .0
195                    .clone(),
196            ),
197        );
198
199        Ok(Self(<E::Instance as WasmInstance<E>>::new(
200            store.as_context_mut().as_inner_context_mut(),
201            &module.0,
202            &new_imports,
203        )?))
204    }
205
206    fn exports(
207        &self,
208        store: impl AsContext<ReproducibleEngine<E>>,
209    ) -> Box<dyn Iterator<Item = Export<ReproducibleEngine<E>>>> {
210        Box::new(
211            WasmInstance::exports(&self.0, store.as_context().as_inner_context()).map(
212                |Export { name, value }| Export {
213                    name,
214                    value: from_extern(value),
215                },
216            ),
217        )
218    }
219
220    fn get_export(
221        &self,
222        store: impl AsContext<ReproducibleEngine<E>>,
223        name: &str,
224    ) -> Option<Extern<ReproducibleEngine<E>>> {
225        WasmInstance::get_export(&self.0, store.as_context().as_inner_context(), name)
226            .map(from_extern)
227    }
228}
229
230#[derive(Clone)]
231#[repr(transparent)]
232pub struct ReproducibleMemory<E: WasmEngine>(E::Memory);
233
234impl<E: WasmEngine> WasmMemory<ReproducibleEngine<E>> for ReproducibleMemory<E> {
235    fn new(
236        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
237        ty: MemoryType,
238    ) -> anyhow::Result<Self> {
239        Ok(Self(<E::Memory as WasmMemory<E>>::new(
240            ctx.as_context_mut().as_inner_context_mut(),
241            ty,
242        )?))
243    }
244
245    fn ty(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> MemoryType {
246        WasmMemory::ty(&self.0, ctx.as_context().as_inner_context())
247    }
248
249    fn grow(
250        &self,
251        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
252        additional: u32,
253    ) -> anyhow::Result<u32> {
254        WasmMemory::grow(
255            &self.0,
256            ctx.as_context_mut().as_inner_context_mut(),
257            additional,
258        )
259    }
260
261    fn current_pages(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> u32 {
262        WasmMemory::current_pages(&self.0, ctx.as_context().as_inner_context())
263    }
264
265    fn read(
266        &self,
267        ctx: impl AsContext<ReproducibleEngine<E>>,
268        offset: usize,
269        buffer: &mut [u8],
270    ) -> anyhow::Result<()> {
271        WasmMemory::read(&self.0, ctx.as_context().as_inner_context(), offset, buffer)
272    }
273
274    fn write(
275        &self,
276        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
277        offset: usize,
278        buffer: &[u8],
279    ) -> anyhow::Result<()> {
280        WasmMemory::write(
281            &self.0,
282            ctx.as_context_mut().as_inner_context_mut(),
283            offset,
284            buffer,
285        )
286    }
287}
288
289pub const DETERMINISTIC_WASM_MODULE_FEATURES: wasmparser::WasmFeaturesInflated =
290    wasmparser::WasmFeaturesInflated {
291        // MUST: mutable globals do not introduce non-determinism, as long
292        //       as the host does not change their value to be non-
293        //       deterministic
294        mutable_global: true,
295        // OK: saturating float -> int conversions only produce finite values
296        saturating_float_to_int: true,
297        // MUST: arithmetic sign extension operators are deterministic
298        sign_extension: true,
299        // (unsure): disabled for now, needs further research
300        reference_types: false,
301        // OK: returning multiple values does not interact with determinism
302        multi_value: true,
303        // MUST: operations like memcpy and memset are deterministic
304        bulk_memory: true,
305        // (ok): fixed-width SIMD replicates scalar float semantics
306        simd: true,
307        // BAD: exposes platform-dependent behaviour and non-determinism
308        relaxed_simd: false,
309        // BAD: allows non-deterministic concurrency and race conditions
310        threads: false,
311        // BAD: allows non-deterministic concurrency and race conditions
312        shared_everything_threads: false,
313        // (ok): using tail calls does not interact with determinism
314        //       but support is not universal yet:
315        //       https://webassembly.org/features/
316        tail_call: false,
317        // BAD: float operations can introduce non-deterministic NaNs
318        floats: false,
319        // MUST: using multiple memories does not interact with determinism
320        multi_memory: true,
321        // (unsure): disabled for now, needs further research
322        exceptions: false,
323        // (nope): using a 64bit memory space does not interact with
324        //         determinism but encourages large memory usage
325        memory64: false,
326        // (ok): const i[32|64] add, sub, and mul are deterministic
327        //       but support is not universal yet:
328        //       https://webassembly.org/features/
329        extended_const: false,
330        // NO-CORE: components must have been translated into core WASM
331        //          modules by now
332        component_model: false,
333        // (unsure): disabled for now, needs further research
334        function_references: false,
335        // (unsure): disabled for now, needs further research
336        memory_control: false,
337        // (unsure): disabled for now, needs further research
338        gc: false,
339        // (ok): statically declaring a custom page size is deterministic
340        //       and could reduce resource consumption
341        //       but there is no support yet
342        custom_page_sizes: false,
343        // (unsure): disabled for now, needs further research
344        legacy_exceptions: false,
345        // (unsure): disabled for now, depends on reference types and gc,
346        //           needs further research
347        gc_types: false,
348        // (unsure): disabled for now, not needed since codecs are sync for now
349        stack_switching: false,
350        // OK: wide integer add, sub, and mul are deterministic
351        wide_arithmetic: true,
352        // NO-CORE: components must have been translated into core WASM
353        //          modules by now
354        cm_values: false,
355        // NO-CORE: components must have been translated into core WASM
356        //          modules by now
357        cm_nested_names: false,
358        // NO-CORE: components must have been translated into core WASM
359        //          modules by now
360        cm_async: false,
361        // NO-CORE: components must have been translated into core WASM
362        //          modules by now
363        cm_async_stackful: false,
364        // NO-CORE: components must have been translated into core WASM
365        //          modules by now
366        cm_async_builtins: false,
367        // NO-CORE: components must have been translated into core WASM
368        //          modules by now
369        cm_error_context: false,
370        // NO-CORE: components must have been translated into core WASM
371        //          modules by now
372        cm_fixed_size_list: false,
373        // NO-CORE: components must have been translated into core WASM
374        //          modules by now
375        cm_gc: false,
376        // (unsure): part of reference types, disabled for now, needs further
377        //           research
378        call_indirect_overlong: false,
379        // MUST: part of bulk memory, operations like memcpy and memset are
380        //       deterministic
381        bulk_memory_opt: true,
382    };
383
384#[derive(Clone)]
385#[repr(transparent)]
386pub struct ReproducibleModule<E: WasmEngine>(E::Module);
387
388impl<E: WasmEngine> WasmModule<ReproducibleEngine<E>> for ReproducibleModule<E> {
389    fn new(engine: &ReproducibleEngine<E>, bytes: &[u8]) -> anyhow::Result<Self> {
390        let features = wasmparser::WasmFeatures::from(wasmparser::WasmFeaturesInflated {
391            // MUST: floats are required and we are running the NaN
392            //       canonicalisation transform to make them deterministic
393            floats: true,
394            ..DETERMINISTIC_WASM_MODULE_FEATURES
395        });
396
397        wasmparser::Validator::new_with_features(features).validate_all(bytes)?;
398
399        // Inject an instruction counter into the WASM module
400        let bytes = InstructionCounterInjecter::apply_to_module(bytes, features)?;
401
402        // Normalise NaNs to ensure floating point operations are deterministic
403        let bytes = NaNCanonicaliser::apply_to_module(&bytes, features)?;
404
405        Ok(Self(<E::Module as WasmModule<E>>::new(
406            engine.as_ref(),
407            bytes.as_slice(),
408        )?))
409    }
410
411    fn exports(&self) -> Box<dyn '_ + Iterator<Item = ExportType<'_>>> {
412        WasmModule::exports(&self.0)
413    }
414
415    fn get_export(&self, name: &str) -> Option<ExternType> {
416        WasmModule::get_export(&self.0, name)
417    }
418
419    fn imports(&self) -> Box<dyn '_ + Iterator<Item = ImportType<'_>>> {
420        WasmModule::imports(&self.0)
421    }
422}
423
424struct StoreData<T, E: WasmEngine> {
425    data: T,
426    instruction_counter: Option<ReproducibleGlobal<E>>,
427}
428
429#[derive(Clone)]
430#[repr(transparent)]
431pub struct ReproducibleStore<T, E: WasmEngine>(E::Store<StoreData<T, E>>);
432
433impl<T, E: WasmEngine> WasmStore<T, ReproducibleEngine<E>> for ReproducibleStore<T, E> {
434    fn new(engine: &ReproducibleEngine<E>, data: T) -> Self {
435        Self(<E::Store<StoreData<T, E>> as WasmStore<
436            StoreData<T, E>,
437            E,
438        >>::new(
439            engine.as_ref(),
440            StoreData {
441                data,
442                instruction_counter: None,
443            },
444        ))
445    }
446
447    fn engine(&self) -> &ReproducibleEngine<E> {
448        ReproducibleEngine::from_ref(WasmStore::engine(&self.0))
449    }
450
451    fn data(&self) -> &T {
452        &WasmStore::data(&self.0).data
453    }
454
455    fn data_mut(&mut self) -> &mut T {
456        &mut WasmStore::data_mut(&mut self.0).data
457    }
458
459    fn into_data(self) -> T {
460        WasmStore::into_data(self.0).data
461    }
462}
463
464impl<T, E: WasmEngine> AsContext<ReproducibleEngine<E>> for ReproducibleStore<T, E> {
465    type UserState = T;
466
467    fn as_context(&self) -> ReproducibleStoreContext<'_, Self::UserState, E> {
468        ReproducibleStoreContext(AsContext::as_context(&self.0))
469    }
470}
471
472impl<T, E: WasmEngine> AsContextMut<ReproducibleEngine<E>> for ReproducibleStore<T, E> {
473    fn as_context_mut(&mut self) -> ReproducibleStoreContextMut<'_, Self::UserState, E> {
474        ReproducibleStoreContextMut(AsContextMut::as_context_mut(&mut self.0))
475    }
476}
477
478#[repr(transparent)]
479pub struct ReproducibleStoreContext<'a, T: 'a, E: WasmEngine>(E::StoreContext<'a, StoreData<T, E>>);
480
481impl<'a, T: 'a, E: WasmEngine> WasmStoreContext<'a, T, ReproducibleEngine<E>>
482    for ReproducibleStoreContext<'a, T, E>
483{
484    fn engine(&self) -> &ReproducibleEngine<E> {
485        ReproducibleEngine::from_ref(WasmStoreContext::engine(&self.0))
486    }
487
488    fn data(&self) -> &T {
489        &WasmStoreContext::data(&self.0).data
490    }
491}
492
493impl<'a, T: 'a, E: WasmEngine> AsContext<ReproducibleEngine<E>>
494    for ReproducibleStoreContext<'a, T, E>
495{
496    type UserState = T;
497
498    fn as_context(&self) -> ReproducibleStoreContext<'_, Self::UserState, E> {
499        ReproducibleStoreContext(AsContext::as_context(&self.0))
500    }
501}
502
503impl<'a, T: 'a, E: WasmEngine> ReproducibleStoreContext<'a, T, E> {
504    fn as_inner_context(&self) -> E::StoreContext<'_, StoreData<T, E>> {
505        self.0.as_context()
506    }
507}
508
509#[repr(transparent)]
510pub struct ReproducibleStoreContextMut<'a, T: 'a, E: WasmEngine>(
511    E::StoreContextMut<'a, StoreData<T, E>>,
512);
513
514impl<'a, T: 'a, E: WasmEngine> WasmStoreContext<'a, T, ReproducibleEngine<E>>
515    for ReproducibleStoreContextMut<'a, T, E>
516{
517    fn engine(&self) -> &ReproducibleEngine<E> {
518        ReproducibleEngine::from_ref(WasmStoreContext::engine(&self.0))
519    }
520
521    fn data(&self) -> &T {
522        &WasmStoreContext::data(&self.0).data
523    }
524}
525
526impl<'a, T: 'a, E: WasmEngine> WasmStoreContextMut<'a, T, ReproducibleEngine<E>>
527    for ReproducibleStoreContextMut<'a, T, E>
528{
529    fn data_mut(&mut self) -> &mut T {
530        &mut WasmStoreContextMut::data_mut(&mut self.0).data
531    }
532}
533
534impl<'a, T: 'a, E: WasmEngine> AsContext<ReproducibleEngine<E>>
535    for ReproducibleStoreContextMut<'a, T, E>
536{
537    type UserState = T;
538
539    fn as_context(&self) -> ReproducibleStoreContext<'_, Self::UserState, E> {
540        ReproducibleStoreContext(AsContext::as_context(&self.0))
541    }
542}
543
544impl<'a, T: 'a, E: WasmEngine> AsContextMut<ReproducibleEngine<E>>
545    for ReproducibleStoreContextMut<'a, T, E>
546{
547    fn as_context_mut(&mut self) -> ReproducibleStoreContextMut<'_, Self::UserState, E> {
548        ReproducibleStoreContextMut(AsContextMut::as_context_mut(&mut self.0))
549    }
550}
551
552impl<'a, T: 'a, E: WasmEngine> ReproducibleStoreContextMut<'a, T, E> {
553    fn as_inner_context_mut(&mut self) -> E::StoreContextMut<'_, StoreData<T, E>> {
554        self.0.as_context_mut()
555    }
556
557    fn get_instruction_counter_global(&mut self) -> &ReproducibleGlobal<E> {
558        let mut this = self;
559
560        // NLL cannot prove this to be safe, but Polonius can
561        polonius_the_crab::polonius!(|this| -> &'polonius ReproducibleGlobal<E> {
562            let data: &mut StoreData<T, E> = WasmStoreContextMut::data_mut(&mut this.0);
563            if let Some(global) = &data.instruction_counter {
564                polonius_the_crab::polonius_return!(global);
565            }
566        });
567
568        let global = WasmGlobal::new(AsContextMut::as_context_mut(this), Value::I64(0), true);
569
570        let data: &mut StoreData<T, E> = WasmStoreContextMut::data_mut(&mut this.0);
571        data.instruction_counter.insert(global)
572    }
573}
574
575#[derive(Clone)]
576#[repr(transparent)]
577pub struct ReproducibleTable<E: WasmEngine>(E::Table);
578
579impl<E: WasmEngine> WasmTable<ReproducibleEngine<E>> for ReproducibleTable<E> {
580    fn new(
581        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
582        ty: TableType,
583        init: Value<ReproducibleEngine<E>>,
584    ) -> anyhow::Result<Self> {
585        Ok(Self(<E::Table as WasmTable<E>>::new(
586            ctx.as_context_mut().as_inner_context_mut(),
587            ty,
588            into_value(init),
589        )?))
590    }
591
592    fn ty(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> TableType {
593        WasmTable::ty(&self.0, ctx.as_context().as_inner_context())
594    }
595
596    fn size(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> u32 {
597        WasmTable::size(&self.0, ctx.as_context().as_inner_context())
598    }
599
600    fn grow(
601        &self,
602        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
603        delta: u32,
604        init: Value<ReproducibleEngine<E>>,
605    ) -> anyhow::Result<u32> {
606        WasmTable::grow(
607            &self.0,
608            ctx.as_context_mut().as_inner_context_mut(),
609            delta,
610            into_value(init),
611        )
612    }
613
614    fn get(
615        &self,
616        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
617        index: u32,
618    ) -> Option<Value<ReproducibleEngine<E>>> {
619        WasmTable::get(&self.0, ctx.as_context_mut().as_inner_context_mut(), index).map(from_value)
620    }
621
622    fn set(
623        &self,
624        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
625        index: u32,
626        value: Value<ReproducibleEngine<E>>,
627    ) -> anyhow::Result<()> {
628        WasmTable::set(
629            &self.0,
630            ctx.as_context_mut().as_inner_context_mut(),
631            index,
632            into_value(value),
633        )
634    }
635}
636
637const fn as_values<E: WasmEngine>(values: &[Value<ReproducibleEngine<E>>]) -> &[Value<E>] {
638    // Safety: all of our WASM runtime type wrappers are transparent newtypes
639    #[expect(unsafe_code)]
640    unsafe {
641        std::slice::from_raw_parts(values.as_ptr().cast(), values.len())
642    }
643}
644
645const fn as_values_mut<E: WasmEngine>(
646    values: &mut [Value<ReproducibleEngine<E>>],
647) -> &mut [Value<E>] {
648    // Safety: all of our WASM runtime type wrappers are transparent newtypes
649    #[expect(unsafe_code)]
650    unsafe {
651        std::slice::from_raw_parts_mut(values.as_mut_ptr().cast(), values.len())
652    }
653}
654
655const fn from_values<E: WasmEngine>(values: &[Value<E>]) -> &[Value<ReproducibleEngine<E>>] {
656    // Safety: all of our WASM runtime type wrappers are transparent newtypes
657    #[expect(unsafe_code)]
658    unsafe {
659        std::slice::from_raw_parts(values.as_ptr().cast(), values.len())
660    }
661}
662
663const fn from_values_mut<E: WasmEngine>(
664    values: &mut [Value<E>],
665) -> &mut [Value<ReproducibleEngine<E>>] {
666    // Safety: all of our WASM runtime type wrappers are transparent newtypes
667    #[expect(unsafe_code)]
668    unsafe {
669        std::slice::from_raw_parts_mut(values.as_mut_ptr().cast(), values.len())
670    }
671}
672
673fn into_value<E: WasmEngine>(value: Value<ReproducibleEngine<E>>) -> Value<E> {
674    match value {
675        Value::I32(v) => Value::I32(v),
676        Value::I64(v) => Value::I64(v),
677        Value::F32(v) => Value::F32(v),
678        Value::F64(v) => Value::F64(v),
679        Value::FuncRef(v) => Value::FuncRef(v.map(|v| v.0)),
680        Value::ExternRef(v) => Value::ExternRef(v.map(|v| v.0)),
681    }
682}
683
684fn from_value<E: WasmEngine>(value: Value<E>) -> Value<ReproducibleEngine<E>> {
685    match value {
686        Value::I32(v) => Value::I32(v),
687        Value::I64(v) => Value::I64(v),
688        Value::F32(v) => Value::F32(v),
689        Value::F64(v) => Value::F64(v),
690        Value::FuncRef(v) => Value::FuncRef(v.map(ReproducibleFunc)),
691        Value::ExternRef(v) => Value::ExternRef(v.map(ReproducibleExternRef)),
692    }
693}
694
695fn into_extern<E: WasmEngine>(value: Extern<ReproducibleEngine<E>>) -> Extern<E> {
696    match value {
697        Extern::Global(v) => Extern::Global(v.0),
698        Extern::Table(v) => Extern::Table(v.0),
699        Extern::Memory(v) => Extern::Memory(v.0),
700        Extern::Func(v) => Extern::Func(v.0),
701    }
702}
703
704fn from_extern<E: WasmEngine>(value: Extern<E>) -> Extern<ReproducibleEngine<E>> {
705    match value {
706        Extern::Global(v) => Extern::Global(ReproducibleGlobal(v)),
707        Extern::Table(v) => Extern::Table(ReproducibleTable(v)),
708        Extern::Memory(v) => Extern::Memory(ReproducibleMemory(v)),
709        Extern::Func(v) => Extern::Func(ReproducibleFunc(v)),
710    }
711}