Advertisement
MeXaN1cK

LZ78

Mar 7th, 2017
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.14 KB | None | 0 0
  1. local trm = require("term")
  2. local shl = require("shell")
  3. local fls = require("filesystem")
  4. local b32 = require("bit32")
  5. local args = shl.parse(...)
  6.  
  7. VALUE = 0 LEN = 0
  8. function AddBite(value, len)
  9.   VALUE = b32.lshift(VALUE, len) + value
  10.   LEN = LEN + len
  11.   while LEN > 7 do
  12.     file:write(string.char(b32.rshift(VALUE, LEN - 8)))
  13.     VALUE = VALUE % (2 ^ (LEN - 8))
  14.     LEN = LEN - 8
  15.   end
  16. end
  17.  
  18. function deflate()
  19.   file = io.open(args[1], "rb")
  20.   if file == nil then trm.write("file "..args[1].." not found") os.exit()
  21.   end
  22.   STR = file:read("*a")
  23.   file:close()
  24.  
  25.   local dict = {[""] = 0}
  26.   local DLEN = 1
  27.   local word = ""
  28.  
  29.   file = io.open(args[2], "wb")  
  30.   if file == nil then trm.write("file "..args[2].." already in use") os.exit()
  31.   end
  32.   for i=1, #STR do
  33.     word = word..STR:sub(i, i)
  34.     if dict[word] == nil then
  35.       AddBite(dict[word:sub(1, -2)], math.ceil(math.log(DLEN+1, 2)))
  36.       AddBite(word:byte(-1), 8)
  37.       dict[word] = DLEN DLEN = DLEN + 1
  38.       word = ""
  39.     end
  40.   end
  41.   if word ~= "" then
  42.     AddBite(dict[word], math.ceil(math.log(DLEN+1, 2)))
  43.   end
  44.   if LEN ~= 0 then
  45.     file:write(string.char(b32.lshift(VALUE, 8 - LEN)))
  46.   end  
  47.   file:close()
  48. end
  49.  
  50. function PutBite(len)
  51.   while LEN < len do
  52.     if POS > #STR1 then return false
  53.     end
  54.     VALUE = VALUE * 256 + STR1:byte(POS)
  55.     POS = POS + 1
  56.     LEN = LEN + 8
  57.   end
  58.   LEN = LEN - len
  59.   local tmp = b32.rshift(VALUE, LEN)
  60.   VALUE = VALUE % (2 ^ LEN)
  61.   return tmp
  62. end
  63.  
  64.  
  65. function inflate()
  66.   file = io.open(args[2], "rb")
  67.   if file == nil then trm.write("file "..args[2].." file no found") os.exit()
  68.   end
  69.   STR1 = file:read("*a")
  70.   file:close()
  71.   LEN = 0
  72.   POS = 1
  73.   VALUE = 0
  74.   local dict = {[0] = ""}
  75.   local DLE = 1
  76.   OUT = ""
  77.   while true do
  78.     local TEMP = PutBite(math.ceil(math.log(DLE+1, 2)))
  79.     local symbol = PutBite(8)
  80.     if TEMP == false then break
  81.     end
  82.     if symbol == false then
  83.       OUT = OUT..dict[TEMP]
  84.       break
  85.     else
  86.       symbol = string.char(symbol)
  87.       OUT = OUT..dict[TEMP]..symbol
  88.       dict[DLE] = dict[TEMP]..symbol DLE = DLE + 1
  89.     end
  90.   end
  91. end
  92.  
  93. deflate()
  94. inflate()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement