binaryreader.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. module.exports = BinaryReader;
  2. function BinaryReader(buffer, isBigEndian) {
  3. this.buffer = buffer;
  4. this.position = 0;
  5. this.isBigEndian = isBigEndian || false;
  6. }
  7. function _read(readLE, readBE, size) {
  8. return function () {
  9. var value;
  10. if (this.isBigEndian)
  11. value = readBE.call(this.buffer, this.position);
  12. else
  13. value = readLE.call(this.buffer, this.position);
  14. this.position += size;
  15. return value;
  16. };
  17. }
  18. BinaryReader.prototype.readUInt8 = _read(Buffer.prototype.readUInt8, Buffer.prototype.readUInt8, 1);
  19. BinaryReader.prototype.readUInt16 = _read(Buffer.prototype.readUInt16LE, Buffer.prototype.readUInt16BE, 2);
  20. BinaryReader.prototype.readUInt32 = _read(Buffer.prototype.readUInt32LE, Buffer.prototype.readUInt32BE, 4);
  21. BinaryReader.prototype.readInt8 = _read(Buffer.prototype.readInt8, Buffer.prototype.readInt8, 1);
  22. BinaryReader.prototype.readInt16 = _read(Buffer.prototype.readInt16LE, Buffer.prototype.readInt16BE, 2);
  23. BinaryReader.prototype.readInt32 = _read(Buffer.prototype.readInt32LE, Buffer.prototype.readInt32BE, 4);
  24. BinaryReader.prototype.readFloat = _read(Buffer.prototype.readFloatLE, Buffer.prototype.readFloatBE, 4);
  25. BinaryReader.prototype.readDouble = _read(Buffer.prototype.readDoubleLE, Buffer.prototype.readDoubleBE, 8);
  26. BinaryReader.prototype.readVarInt = function () {
  27. var nextByte,
  28. result = 0,
  29. bytesRead = 0;
  30. do {
  31. nextByte = this.buffer[this.position + bytesRead];
  32. result += (nextByte & 0x7F) << (7 * bytesRead);
  33. bytesRead++;
  34. } while (nextByte >= 0x80);
  35. this.position += bytesRead;
  36. return result;
  37. };