binarywriter.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. module.exports = BinaryWriter;
  2. function BinaryWriter(size, allowResize) {
  3. this.buffer = new Buffer(size);
  4. this.position = 0;
  5. this.allowResize = allowResize;
  6. }
  7. function _write(write, size) {
  8. return function (value, noAssert) {
  9. this.ensureSize(size);
  10. write.call(this.buffer, value, this.position, noAssert);
  11. this.position += size;
  12. };
  13. }
  14. BinaryWriter.prototype.writeUInt8 = _write(Buffer.prototype.writeUInt8, 1);
  15. BinaryWriter.prototype.writeUInt16LE = _write(Buffer.prototype.writeUInt16LE, 2);
  16. BinaryWriter.prototype.writeUInt16BE = _write(Buffer.prototype.writeUInt16BE, 2);
  17. BinaryWriter.prototype.writeUInt32LE = _write(Buffer.prototype.writeUInt32LE, 4);
  18. BinaryWriter.prototype.writeUInt32BE = _write(Buffer.prototype.writeUInt32BE, 4);
  19. BinaryWriter.prototype.writeInt8 = _write(Buffer.prototype.writeInt8, 1);
  20. BinaryWriter.prototype.writeInt16LE = _write(Buffer.prototype.writeInt16LE, 2);
  21. BinaryWriter.prototype.writeInt16BE = _write(Buffer.prototype.writeInt16BE, 2);
  22. BinaryWriter.prototype.writeInt32LE = _write(Buffer.prototype.writeInt32LE, 4);
  23. BinaryWriter.prototype.writeInt32BE = _write(Buffer.prototype.writeInt32BE, 4);
  24. BinaryWriter.prototype.writeFloatLE = _write(Buffer.prototype.writeFloatLE, 4);
  25. BinaryWriter.prototype.writeFloatBE = _write(Buffer.prototype.writeFloatBE, 4);
  26. BinaryWriter.prototype.writeDoubleLE = _write(Buffer.prototype.writeDoubleLE, 8);
  27. BinaryWriter.prototype.writeDoubleBE = _write(Buffer.prototype.writeDoubleBE, 8);
  28. BinaryWriter.prototype.writeBuffer = function (buffer) {
  29. this.ensureSize(buffer.length);
  30. buffer.copy(this.buffer, this.position, 0, buffer.length);
  31. this.position += buffer.length;
  32. };
  33. BinaryWriter.prototype.writeVarInt = function (value) {
  34. var length = 1;
  35. while ((value & 0xFFFFFF80) !== 0) {
  36. this.writeUInt8((value & 0x7F) | 0x80);
  37. value >>>= 7;
  38. length++;
  39. }
  40. this.writeUInt8(value & 0x7F);
  41. return length;
  42. };
  43. BinaryWriter.prototype.ensureSize = function (size) {
  44. if (this.buffer.length < this.position + size) {
  45. if (this.allowResize) {
  46. var tempBuffer = new Buffer(this.position + size);
  47. this.buffer.copy(tempBuffer, 0, 0, this.buffer.length);
  48. this.buffer = tempBuffer;
  49. }
  50. else {
  51. throw new RangeError('index out of range');
  52. }
  53. }
  54. };