Skip to content

Instantly share code, notes, and snippets.

Created June 9, 2013 16:24
Show Gist options
  • Save anonymous/5744151 to your computer and use it in GitHub Desktop.
Save anonymous/5744151 to your computer and use it in GitHub Desktop.
/**
* Created with JetBrains WebStorm.
* User: kiyangqi
* Date: 13-6-9
* Time: 下午11:36
* To change this template use File | Settings | File Templates.
*/
function StreamBuf() {
this.chunks = [];
this.length = 0;
}
// chunk must be Buffer
StreamBuf.prototype.write = function(chunk) {
if(typeof chunk == 'string') {
chunk = Buffer(chunk);
}
if(chunk.constructor != Buffer) {
throw new Error("chunk must be Buffer or String");
}
this.chunks.push(chunk);
this.length += chunk.length;
}
StreamBuf.prototype.read = function(need) {
if(need <= this.length) {
var bytes = 0, i = 0;
var out = [];
while(bytes < need) {
if(bytes + this.chunks[0] <= need) {
var item = this.chunks.shift();
out.push(item);
bytes += item.length;
} else {
var item = this.chunks.shift();
out.push(item.slice(0, need - bytes));
this.chunks.unshift(item.slice(need-bytes));
bytes = need;
}
}
this.length -= need;
return Buffer.concat(out, need);
}
throw new Error("not enough bytes");
}
StreamBuf.prototype.readSome = function(needMax) {
return this.read(Math.min(needMax, this.length));
}
module.exports = StreamBuf;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment