Skip to content

Instantly share code, notes, and snippets.

@roblabla
Created May 20, 2015 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roblabla/c1811c7ae3b9298c1dd7 to your computer and use it in GitHub Desktop.
Save roblabla/c1811c7ae3b9298c1dd7 to your computer and use it in GitHub Desktop.
Packet framing transform stream
var readVarInt = require("../datatypes/utils").varint[0];
var Transform = require("stream").Transform;
module.exports.createSplitter = function() {
return new Splitter();
}
class Splitter extends Transform {
constructor() {
super();
this.buffer = new Buffer(0);
}
_transform(chunk, enc, cb) {
this.buffer = Buffer.concat([this.buffer, chunk]);
var value;
var size;
var offset = 0;
({ value, size, error } = readVarInt(buffer, offset));
while (!error && this.buffer.length >= offset + size + value)
{
this.push(this.buffer.slice(offset + size, offset + size + value));
offset += size + value;
({ value, size, error } = readVarInt(buffer, offset));
}
this.buffer = this.buffer.slice(offset);
return cb();
}
}
class Framer extends Transform {
constructor() {
super();
}
_transform(chunk, enc, cb) {
var buffer = new Buffer(sizeOfVarInt(chunk.length));
writeVarInt(chunk.length, buffer, 0);
this.push(buffer);
this.push(chunk);
return cb();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment