OC-PsychOS/modules/lib/cdlib.lua

32 lines
1.0 KiB
Lua

-- cdlib by t20kdc, from https://github.com/20kdc/OC-Copper/blob/master/cdlib.lua
-- modified for PsychOS by Izaya
_G.cdlib = {}
function cdlib.encodeName(name)
if name:len() > 256 then error("Bad name (l>256)") end
if name == "" then error("No name") end
return string.char(name:len() - 1) .. name
end
function cdlib.decodeName(message)
if message:len() < 2 then return end
local nlen = message:byte(1) + 1
local fnam = message:sub(2, nlen + 1)
if fnam:len() < nlen then return end
return fnam, message:sub(nlen + 2)
end
function cdlib.decodeNoHops(data)
local src, data = cdlib.decodeName(data)
if not src then return end
local dst, data = cdlib.decodeName(data)
if not dst then return end
return src, dst, data
end
function cdlib.encode(hops, src, dst, data)
return string.char(hops) .. cdlib.encodeName(src) .. cdlib.encodeName(dst) .. data
end
function cdlib.decode(d)
if d:len() < 3 then return end
local src, dst, data = cdlib.decodeNoHops(d:sub(2))
if not data then return end
return d:byte(1), src, dst, data
end