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