Last active
March 1, 2022 21:55
-
-
Save brandon-lockaby/2048204 to your computer and use it in GitHub Desktop.
Bufferer
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 Bufferer = function() { | |
this.buffer = new Buffer(0); | |
this.expects = []; | |
return this; | |
}; | |
Bufferer.prototype.receive = function(buffer) { | |
var new_buffer = new Buffer(this.buffer.length + buffer.length); | |
this.buffer.copy(new_buffer); | |
buffer.copy(new_buffer, this.buffer.length); | |
this.buffer = new_buffer; | |
this.tryFlush(); | |
return this; | |
}; | |
Bufferer.prototype.expect = function(requirement, callback) { | |
this.expects.push({requirement: requirement, callback: callback}); | |
this.tryFlush(); | |
return this; | |
}; | |
Bufferer.prototype.tryFlush = function() { | |
if(this.expects.length < 1) return; | |
if(typeof this.expects[0].requirement === "number") { | |
if(this.buffer.length >= this.expects[0].requirement) { | |
var expects = this.expects.shift(); | |
if(typeof expects.callback == "function") { | |
process.nextTick(expects.callback.bind(this, this.buffer.slice(0, expects.requirement))); | |
} | |
this.chop(expects.requirement); | |
} | |
} else if(typeof this.expects[0].requirement === "function") { | |
var result = this.expects[0].requirement(this.buffer); | |
if(!result) return; | |
var expects = this.expects.shift(); | |
if(typeof expects.callback == "function") { | |
process.nextTick(expects.callback.bind(this, result)); | |
} | |
this.chop(result.size || 0); | |
} | |
return this; | |
}; | |
Bufferer.prototype.read = function(size) { | |
if(this.buffer.length < size) return false; | |
var result = this.buffer.slice(0, size); | |
this.chop(size); | |
return result; | |
}; | |
Bufferer.prototype.chop = function(size) { | |
if(this.buffer.length > size) | |
this.buffer = this.buffer.slice(size); | |
else | |
this.buffer = new Buffer(0); | |
process.nextTick(this.tryFlush.bind(this)); | |
}; | |
module.exports = Bufferer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment