buffer-list.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import {Buffer} from 'buffer';
  2. export default BufferList;
  3. function BufferList() {
  4. this.head = null;
  5. this.tail = null;
  6. this.length = 0;
  7. }
  8. BufferList.prototype.push = function (v) {
  9. var entry = { data: v, next: null };
  10. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  11. this.tail = entry;
  12. ++this.length;
  13. };
  14. BufferList.prototype.unshift = function (v) {
  15. var entry = { data: v, next: this.head };
  16. if (this.length === 0) this.tail = entry;
  17. this.head = entry;
  18. ++this.length;
  19. };
  20. BufferList.prototype.shift = function () {
  21. if (this.length === 0) return;
  22. var ret = this.head.data;
  23. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  24. --this.length;
  25. return ret;
  26. };
  27. BufferList.prototype.clear = function () {
  28. this.head = this.tail = null;
  29. this.length = 0;
  30. };
  31. BufferList.prototype.join = function (s) {
  32. if (this.length === 0) return '';
  33. var p = this.head;
  34. var ret = '' + p.data;
  35. while (p = p.next) {
  36. ret += s + p.data;
  37. }return ret;
  38. };
  39. BufferList.prototype.concat = function (n) {
  40. if (this.length === 0) return Buffer.alloc(0);
  41. if (this.length === 1) return this.head.data;
  42. var ret = Buffer.allocUnsafe(n >>> 0);
  43. var p = this.head;
  44. var i = 0;
  45. while (p) {
  46. p.data.copy(ret, i);
  47. i += p.data.length;
  48. p = p.next;
  49. }
  50. return ret;
  51. };