BufferList.js 1.4 KB

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