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.

54 lines
1.2KB

  1. local lz = require "lzss"
  2. local buffer = require "buffer"
  3. lz16 = {}
  4. local function readBuffer(fi)
  5. local stream = {}
  6. if fi:read(4) ~= "lz16" then
  7. return false, "not an lz16 archive"
  8. end
  9. function stream.read()
  10. local len = string.unpack(">I2", fi:read(2) or "\0\0")
  11. if len < 1 then
  12. return nil
  13. end
  14. if os.sleep then os.sleep(0) else coroutine.yield() end
  15. return lz.decompress(fi:read(len))
  16. end
  17. function stream.close()
  18. fi:close()
  19. end
  20. return buffer.new("rb",stream)
  21. end
  22. local function writeBuffer(fo)
  23. local stream = {}
  24. function stream:write(data)
  25. local cblock = lz.compress(data)
  26. fo:write(string.pack(">I2", cblock:len()) .. cblock)
  27. return cblock:len()+2
  28. end
  29. function stream.close()
  30. fo:close()
  31. end
  32. fo:write("lz16") -- write header
  33. return buffer.new("wb",stream)
  34. end
  35. function lz16.buffer(stream) -- table -- table -- Wrap a stream to read or write LZ16.
  36. if stream.mode.w then
  37. return writeBuffer(stream)
  38. end
  39. return readBuffer(stream)
  40. end
  41. function lz16.open(fname, mode) -- string string -- table -- Open file *fname* to read or write LZ16-compressed data depending on *mode*
  42. local f = io.open(fname, mode)
  43. if not f then return false end
  44. f.mode.b = true
  45. return lz16.buffer(f)
  46. end
  47. return lz16