stream.lua 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. local Queue = require("lockbox.util.queue");
  2. local String = require("string");
  3. local Stream = {};
  4. Stream.fromString = function(string)
  5. local i = 0;
  6. return function()
  7. i = i + 1;
  8. return String.byte(string, i);
  9. end
  10. end
  11. Stream.toString = function(stream)
  12. local array = {};
  13. local i = 1;
  14. local byte = stream();
  15. while byte ~= nil do
  16. array[i] = String.char(byte);
  17. i = i + 1;
  18. byte = stream();
  19. end
  20. return table.concat(array);
  21. end
  22. Stream.fromArray = function(array)
  23. local queue = Queue();
  24. local i = 1;
  25. local byte = array[i];
  26. while byte ~= nil do
  27. queue.push(byte);
  28. i = i + 1;
  29. byte = array[i];
  30. end
  31. return queue.pop;
  32. end
  33. Stream.toArray = function(stream)
  34. local array = {};
  35. local i = 1;
  36. local byte = stream();
  37. while byte ~= nil do
  38. array[i] = byte;
  39. i = i + 1;
  40. byte = stream();
  41. end
  42. return array;
  43. end
  44. local fromHexTable = {};
  45. for i = 0, 255 do
  46. fromHexTable[String.format("%02X", i)] = i;
  47. fromHexTable[String.format("%02x", i)] = i;
  48. end
  49. Stream.fromHex = function(hex)
  50. local queue = Queue();
  51. for i = 1, String.len(hex) / 2 do
  52. local h = String.sub(hex, i * 2 - 1, i * 2);
  53. queue.push(fromHexTable[h]);
  54. end
  55. return queue.pop;
  56. end
  57. local toHexTable = {};
  58. for i = 0, 255 do
  59. toHexTable[i] = String.format("%02X", i);
  60. end
  61. Stream.toHex = function(stream)
  62. local hex = {};
  63. local i = 1;
  64. local byte = stream();
  65. while byte ~= nil do
  66. hex[i] = toHexTable[byte];
  67. i = i + 1;
  68. byte = stream();
  69. end
  70. return table.concat(hex);
  71. end
  72. return Stream;