parity_wasm/builder/
table.rs

1use super::invoke::{Identity, Invoke};
2use crate::elements;
3use alloc::vec::Vec;
4
5/// Table definition
6#[derive(Debug, PartialEq, Default)]
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 Default for TableBuilder {
39	fn default() -> Self {
40		Self::new()
41	}
42}
43
44impl<F> TableBuilder<F>
45where
46	F: Invoke<TableDefinition>,
47{
48	/// New table builder with callback in chained context
49	pub fn with_callback(callback: F) -> Self {
50		TableBuilder { callback, table: Default::default() }
51	}
52
53	/// Set/override minimum length
54	pub fn with_min(mut self, min: u32) -> Self {
55		self.table.min = min;
56		self
57	}
58
59	/// Set/override maximum length
60	pub fn with_max(mut self, max: Option<u32>) -> Self {
61		self.table.max = max;
62		self
63	}
64
65	/// Generate initialization expression and element values on specified index
66	pub fn with_element(mut self, index: u32, values: Vec<u32>) -> Self {
67		self.table.elements.push(TableEntryDefinition {
68			offset: elements::InitExpr::new(vec![
69				elements::Instruction::I32Const(index as i32),
70				elements::Instruction::End,
71			]),
72			values,
73		});
74		self
75	}
76
77	/// Finalize current builder spawning resulting struct
78	pub fn build(self) -> F::Result {
79		self.callback.invoke(self.table)
80	}
81}