streams: refactor BufferList into ES6 class

PR-URL: https://github.com/nodejs/node/pull/12644
Reviewed-By: Brian White <mscdex@mscdex.net>
This commit is contained in:
James M Snell 2017-04-24 16:00:45 -07:00
parent ed0716f0e9
commit e2199e0fc2

View File

@ -2,71 +2,71 @@
const Buffer = require('buffer').Buffer; const Buffer = require('buffer').Buffer;
module.exports = BufferList; module.exports = class BufferList {
constructor() {
function BufferList() { this.head = null;
this.head = null; this.tail = null;
this.tail = null; this.length = 0;
this.length = 0; }
}
push(v) {
BufferList.prototype.push = function(v) { const entry = { data: v, next: null };
const entry = { data: v, next: null }; if (this.length > 0)
if (this.length > 0) this.tail.next = entry;
this.tail.next = entry; else
else this.head = entry;
this.head = entry; this.tail = entry;
this.tail = entry; ++this.length;
++this.length; }
};
unshift(v) {
BufferList.prototype.unshift = function(v) { const entry = { data: v, next: this.head };
const entry = { data: v, next: this.head }; if (this.length === 0)
if (this.length === 0) this.tail = entry;
this.tail = entry; this.head = entry;
this.head = entry; ++this.length;
++this.length; }
};
shift() {
BufferList.prototype.shift = function() { if (this.length === 0)
if (this.length === 0) return;
return; const ret = this.head.data;
const ret = this.head.data; if (this.length === 1)
if (this.length === 1) this.head = this.tail = null;
this.head = this.tail = null; else
else this.head = this.head.next;
this.head = this.head.next; --this.length;
--this.length; return ret;
return ret; }
};
clear() {
BufferList.prototype.clear = function() { this.head = this.tail = null;
this.head = this.tail = null; this.length = 0;
this.length = 0; }
};
join(s) {
BufferList.prototype.join = function(s) { if (this.length === 0)
if (this.length === 0) return '';
return ''; var p = this.head;
var p = this.head; var ret = '' + p.data;
var ret = '' + p.data; while (p = p.next)
while (p = p.next) ret += s + p.data;
ret += s + p.data; return ret;
return ret; }
};
concat(n) {
BufferList.prototype.concat = function(n) { if (this.length === 0)
if (this.length === 0) return Buffer.alloc(0);
return Buffer.alloc(0); if (this.length === 1)
if (this.length === 1) return this.head.data;
return this.head.data; const ret = Buffer.allocUnsafe(n >>> 0);
const ret = Buffer.allocUnsafe(n >>> 0); var p = this.head;
var p = this.head; var i = 0;
var i = 0; while (p) {
while (p) { p.data.copy(ret, i);
p.data.copy(ret, i); i += p.data.length;
i += p.data.length; p = p.next;
p = p.next; }
return ret;
} }
return ret;
}; };