forked from brianc/node-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer-list.js
69 lines (60 loc) · 1.49 KB
/
buffer-list.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
BufferList = function() {
this.buffers = [];
};
var p = BufferList.prototype;
p.add = function(buffer, front) {
this.buffers[front ? "unshift" : "push"](buffer);
return this;
};
p.addInt16 = function(val, front) {
return this.add(new Buffer([(val >>> 8), (val >>> 0)]), front);
};
p.getByteLength = function(initial) {
return this.buffers.reduce(function(previous, current){
return previous + current.length;
},initial || 0);
};
p.addInt32 = function(val, first) {
return this.add(new Buffer([
(val >>> 24 & 0xFF),
(val >>> 16 & 0xFF),
(val >>> 8 & 0xFF),
(val >>> 0 & 0xFF)
]),first);
};
p.addCString = function(val, front) {
var len = Buffer.byteLength(val);
var buffer = new Buffer(len+1);
buffer.write(val);
buffer[len] = 0;
return this.add(buffer, front);
};
p.addChar = function(char, first) {
return this.add(new Buffer(char, 'utf8'), first);
};
p.join = function(appendLength, char) {
var length = this.getByteLength();
if(appendLength) {
this.addInt32(length+4, true);
return this.join(false, char);
}
if(char) {
this.addChar(char, true);
length++;
}
var result = new Buffer(length);
var index = 0;
this.buffers.forEach(function(buffer) {
buffer.copy(result, index, 0);
index += buffer.length;
});
return result;
};
BufferList.concat = function() {
var total = new BufferList();
for(var i = 0; i < arguments.length; i++) {
total.add(arguments[i]);
}
return total.join();
};
module.exports = BufferList;