receivebuffer.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. class ReceiveBuffer {
  4. constructor(size = 4096) {
  5. this._buffer = Buffer.allocUnsafe(size);
  6. this._offset = 0;
  7. this._originalSize = size;
  8. }
  9. get length() {
  10. return this._offset;
  11. }
  12. append(data) {
  13. if (!Buffer.isBuffer(data)) {
  14. throw new Error('Attempted to append a non-buffer instance to ReceiveBuffer.');
  15. }
  16. if (this._offset + data.length >= this._buffer.length) {
  17. const tmp = this._buffer;
  18. this._buffer = Buffer.allocUnsafe(Math.max(this._buffer.length + this._originalSize, this._buffer.length + data.length));
  19. tmp.copy(this._buffer);
  20. }
  21. data.copy(this._buffer, this._offset);
  22. return (this._offset += data.length);
  23. }
  24. peek(length) {
  25. if (length > this._offset) {
  26. throw new Error('Attempted to read beyond the bounds of the managed internal data.');
  27. }
  28. return this._buffer.slice(0, length);
  29. }
  30. get(length) {
  31. if (length > this._offset) {
  32. throw new Error('Attempted to read beyond the bounds of the managed internal data.');
  33. }
  34. const value = Buffer.allocUnsafe(length);
  35. this._buffer.slice(0, length).copy(value);
  36. this._buffer.copyWithin(0, length, length + this._offset - length);
  37. this._offset -= length;
  38. return value;
  39. }
  40. }
  41. exports.ReceiveBuffer = ReceiveBuffer;
  42. //# sourceMappingURL=receivebuffer.js.map