Created
May 20, 2015 00:45
-
-
Save roblabla/c1811c7ae3b9298c1dd7 to your computer and use it in GitHub Desktop.
Packet framing transform stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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