Skip to content

Instantly share code, notes, and snippets.

@bklimt
Last active December 14, 2015 03:38
Show Gist options
  • Save bklimt/5022112 to your computer and use it in GitHub Desktop.
Save bklimt/5022112 to your computer and use it in GitHub Desktop.
BufferWriter for Cloud Code Buffer
/**
* Lets you fill a Buffer without having to know its size beforehand.
*/
var BufferWriter = function() {
this._size = 0;
this._buffer = new Buffer(100);
};
_.extend(BufferWriter.prototype, {
buffer: function() {
return this._buffer.slice(0, this._size);
},
writeUInt8: function(value) {
this._reserve(this._size + 1);
this._buffer.writeUInt8(value, this._size);
this._size = this._size + 1;
},
writeInt16LE: function(value) {
this._reserve(this._size + 2);
this._buffer.writeInt16LE(value, this._size);
this._size = this._size + 2;
},
writeUInt16LE: function(value) {
this._reserve(this._size + 2);
this._buffer.writeUInt16LE(value, this._size);
this._size = this._size + 2;
},
writeUInt32LE: function(value) {
this._reserve(this._size + 4);
this._buffer.writeUInt32LE(value, this._size);
this._size = this._size + 4;
},
writeUTF8: function(str) {
this._reserve(this._size + str.length * 6);
this._size = this._size + this._buffer.write(str, this._size);
},
/**
* Resizes the backing buffer to ensure it can hold at least size bytes.
*/
_reserve: function(size) {
var current = this._buffer.length;
while (size >= current) {
this._buffer = Buffer.concat([this._buffer, new Buffer(current)],
current * 2);
current = this._buffer.length;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment