receivebuffer.js 1.5 KB

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