parity_wasm/builder/
global.rs1use super::{
2 invoke::{Identity, Invoke},
3 misc::ValueTypeBuilder,
4};
5
6use crate::elements;
7
8pub struct GlobalBuilder<F = Identity> {
10 callback: F,
11 value_type: elements::ValueType,
12 is_mutable: bool,
13 init_expr: elements::InitExpr,
14}
15
16impl GlobalBuilder {
17 pub fn new() -> Self {
19 GlobalBuilder::with_callback(Identity)
20 }
21}
22
23impl Default for GlobalBuilder {
24 fn default() -> Self {
25 Self::new()
26 }
27}
28
29impl<F> GlobalBuilder<F> {
30 pub fn with_callback(callback: F) -> Self {
32 GlobalBuilder {
33 callback,
34 value_type: elements::ValueType::I32,
35 init_expr: elements::InitExpr::empty(),
36 is_mutable: false,
37 }
38 }
39
40 pub fn with_type(mut self, value_type: elements::ValueType) -> Self {
42 self.value_type = value_type;
43 self
44 }
45
46 pub fn mutable(mut self) -> Self {
48 self.is_mutable = true;
49 self
50 }
51
52 pub fn init_expr(mut self, instruction: elements::Instruction) -> Self {
54 self.init_expr = elements::InitExpr::new(vec![instruction, elements::Instruction::End]);
55 self
56 }
57
58 pub fn value_type(self) -> ValueTypeBuilder<Self> {
60 ValueTypeBuilder::with_callback(self)
61 }
62}
63
64impl<F> GlobalBuilder<F>
65where
66 F: Invoke<elements::GlobalEntry>,
67{
68 pub fn build(self) -> F::Result {
70 self.callback.invoke(elements::GlobalEntry::new(
71 elements::GlobalType::new(self.value_type, self.is_mutable),
72 self.init_expr,
73 ))
74 }
75}
76
77impl<F> Invoke<elements::ValueType> for GlobalBuilder<F> {
78 type Result = Self;
79 fn invoke(self, the_type: elements::ValueType) -> Self {
80 self.with_type(the_type)
81 }
82}
83
84pub fn global() -> GlobalBuilder {
86 GlobalBuilder::new()
87}
88
89#[cfg(test)]
90mod tests {
91 use super::global;
92 use crate::elements;
93
94 #[test]
95 fn example() {
96 let entry = global().value_type().i32().build();
97 assert_eq!(entry.global_type().content_type(), elements::ValueType::I32);
98 assert!(!entry.global_type().is_mutable());
99 }
100}