2010-10-09 12:00:37 +08:00
|
|
|
BufferList = function() {
|
|
|
|
this.buffers = [];
|
|
|
|
};
|
2010-10-24 03:50:28 +08:00
|
|
|
var p = BufferList.prototype;
|
2010-10-09 12:00:37 +08:00
|
|
|
|
2010-10-24 03:50:28 +08:00
|
|
|
p.add = function(buffer, front) {
|
2010-10-09 12:00:37 +08:00
|
|
|
this.buffers[front ? "unshift" : "push"](buffer);
|
|
|
|
return this;
|
|
|
|
};
|
|
|
|
|
2010-10-24 03:50:28 +08:00
|
|
|
p.addInt16 = function(val, front) {
|
2010-10-09 12:00:37 +08:00
|
|
|
return this.add(Buffer([(val >>> 8),(val >>> 0)]),front);
|
|
|
|
};
|
|
|
|
|
2010-10-24 03:50:28 +08:00
|
|
|
p.getByteLength = function(initial) {
|
2010-10-09 12:00:37 +08:00
|
|
|
return this.buffers.reduce(function(previous, current){
|
|
|
|
return previous + current.length;
|
|
|
|
},initial || 0);
|
|
|
|
};
|
|
|
|
|
2010-10-24 03:50:28 +08:00
|
|
|
p.addInt32 = function(val, first) {
|
2010-10-09 12:00:37 +08:00
|
|
|
return this.add(Buffer([
|
2010-10-16 06:29:01 +08:00
|
|
|
(val >>> 24 & 0xFF),
|
|
|
|
(val >>> 16 & 0xFF),
|
|
|
|
(val >>> 8 & 0xFF),
|
|
|
|
(val >>> 0 & 0xFF)
|
2010-10-09 12:00:37 +08:00
|
|
|
]),first);
|
|
|
|
};
|
|
|
|
|
2010-10-24 03:50:28 +08:00
|
|
|
p.addCString = function(val) {
|
2010-10-09 12:00:37 +08:00
|
|
|
return this.add(Buffer(val + '\0','utf8'));
|
|
|
|
};
|
|
|
|
|
2010-10-24 03:50:28 +08:00
|
|
|
p.addChar = function(char, first) {
|
2010-10-11 07:10:26 +08:00
|
|
|
return this.add(Buffer(char,'utf8'), first);
|
2010-10-11 06:40:11 +08:00
|
|
|
};
|
|
|
|
|
2010-10-24 03:50:28 +08:00
|
|
|
p.join = function(appendLength, char) {
|
2010-10-09 12:00:37 +08:00
|
|
|
var length = this.getByteLength();
|
|
|
|
if(appendLength) {
|
|
|
|
this.addInt32(length+4, true);
|
|
|
|
return this.join(false, char);
|
|
|
|
}
|
|
|
|
if(char) {
|
2010-10-11 06:40:11 +08:00
|
|
|
this.addChar(char, true);
|
2010-10-09 12:00:37 +08:00
|
|
|
length++;
|
|
|
|
}
|
|
|
|
var result = 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();
|
|
|
|
};
|
2010-10-09 12:02:01 +08:00
|
|
|
|
|
|
|
module.exports = BufferList;
|