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
use crate::map::IdHashMap;
use crate::{DataId, ElementId, Function, FunctionId, GlobalId, Result};
use crate::{LocalId, MemoryId, TableId, TypeId};
use failure::bail;
#[derive(Debug, Default)]
pub struct IndicesToIds {
tables: Vec<TableId>,
types: Vec<TypeId>,
funcs: Vec<FunctionId>,
globals: Vec<GlobalId>,
memories: Vec<MemoryId>,
elements: Vec<ElementId>,
data: Vec<DataId>,
locals: IdHashMap<Function, Vec<LocalId>>,
}
macro_rules! define_push_get {
( $push:ident, $get:ident, $id_ty:ty, $member:ident ) => {
impl IndicesToIds {
pub(crate) fn $push(&mut self, id: $id_ty) -> u32 {
self.$member.push(id);
(self.$member.len() - 1) as u32
}
pub fn $get(&self, index: u32) -> Result<$id_ty> {
match self.$member.get(index as usize) {
Some(x) => Ok(*x),
None => bail!(
"index `{}` is out of bounds for {}",
index,
stringify!($member)
),
}
}
}
};
}
define_push_get!(push_table, get_table, TableId, tables);
define_push_get!(push_type, get_type, TypeId, types);
define_push_get!(push_func, get_func, FunctionId, funcs);
define_push_get!(push_global, get_global, GlobalId, globals);
define_push_get!(push_memory, get_memory, MemoryId, memories);
define_push_get!(push_data, get_data, DataId, data);
impl IndicesToIds {
pub(crate) fn push_local(&mut self, function: FunctionId, id: LocalId) -> u32 {
let list = self.locals.entry(function).or_insert(Vec::new());
list.push(id);
(list.len() as u32) - 1
}
pub fn get_local(&self, function: FunctionId, index: u32) -> Result<LocalId> {
let ret = self
.locals
.get(&function)
.and_then(|list| list.get(index as usize));
match ret {
Some(x) => Ok(*x),
None => bail!("index `{}` is out of bounds for local", index,),
}
}
}