-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffers.js
79 lines (61 loc) · 1.41 KB
/
buffers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
var EMPTY = new Buffer(0);
var BufferList = function() {
this.length = 0;
this._list = [];
this._offset = 0;
};
BufferList.prototype.push = function(buf) {
if (!buf.length) {
return;
}
this._list.push(buf);
this.length += buf.length;
};
BufferList.prototype.shift = function() {
var b = this._list[0] && this._list[0][this._offset++];
this.length--;
if (this._offset >= (this._list[0] && this._list[0].length)) {
this._list.shift();
this._offset = 0;
}
return b;
};
BufferList.prototype.join = function() {
var list = this._list;
if (!list.length) {
return EMPTY;
}
var first = this._offset ? list[0].slice(this._offset) : list[0];
if (list.length === 1) {
return first;
}
var all = new Buffer(this.length);
var offset = 0;
list[0] = first;
for (var i = 0; i < list.length; i++) {
list[i].copy(all, offset);
offset += list[i].length
}
return all;
};
BufferList.prototype.empty = function(length) {
var first = this._list[0];
if (length && (this._offset + length < first.length) && (this._offset < this._offset + length)) {
var b = first.slice(this._offset, this._offset+length);
this._offset += length;
this.length -= length;
return b;
}
var all = this.join();
this.length = 0;
this._list = [];
this._offset = 0;
if (!length) {
return all;
}
this.push(all.slice(length));
return all.slice(0, length);
};
exports.create = function() {
return new BufferList();
};