| 1 |
import {Buffer} from 'buffer'; |
| 2 |
|
| 3 |
export default BufferList; |
| 4 |
|
| 5 |
function BufferList() { |
| 6 |
this.head = null; |
| 7 |
this.tail = null; |
| 8 |
this.length = 0; |
| 9 |
} |
| 10 |
|
| 11 |
BufferList.prototype.push = function (v) { |
| 12 |
var entry = { data: v, next: null }; |
| 13 |
if (this.length > 0) this.tail.next = entry;else this.head = entry; |
| 14 |
this.tail = entry; |
| 15 |
++this.length; |
| 16 |
}; |
| 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 |
|
| 25 |
BufferList.prototype.shift = function () { |
| 26 |
if (this.length === 0) return; |
| 27 |
var ret = this.head.data; |
| 28 |
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; |
| 29 |
--this.length; |
| 30 |
return ret; |
| 31 |
}; |
| 32 |
|
| 33 |
BufferList.prototype.clear = function () { |
| 34 |
this.head = this.tail = null; |
| 35 |
this.length = 0; |
| 36 |
}; |
| 37 |
|
| 38 |
BufferList.prototype.join = function (s) { |
| 39 |
if (this.length === 0) return ''; |
| 40 |
var p = this.head; |
| 41 |
var ret = '' + p.data; |
| 42 |
while (p = p.next) { |
| 43 |
ret += s + p.data; |
| 44 |
}return ret; |
| 45 |
}; |
| 46 |
|
| 47 |
BufferList.prototype.concat = function (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 |
p.data.copy(ret, i); |
| 55 |
i += p.data.length; |
| 56 |
p = p.next; |
| 57 |
} |
| 58 |
return ret; |
| 59 |
}; |