forked from nodejs/readable-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrom-list.js
More file actions
61 lines (54 loc) · 1.46 KB
/
from-list.js
File metadata and controls
61 lines (54 loc) · 1.46 KB
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
'use strict';
// Read n bytes from the supplied list of buffers.
// the length is the sum of all the buffers in the list.
module.exports = fromList;
function fromList(n, list, length) {
var ret;
// nothing in the list, definitely empty.
if (list.length === 0) {
return null;
}
if (typeof length === 'undefined') {
// didn't tell us the length of the list.
// flatten and proceed from there.
var buf = Buffer.concat(list);
length = buf.length;
list.length = 0;
list.push(buf);
}
if (length === 0) {
ret = null;
} else if (!n || n >= length) {
// read it all, truncate the array.
ret = Buffer.concat(list, length);
list.length = 0;
} else {
// read just some of it.
if (n < list[0].length) {
// just take a part of the first list item.
var buf = list[0];
ret = buf.slice(0, n);
list[0] = buf.slice(n);
} else if (n === list[0].length) {
// first list is a perfect match
ret = list.shift();
} else {
// complex case.
// we have enough to cover it, but it spans past the first buffer.
ret = new Buffer(n);
var c = 0;
for (var i = 0, l = list.length; i < l && c < n; i++) {
var buf = list[0];
var cpy = Math.min(n - c, buf.length);
buf.copy(ret, c, 0, cpy);
if (cpy < buf.length) {
list[0] = buf.slice(cpy);
} else {
list.shift();
}
c += cpy;
}
}
}
return ret;
}