tetsy_wasm/builder/
memory.rs

1use alloc::vec::Vec;
2use crate::elements;
3use super::invoke::{Invoke, Identity};
4
5/// Memory definition struct
6#[derive(Debug, PartialEq)]
7pub struct MemoryDefinition {
8	/// Minimum memory size
9	pub min: u32,
10	/// Maximum memory size
11	pub max: Option<u32>,
12	/// Memory data segments (static regions)
13	pub data: Vec<MemoryDataDefinition>,
14}
15
16/// Memory static region entry definition
17#[derive(Debug, PartialEq)]
18pub struct MemoryDataDefinition {
19	/// Segment initialization expression for offset
20	pub offset: elements::InitExpr,
21	/// Raw bytes of static region
22	pub values: Vec<u8>,
23}
24
25/// Memory and static regions builder
26pub struct MemoryBuilder<F=Identity> {
27	callback: F,
28	memory: MemoryDefinition,
29}
30
31impl MemoryBuilder {
32	/// New memory builder
33	pub fn new() -> Self {
34		MemoryBuilder::with_callback(Identity)
35	}
36}
37
38impl<F> MemoryBuilder<F> where F: Invoke<MemoryDefinition> {
39	/// New memory builder with callback (in chained context)
40	pub fn with_callback(callback: F) -> Self {
41		MemoryBuilder {
42			callback: callback,
43			memory: Default::default(),
44		}
45	}
46
47	/// Set/override minimum size
48	pub fn with_min(mut self, min: u32) -> Self {
49		self.memory.min = min;
50		self
51	}
52
53	/// Set/override maximum size
54	pub fn with_max(mut self, max: Option<u32>) -> Self {
55		self.memory.max = max;
56		self
57	}
58
59	/// Push new static region with initialized offset expression and raw bytes
60	pub fn with_data(mut self, index: u32, values: Vec<u8>) -> Self {
61		self.memory.data.push(MemoryDataDefinition {
62			offset: elements::InitExpr::new(vec![
63				elements::Instruction::I32Const(index as i32),
64				elements::Instruction::End,
65			]),
66			values: values,
67		});
68		self
69	}
70
71	/// Finalize current builder, spawning resulting struct
72	pub fn build(self) -> F::Result {
73		self.callback.invoke(self.memory)
74	}
75}
76
77impl Default for MemoryDefinition {
78	fn default() -> Self {
79		MemoryDefinition {
80			min: 1,
81			max: None,
82			data: Vec::new(),
83		}
84	}
85}