susywasm/builder/
table.rs

1use std::vec::Vec;
2use elements;
3use super::invoke::{Invoke, Identity};
4
5/// Table definition
6#[derive(Debug, PartialEq)]
7pub struct TableDefinition {
8	/// Minimum length
9	pub min: u32,
10	/// Maximum length, if any
11	pub max: Option<u32>,
12	/// Element segments, if any
13	pub elements: Vec<TableEntryDefinition>,
14}
15
16/// Table elements entry definition
17#[derive(Debug, PartialEq)]
18pub struct TableEntryDefinition {
19	/// Offset initialization expression
20	pub offset: elements::InitExpr,
21	/// Values of initialization
22	pub values: Vec<u32>,
23}
24
25/// Table builder
26pub struct TableBuilder<F=Identity> {
27	callback: F,
28	table: TableDefinition,
29}
30
31impl TableBuilder {
32	/// New table builder
33	pub fn new() -> Self {
34		TableBuilder::with_callback(Identity)
35	}
36}
37
38impl<F> TableBuilder<F> where F: Invoke<TableDefinition> {
39	/// New table builder with callback in chained context
40	pub fn with_callback(callback: F) -> Self {
41		TableBuilder {
42			callback: callback,
43			table: Default::default(),
44		}
45	}
46
47	/// Set/override minimum length
48	pub fn with_min(mut self, min: u32) -> Self {
49		self.table.min = min;
50		self
51	}
52
53	/// Set/override maximum length
54	pub fn with_max(mut self, max: Option<u32>) -> Self {
55		self.table.max = max;
56		self
57	}
58
59	/// Generate initialization expression and element values on specified index
60	pub fn with_element(mut self, index: u32, values: Vec<u32>) -> Self {
61		self.table.elements.push(TableEntryDefinition {
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.table)
74	}
75}
76
77impl Default for TableDefinition {
78	fn default() -> Self {
79		TableDefinition {
80			min: 0,
81			max: None,
82			elements: Vec::new(),
83		}
84	}
85}