From 3d5c79d823d8d6ae5a569933b2ec615b09423f97 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Sun, 18 Oct 2015 11:11:26 +0200 Subject: [PATCH] Faster generate. --- generate.js | 51 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/generate.js b/generate.js index 6168af8..8a34867 100644 --- a/generate.js +++ b/generate.js @@ -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