utility.lua 989 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. local BASE = (...):match("(.-)[^%.]+$")
  2. local utility = {}
  3. local b1 = 256^3
  4. local b2 = 256^2
  5. local b3 = 256
  6. function utility:lengthToHeader( len )
  7. -- Short message:
  8. if len < 255 then
  9. return string.char(len)
  10. end
  11. -- Long message ('255' followed by 4 bytes of length)
  12. local h1 = math.floor(len/b1)
  13. len = len - h1*b1
  14. local h2 = math.floor(len/b2)
  15. len = len - h2*b2
  16. local h3 = math.floor(len/b3)
  17. len = len - h3*b3
  18. --print("\t",255, h1, h2, h3, len)
  19. return string.char(255,h1,h2,h3,len)
  20. end
  21. function utility:headerToLength( header )
  22. local byte1 = string.byte( header:sub(1,1) )
  23. if byte1 <= 254 then
  24. return byte1, 1
  25. else
  26. if #header == 5 then
  27. local v1 = string.byte(header:sub(2,2))*b1
  28. local v2 = string.byte(header:sub(3,3))*b2
  29. local v3 = string.byte(header:sub(4,4))*b3
  30. local v4 = string.byte(header:sub(5,5))
  31. return v1 + v2 + v3 + v4, 5
  32. end
  33. end
  34. -- If the length is larger than 254, but no 5 bytes have arrived yet...
  35. return nil
  36. end
  37. return utility