Advertisement
osmarks

PaintEncode

Sep 29th, 2018
2,429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.72 KB | None | 0 0
  1. local function chars(str)
  2.     local pos = 1
  3.     return function()
  4.         if pos <= #str  then
  5.             local pos_was = pos
  6.             pos = pos + 1
  7.             return str:sub(pos_was, pos_was), pos_was
  8.         end
  9.     end
  10. end
  11.  
  12. local function nybbles(byte)
  13.     return bit.brshift(bit.band(0xF0, byte), 4), bit.band(0x0F, byte)
  14. end
  15.  
  16. local function from_nybbles(hi, lo)
  17.     return bit.bor(bit.blshift(hi, 4), lo)
  18. end
  19.  
  20. local hexToColor = {}
  21. for n = 0, 15 do
  22.     hexToColor[string.format("%x", n)] = 2 ^ n
  23. end
  24.  
  25. local function log2(x)
  26.     return math.log10(x) / math.log10(2)
  27. end
  28.  
  29. local function decode_col(c)
  30.     return log2(hexToColor[c] or 1)
  31. end
  32.  
  33. local function split_pair(pair)
  34.     return pair:sub(1, 1), pair:sub(2, 2)
  35. end
  36.  
  37. local paint_encode = {}
  38.  
  39. local function groups(str, l)
  40.     local out, current = {}
  41.     local pos = 1
  42.     repeat
  43.         current = str:sub(pos, pos + l - 1)
  44.         pos = pos + l
  45.         table.insert(out, current)
  46.     until current == ""
  47.     return out
  48. end
  49.  
  50. function paint_encode.encode(str)
  51.     local cols = ""
  52.     for c in chars(str) do
  53.         cols = cols .. string.format("%02x", string.byte(c))
  54.     end
  55.     local line_qty = math.sqrt(#cols)
  56.     return table.concat(groups(cols, line_qty), "\n")
  57. end
  58.  
  59. function paint_encode.decode(str)
  60.     local outstr = ""
  61.     for pair in str:gsub("\n", ""):gmatch("..") do
  62.         local fst, snd = split_pair(pair)
  63.         outstr = outstr .. string.char(from_nybbles(decode_col(fst), decode_col(snd)))
  64.     end
  65.     return outstr
  66. end
  67.  
  68. function paint_encode.read(file)
  69.     local f = fs.open(file, "r")
  70.     local out = paint_encode.decode(f.readAll())
  71.     f.close()
  72.     return out
  73. end
  74.  
  75. function paint_encode.write(file, str)
  76.     local f = fs.open(file, "w")
  77.     f.write(paint_encode.encode(str))
  78.     f.close()
  79. end
  80.  
  81. return paint_encode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement