linera_witty/runtime/wasmtime/
memory.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How to access the memory of a Wasmtime guest instance.
5
6use std::borrow::Cow;
7
8use wasmtime::{Extern, Memory};
9
10use super::{super::traits::InstanceWithMemory, EntrypointInstance, ReentrantInstance};
11use crate::{GuestPointer, RuntimeError, RuntimeMemory};
12
13macro_rules! impl_memory_traits {
14    ($instance:ty) => {
15        impl<UserData> InstanceWithMemory for $instance {
16            fn memory_from_export(&self, export: Extern) -> Result<Option<Memory>, RuntimeError> {
17                Ok(match export {
18                    Extern::Memory(memory) => Some(memory),
19                    _ => None,
20                })
21            }
22        }
23
24        impl<UserData> RuntimeMemory<$instance> for Memory {
25            fn read<'instance>(
26                &self,
27                instance: &'instance $instance,
28                location: GuestPointer,
29                length: u32,
30            ) -> Result<Cow<'instance, [u8]>, RuntimeError> {
31                let start = location.0 as usize;
32                let end = start + length as usize;
33
34                Ok(Cow::Borrowed(&self.data(instance)[start..end]))
35            }
36
37            fn write(
38                &mut self,
39                instance: &mut $instance,
40                location: GuestPointer,
41                bytes: &[u8],
42            ) -> Result<(), RuntimeError> {
43                let start = location.0 as usize;
44                let end = start + bytes.len();
45
46                self.data_mut(instance)[start..end].copy_from_slice(bytes);
47
48                Ok(())
49            }
50        }
51    };
52}
53
54impl_memory_traits!(EntrypointInstance<UserData>);
55impl_memory_traits!(ReentrantInstance<'_, UserData>);