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
use prelude::{Vec, String, BTreeMap};
use value::Value;
use opcode::Opcode;
use bincode;
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct Module {
pub types: Vec<Type>,
pub functions: Vec<Function>,
pub data_segments: Vec<DataSegment>,
pub exports: BTreeMap<String, Export>,
pub tables: Vec<Table>,
pub globals: Vec<Global>,
pub natives: Vec<Native>,
pub start_function: Option<u32>
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Native {
pub module: String,
pub field: String,
pub typeidx: u32
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Global {
pub value: Value
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Table {
pub min: u32,
pub max: Option<u32>,
pub elements: Vec<Option<u32>>
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Export {
Function(u32)
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum Type {
Func(Vec<ValType>, Vec<ValType>)
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Function {
pub name: Option<String>,
pub typeidx: u32,
pub locals: Vec<ValType>,
pub body: FunctionBody
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FunctionBody {
pub opcodes: Vec<Opcode>
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DataSegment {
pub offset: u32,
pub data: Vec<u8>
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum ValType {
I32,
I64,
F32,
F64
}
impl Module {
pub fn std_serialize(&self) -> Result<Vec<u8>, String> {
match bincode::serialize(self) {
Ok(v) => Ok(v),
Err(e) => Err(format!("{:?}", e))
}
}
pub fn std_deserialize(data: &[u8]) -> Result<Module, String> {
match bincode::deserialize(data) {
Ok(v) => Ok(v),
Err(e) => Err(format!("{:?}", e))
}
}
pub fn lookup_exported_func(&self, name: &str) -> Option<usize> {
match self.exports.get(name) {
Some(v) => match *v {
Export::Function(id) => Some(id as usize)
},
None => None
}
}
}