2020-06-05 12:10:48 +10:00
local mtar = { }
local function cleanPath ( path )
local pt = { }
for segment in path : gmatch ( " [^/]+ " ) do
if segment == " .. " then
pt [ # pt ] = nil
elseif segment ~= " . " then
pt [ # pt + 1 ] = segment
end
end
return table.concat ( pt , " / " )
end
2020-06-25 09:39:31 +10:00
function mtar . genHeader ( fname , len ) -- string number -- string -- generate a header for file *fname* when provided with file length *len*
2021-05-26 16:15:24 +10:00
return string.format ( " %s%s%s " , string.pack ( " >I2 " , fname : len ( ) ) , fname , string.pack ( " >I2 " , len ) )
2020-06-05 12:10:48 +10:00
end
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 ( )
2020-07-13 00:58:19 +10:00
while remain > 0 do
remain = remain -# stream : read ( math.min ( remain , 2048 ) )
end
2021-05-26 16:15:24 +10:00
local nlen = string.unpack ( " >I2 " , stream : read ( 2 ) or " \0 \0 " )
2020-06-05 12:10:48 +10:00
if nlen == 0 then
return
end
local name = cleanPath ( stream : read ( nlen ) )
2021-05-26 16:15:24 +10:00
local fsize = string.unpack ( " >I2 " , stream : read ( 2 ) )
2020-06-05 12:10:48 +10:00
remain = fsize
return name , read , fsize
end
end
return mtar