BufferList.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. /*<replacement>*/
  3. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4. var Buffer = require('safe-buffer').Buffer;
  5. /*</replacement>*/
  6. function copyBuffer(src, target, offset) {
  7. src.copy(target, offset);
  8. }
  9. module.exports = function () {
  10. function BufferList() {
  11. _classCallCheck(this, BufferList);
  12. this.head = null;
  13. this.tail = null;
  14. this.length = 0;
  15. }
  16. BufferList.prototype.push = function push(v) {
  17. var entry = { data: v, next: null };
  18. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  19. this.tail = entry;
  20. ++this.length;
  21. };
  22. BufferList.prototype.unshift = function unshift(v) {
  23. var entry = { data: v, next: this.head };
  24. if (this.length === 0) this.tail = entry;
  25. this.head = entry;
  26. ++this.length;
  27. };
  28. BufferList.prototype.shift = function shift() {
  29. if (this.length === 0) return;
  30. var ret = this.head.data;
  31. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  32. --this.length;
  33. return ret;
  34. };
  35. BufferList.prototype.clear = function clear() {
  36. this.head = this.tail = null;
  37. this.length = 0;
  38. };
  39. BufferList.prototype.join = function join(s) {
  40. if (this.length === 0) return '';
  41. var p = this.head;
  42. var ret = '' + p.data;
  43. while (p = p.next) {
  44. ret += s + p.data;
  45. }return ret;
  46. };
  47. BufferList.prototype.concat = function concat(n) {
  48. if (this.length === 0) return Buffer.alloc(0);
  49. if (this.length === 1) return this.head.data;
  50. var ret = Buffer.allocUnsafe(n >>> 0);
  51. var p = this.head;
  52. var i = 0;
  53. while (p) {
  54. copyBuffer(p.data, ret, i);
  55. i += p.data.length;
  56. p = p.next;
  57. }
  58. return ret;
  59. };
  60. return BufferList;
  61. }();