OC-misc/mtar/libmtar.lua

47 lines
1.1 KiB
Lua
Raw Normal View History

2020-03-04 15:26:49 +11:00
local mtar = {}
local function toint(s)
local n = 0
local i = 1
2020-03-06 22:10:16 +11:00
for p in s:gmatch(".") do
2020-03-04 15:26:49 +11:00
n = n << 8
2020-03-06 22:10:16 +11:00
n = n | string.byte(p)
2020-03-04 15:26:49 +11:00
i=i+1
end
return n
end
local function cint(n,l)
local t={}
for i = 0, 7 do
t[i+1] = (n >> (i * 8)) & 0xFF
end
return string.reverse(string.char(table.unpack(t)):sub(1,l))
end
function mtar.genHeader(fname,len) -- string number -- string -- Generates an mtar file header for a file called *name* that is *len* bytes long.
2020-03-04 15:26:49 +11:00
return string.format("%s%s%s",cint(fname:len(),2),fname,cint(len,2))
end
2020-05-29 10:54:00 +10:00
function mtar.iter(stream) -- table -- function -- Given buffer *stream*, returns an iterator suitable for use with *for* that returns, for each iteration, the file name, a function to read from the file, and the length of the file.
local remain = 0
local function read(n)
local rb = stream:read(math.min(n,remain))
remain = remain - rb:len()
return rb
end
return function()
stream:read(remain)
local nlen = toint(stream:read(2) or "\0\0")
if nlen == 0 then
return
end
local name = stream:read(nlen)
2020-05-29 10:54:00 +10:00
local fsize = toint(stream:read(2))
remain = fsize
return name, read, fsize
end
end
2020-03-04 15:26:49 +11:00
return mtar