mirror of
https://github.com/ShadowKatStudios/OC-Minitel.git
synced 2024-11-08 19:38:06 +11:00
62 lines
1.4 KiB
Lua
62 lines
1.4 KiB
Lua
local imt = {}
|
|
|
|
imt.ttypes = {}
|
|
imt.ttypes.string=1
|
|
imt.ttypes.number=2
|
|
|
|
imt.ftypes = {tostring,tonumber}
|
|
|
|
function imt.to16bn(n)
|
|
return string.char(math.floor(n/256))..string.char(math.floor(n%256))
|
|
end
|
|
function imt.from16bn(s)
|
|
return (string.byte(s,1,1)*256)+string.byte(s,2,2)
|
|
end
|
|
|
|
function imt.encodePacket(...)
|
|
local tArgs = {...}
|
|
local packet = string.char(#tArgs%256)
|
|
for _,segment in ipairs(tArgs) do
|
|
local segtype = type(segment)
|
|
segment = tostring(segment)
|
|
packet = packet .. imt.to16bn(segment:len()) .. string.char(imt.ttypes[segtype]) .. tostring(segment)
|
|
end
|
|
packet = imt.to16bn(packet:len()) .. packet
|
|
return packet
|
|
end
|
|
|
|
function imt.decodePacket(s)
|
|
local function getfirst(n)
|
|
local ns = s:sub(1,n)
|
|
s=s:sub(n+1)
|
|
return ns
|
|
end
|
|
local plen = imt.from16bn(getfirst(2))
|
|
if s:len() < plen then return false end
|
|
local nsegments = string.byte(getfirst(1))
|
|
local tsegments = {}
|
|
for i = 1, nsegments do
|
|
if s:len() < 1 then return false end
|
|
local seglen = imt.from16bn(getfirst(2))
|
|
local segtype = string.byte(getfirst(1))
|
|
local tempseg = getfirst(seglen)
|
|
tsegments[#tsegments+1] = imt.ftypes[segtype](tempseg)
|
|
end
|
|
return table.unpack(tsegments)
|
|
end
|
|
function imt.getRemainder(s)
|
|
local function getfirst(n)
|
|
local ns = s:sub(1,n)
|
|
s=s:sub(n+1)
|
|
return ns
|
|
end
|
|
local plen = imt.from16bn(getfirst(2))
|
|
if s:len() > plen then
|
|
getfirst(plen)
|
|
return s
|
|
end
|
|
return nil
|
|
end
|
|
|
|
return imt
|