Advertisement
osmarks

libdatatape

Aug 17th, 2018
2,652
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.88 KB | None | 0 0
  1. local ser = require "ser"
  2. if not ser then
  3.     -- Download random library squid recommended
  4. local function a(b,c)local d=fs.open(b,"w")d.write(c)d.close()end;local function e(b)local d=fs.open(b,"r")local c=d.readAll()d.close()return c end;local function f(g)local h=http.get(g)local c=h.readAll()h.close()return c end;local function i(g,d)a(d,f(g))end;i("https://pastebin.com/raw/KXHSsHkt","ser")
  5. end
  6.  
  7. local function move_to_start(tape)
  8.     tape.seek(-tape.getSize())
  9. end
  10.  
  11. local function get_byte(num, byte)
  12.     return bit.band(bit.brshift(num, byte * 8), 0xFF)
  13. end
  14.  
  15. local function from_bytes(b)
  16.     local n = 0
  17.     for ix, byte in pairs(b) do
  18.         n = bit.bor(n, bit.blshift(byte, (ix - 1) * 8))
  19.     end
  20.     return n
  21. end
  22.  
  23. local function write_string(tape, str, ignore_out_of_space)
  24.     if tape.getSize() < (#str + 4) and not ignore_out_of_space then
  25.         return false, "Not enough space"
  26.     end
  27.  
  28.     move_to_start(tape)
  29.  
  30.     tape.write(get_byte(#str, 0))
  31.     tape.write(get_byte(#str, 1))
  32.     tape.write(get_byte(#str, 2))
  33.     tape.write(get_byte(#str, 3))
  34.  
  35.     return tape.write(str)
  36. end
  37.  
  38. local function read_string(tape)
  39.     move_to_start(tape)
  40.  
  41.     local data_length = from_bytes {tape.read(), tape.read(), tape.read(), tape.read()}
  42.     local data_remaining = data_length
  43.  
  44.     if data_length > (tape.getSize() - 4) then
  45.         return false, "Invalid data length."
  46.     end
  47.  
  48.     local data = ""
  49.  
  50.     repeat
  51.         local block = tape.read(256)
  52.         block = block:sub(1, data_remaining)
  53.         data_remaining = data_remaining - #block
  54.         data = data .. block -- for some reason, only 256 chars at once can be read?
  55.         sleep()
  56.     until data_remaining == 0
  57.  
  58.     return data
  59. end
  60.  
  61. local function write(tape, dat, ignore_out_of_space)
  62.     return write_string(tape, ser.serialize(dat), ignore_out_of_space)
  63. end
  64.  
  65. local function read(tape)
  66.     return ser.deserialize(read_string(tape))
  67. end
  68.  
  69. return { read_string = read_string, read = read, write_string = write_string, write = write }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement