near_vm_types/
initializers.rs

1use crate::indexes::{FunctionIndex, GlobalIndex, MemoryIndex, TableIndex};
2use crate::lib::std::boxed::Box;
3
4/// A WebAssembly table initializer.
5#[derive(Clone, Debug, Hash, PartialEq, Eq, rkyv::Serialize, rkyv::Deserialize, rkyv::Archive)]
6pub struct OwnedTableInitializer {
7    /// The index of a table to initialize.
8    pub table_index: TableIndex,
9    /// Optionally, a global variable giving a base index.
10    pub base: Option<GlobalIndex>,
11    /// The offset to add to the base.
12    pub offset: usize,
13    /// The values to write into the table elements.
14    pub elements: Box<[FunctionIndex]>,
15}
16
17/// A memory index and offset within that memory where a data initialization
18/// should be performed.
19#[derive(Clone, Debug, PartialEq, Eq, rkyv::Serialize, rkyv::Deserialize, rkyv::Archive)]
20pub struct DataInitializerLocation {
21    /// The index of the memory to initialize.
22    pub memory_index: MemoryIndex,
23
24    /// Optionally a Global variable base to initialize at.
25    pub base: Option<GlobalIndex>,
26
27    /// A constant offset to initialize at.
28    pub offset: usize,
29}
30
31/// A data initializer for linear memory.
32#[derive(Debug)]
33pub struct DataInitializer<'data> {
34    /// The location where the initialization is to be performed.
35    pub location: DataInitializerLocation,
36
37    /// The initialization data.
38    pub data: &'data [u8],
39}
40
41/// As `DataInitializer` but owning the data rather than
42/// holding a reference to it
43#[derive(Debug, Clone, PartialEq, Eq, rkyv::Serialize, rkyv::Deserialize, rkyv::Archive)]
44pub struct OwnedDataInitializer {
45    /// The location where the initialization is to be performed.
46    pub location: DataInitializerLocation,
47
48    /// The initialization owned data.
49    pub data: Vec<u8>,
50}
51
52impl OwnedDataInitializer {
53    /// Creates a new `OwnedDataInitializer` from a `DataInitializer`.
54    pub fn new(borrowed: &DataInitializer<'_>) -> Self {
55        Self { location: borrowed.location.clone(), data: borrowed.data.to_vec() }
56    }
57}
58
59impl<'a> From<&'a OwnedDataInitializer> for DataInitializer<'a> {
60    fn from(init: &'a OwnedDataInitializer) -> Self {
61        DataInitializer { location: init.location.clone(), data: &*init.data }
62    }
63}
64
65impl<'a> From<&'a ArchivedOwnedDataInitializer> for DataInitializer<'a> {
66    fn from(init: &'a ArchivedOwnedDataInitializer) -> Self {
67        DataInitializer {
68            location: rkyv::rancor::ResultExt::<_, rkyv::rancor::Panic>::always_ok(
69                rkyv::api::deserialize_using(&init.location, &mut ()),
70            ),
71            data: &*init.data,
72        }
73    }
74}
75
76impl<'a> From<DataInitializer<'a>> for OwnedDataInitializer {
77    fn from(init: DataInitializer<'a>) -> Self {
78        Self { location: init.location.clone(), data: init.data.to_vec() }
79    }
80}