quick and dirty pure lua webassembly interpreter
1local intutil = {}
2
3function intutil.fromle16(tab, idx)
4 local n = tab[idx]
5 n = n | tab[idx+1] << 8
6 return n
7end
8
9function intutil.tole16(tab, idx, n)
10 tab[idx] = n & 0xFF
11 tab[idx+1] = (n >> 8) & 0xFF
12end
13
14function intutil.fromle32(tab, idx)
15 local n = tab[idx]
16 n = n | tab[idx+1] << 8
17 n = n | tab[idx+2] << 16
18 n = n | tab[idx+3] << 24
19 return n
20end
21
22function intutil.tole32(tab, idx, n)
23 tab[idx] = n & 0xFF
24 tab[idx+1] = (n >> 8) & 0xFF
25 tab[idx+2] = (n >> 16) & 0xFF
26 tab[idx+3] = (n >> 24) & 0xFF
27end
28
29function intutil.fromle64(tab, idx)
30 local n = tab[idx]
31 n = n | tab[idx+1] << 8
32 n = n | tab[idx+2] << 16
33 n = n | tab[idx+3] << 24
34 n = n | tab[idx+4] << 32
35 n = n | tab[idx+5] << 40
36 n = n | tab[idx+6] << 48
37 n = n | tab[idx+7] << 56
38 return n
39end
40
41function intutil.tole64(tab, idx, n)
42 tab[idx] = n & 0xFF
43 tab[idx+1] = (n >> 8) & 0xFF
44 tab[idx+2] = (n >> 16) & 0xFF
45 tab[idx+3] = (n >> 24) & 0xFF
46 tab[idx+4] = (n >> 32) & 0xFF
47 tab[idx+5] = (n >> 40) & 0xFF
48 tab[idx+6] = (n >> 48) & 0xFF
49 tab[idx+7] = (n >> 56) & 0xFF
50end
51
52function intutil.signexti32(n)
53 if (n & 0x80000000) ~= 0 then
54 n = n | 0xFFFFFFFF00000000
55 end
56 return n
57end
58
59function intutil.signexti16(n)
60 if (n & 0x8000) ~= 0 then
61 n = n | 0xFFFFFFFFFFFF0000
62 end
63 return n
64end
65
66function intutil.signexti8(n)
67 if (n & 0x80) ~= 0 then
68 n = n | 0xFFFFFFFFFFFFFF00
69 end
70 return n
71end
72
73function intutil.fromuleb128(tab, idx)
74 local result = 0
75 local shift = 0
76 local len = 0
77 repeat
78 local byte = tab[idx+len]
79 result = result | ((byte & 0x7F) << shift)
80 shift = shift + 7
81 len = len + 1
82 until (byte & 0x80) == 0
83 return len, result
84end
85
86function intutil.fromsleb128(tab, idx, bits)
87 bits = bits or 64
88 local result = 0
89 local shift = 0
90 local len = 0
91
92 repeat
93 local byte = tab[idx+len]
94 result = result | ((byte & 0x7F) << shift)
95 shift = shift + 7
96 len = len + 1
97 until (byte & 0x80) == 0
98
99 if (shift < bits) and ((tab[idx+len-1] & 0x40) ~= 0) then
100 result = result | (((1 << bits) - 1) << shift)
101 end
102 return len, result & ((1 << bits) - 1)
103end
104
105return intutil