-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathiohelpers.lua
49 lines (32 loc) · 1018 Bytes
/
iohelpers.lua
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
ioh = { }
local function read_bytes(f, c, d)
local s = (d < 0) and c or 1
local e = (d < 0) and 1 or c
local buf = f:read(c)
if (not buf) or (buf:len() ~= c) then return nil end
local r = 0
for x = s, e, d do
r = r * 256
r = r + buf:byte(x)
end
return r
end
local function write_bytes(f, n, c, d)
local s = (d < 0) and c or 1
local e = (d < 0) and 1 or c
local buf = ""
for x = s, e, d do
local ch = (n % 256)
buf = buf..string.char(ch)
n = (n - ch) / 256
end
f:write(buf)
end
function ioh.read_int16_le(f) return read_bytes(f, 2, -1) end
function ioh.read_int32_le(f) return read_bytes(f, 4, -1) end
function ioh.read_int16_be(f) return read_bytes(f, 2, 1) end
function ioh.read_int32_be(f) return read_bytes(f, 4, 1) end
function ioh.write_int16_le(f, n) write_bytes(f, n, 2, -1) end
function ioh.write_int32_le(f, n) write_bytes(f, n, 4, -1) end
function ioh.write_int16_be(f, n) write_bytes(f, n, 2, 1) end
function ioh.write_int32_be(f, n) write_bytes(f, n, 4, 1) end