Operating system for OpenComputers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.2KB

  1. local mtar = {}
  2. local function cleanPath(path)
  3. local pt = {}
  4. for segment in path:gmatch("[^/]+") do
  5. if segment == ".." then
  6. pt[#pt] = nil
  7. elseif segment ~= "." then
  8. pt[#pt+1] = segment
  9. end
  10. end
  11. return table.concat(pt,"/")
  12. end
  13. function mtar.genHeader(fname,len) -- string number -- string -- generate a header for file *fname* when provided with file length *len*
  14. return string.format("%s%s%s", string.pack(">I2",fname:len()), fname, string.pack(">I2",len))
  15. end
  16. 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.
  17. local remain = 0
  18. local function read(n)
  19. local rb = stream:read(math.min(n,remain))
  20. remain = remain - rb:len()
  21. return rb
  22. end
  23. return function()
  24. while remain > 0 do
  25. remain=remain-#stream:read(math.min(remain,2048))
  26. end
  27. local nlen = string.unpack(">I2", stream:read(2) or "\0\0")
  28. if nlen == 0 then
  29. return
  30. end
  31. local name = cleanPath(stream:read(nlen))
  32. local fsize = string.unpack(">I2", stream:read(2))
  33. remain = fsize
  34. return name, read, fsize
  35. end
  36. end
  37. return mtar