Operating system for OpenComputers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.5KB

  1. local imt = {}
  2. imt.ttypes = {}
  3. imt.ttypes.string=1
  4. imt.ttypes.number=2
  5. imt.ftypes = {tostring,tonumber}
  6. function imt.to16bn(n)
  7. return string.char(math.floor(n/256))..string.char(math.floor(n%256))
  8. end
  9. function imt.from16bn(s)
  10. return (string.byte(s,1,1)*256)+string.byte(s,2,2)
  11. end
  12. function imt.encodePacket(...)
  13. local tArgs = {...}
  14. local packet = string.char(#tArgs%256)
  15. for _,segment in ipairs(tArgs) do
  16. local segtype = type(segment)
  17. segment = tostring(segment)
  18. packet = packet .. imt.to16bn(segment:len()) .. string.char(imt.ttypes[segtype]) .. tostring(segment)
  19. end
  20. packet = imt.to16bn(packet:len()) .. packet
  21. return packet
  22. end
  23. function imt.decodePacket(s)
  24. local function getfirst(n)
  25. local ns = s:sub(1,n)
  26. s=s:sub(n+1)
  27. return ns
  28. end
  29. if s:len() < 2 then return false end
  30. local plen = imt.from16bn(getfirst(2))
  31. local segments = {}
  32. if s:len() < plen then return false end
  33. local nsegments = string.byte(getfirst(1))
  34. --print(tostring(plen).." bytes, "..tostring(nsegments).." segments")
  35. for i = 1, nsegments do
  36. local seglen = imt.from16bn(getfirst(2))
  37. local segtype = imt.ftypes[string.byte(getfirst(1))]
  38. local segment = segtype(getfirst(seglen))
  39. --print(seglen,segtype,segment,type(segment))
  40. segments[#segments+1] = segment
  41. end
  42. return table.unpack(segments)
  43. end
  44. function imt.getRemainder(s)
  45. local function getfirst(n)
  46. local ns = s:sub(1,n)
  47. s=s:sub(n+1)
  48. return ns
  49. end
  50. local plen = imt.from16bn(getfirst(2))
  51. if s:len() > plen then
  52. getfirst(plen)
  53. return s
  54. end
  55. return nil
  56. end
  57. return imt