Skip to content

Commit 8b091d6

Browse files
committed
Replace malloc/free calls in bytecode generator with ffi.new and copy
1 parent 665319b commit 8b091d6

File tree

1 file changed

+12
-25
lines changed

1 file changed

+12
-25
lines changed

lang/bytecode.lua

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -187,43 +187,32 @@ local FOR_GEN = "(for generator)";
187187
local FOR_STATE = "(for state)";
188188
local FOR_CTL = "(for control)";
189189

190-
ffi.cdef[[
191-
void *malloc(size_t);
192-
void *realloc(void*, size_t);
193-
int free(void*);
194-
195-
typedef struct Buf {
196-
unsigned int size;
197-
unsigned int offs;
198-
uint8_t *data;
199-
} Buf;
200-
]]
201-
202190
local function num_is_int32(x)
203191
return x % 1 == 0 and x >= -2^31 and x < 2^31
204192
end
205193

206194
Buf = {}
207195
Buf.new = function(size)
208-
if not size then
209-
size = 2048
210-
end
211-
local self = ffi.new('Buf', size)
212-
self.data = ffi.C.malloc(size)
213-
self.offs = 0
214-
return self
215-
end
216-
Buf.__gc = function(self)
217-
ffi.C.free(self.data)
196+
size = size or 2048
197+
local self = {
198+
data = ffi.new('char[?]', size),
199+
size = size,
200+
offs = 0,
201+
}
202+
return setmetatable(self, Buf)
218203
end
204+
219205
Buf.__index = {}
220206
Buf.__index.need = function(self, size)
221207
local need_size = self.offs + size
222208
if self.size <= need_size then
209+
local prev_size = self.size
223210
while self.size <= need_size do
224211
self.size = self.size * 2
225212
end
226-
self.data = ffi.C.realloc(ffi.cast('void*', self.data), self.size)
213+
local new_data = ffi.new('char[?]', self.size)
214+
ffi.copy(new_data, self.data, prev_size)
215+
self.data = new_data
227216
end
228217
end
229218
Buf.__index.put = function(self, v)
@@ -332,8 +321,6 @@ Buf.__index.put_number = function(self, v)
332321
return offs
333322
end
334323

335-
ffi.metatype('Buf', Buf)
336-
337324
Ins = {}
338325
Ins.__index = {}
339326
function Ins.new(op, a, b, c)

0 commit comments

Comments
 (0)