stream.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* Wrapper for accessing strings through sequential reads */
  2. function Stream(str) {
  3. var position = 0;
  4. function read(length) {
  5. var result = str.substr(position, length);
  6. position += length;
  7. return result;
  8. }
  9. /* read a big-endian 32-bit integer */
  10. function readInt32() {
  11. var result = (
  12. (str.charCodeAt(position) << 24)
  13. + (str.charCodeAt(position + 1) << 16)
  14. + (str.charCodeAt(position + 2) << 8)
  15. + str.charCodeAt(position + 3));
  16. position += 4;
  17. return result;
  18. }
  19. /* read a big-endian 16-bit integer */
  20. function readInt16() {
  21. var result = (
  22. (str.charCodeAt(position) << 8)
  23. + str.charCodeAt(position + 1));
  24. position += 2;
  25. return result;
  26. }
  27. /* read an 8-bit integer */
  28. function readInt8(signed) {
  29. var result = str.charCodeAt(position);
  30. if (signed && result > 127) result -= 256;
  31. position += 1;
  32. return result;
  33. }
  34. function eof() {
  35. return position >= str.length;
  36. }
  37. /* read a MIDI-style variable-length integer
  38. (big-endian value in groups of 7 bits,
  39. with top bit set to signify that another byte follows)
  40. */
  41. function readVarInt() {
  42. var result = 0;
  43. while (true) {
  44. var b = readInt8();
  45. if (b & 0x80) {
  46. result += (b & 0x7f);
  47. result <<= 7;
  48. } else {
  49. /* b is the last byte */
  50. return result + b;
  51. }
  52. }
  53. }
  54. return {
  55. 'eof': eof,
  56. 'read': read,
  57. 'readInt32': readInt32,
  58. 'readInt16': readInt16,
  59. 'readInt8': readInt8,
  60. 'readVarInt': readVarInt
  61. }
  62. }