Skip to content

Commit

Permalink
Faster generate.
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed Oct 18, 2015
1 parent 7995f62 commit 3d5c79d
Showing 1 changed file with 48 additions and 3 deletions.
51 changes: 48 additions & 3 deletions generate.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,57 @@
'use strict';

var writeToStream = require('./writeToStream')
var bl = require('bl')
, EE = require('events').EventEmitter
, inherits = require('inherits')

function generate(packet) {
var stream = bl()
var stream = new Accumulator()
writeToStream(packet, stream)
return stream.slice()
return stream.concat()
}

function Accumulator() {
this._array = new Array(20)
this._i = 0
}

inherits(Accumulator, EE)

Accumulator.prototype.write = function (chunk) {
this._array[this._i++] = chunk
return true
};

Accumulator.prototype.concat = function () {
var length = 0
, lengths = new Array(this._array.length)
, list = this._array
, pos = 0
, i
, result;

for (i = 0; i < list.length && list[i]; i++) {
if (typeof list[i] !== 'string') {
lengths[i] = list[i].length;
} else {
lengths[i] = Buffer.byteLength(list[i]);
}
length += lengths[i];
}

result = new Buffer(length);

for (i = 0; i < list.length && list[i]; i++) {
if (typeof list[i] !== 'string') {
list[i].copy(result, pos);
pos += lengths[i];
} else {
result.write(list[i], pos);
pos += lengths[i];
}
}

return result;
};

module.exports = generate

0 comments on commit 3d5c79d

Please sign in to comment.