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 ) -- generate a header for file *fname* when provided with file length *len*
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
2020-05-30 09:51:47 +10:00
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