Skip to content

Commit

Permalink
Added getRandomBytes to improve generateId performance
Browse files Browse the repository at this point in the history
  • Loading branch information
Kristian Faeldt committed Aug 28, 2012
1 parent 21a3733 commit a10e963
Showing 1 changed file with 55 additions and 2 deletions.
57 changes: 55 additions & 2 deletions lib/manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,60 @@ Manager.prototype.handleClient = function (data, req) {
};

/**
* Generates a session id.
* Get random bytes
*
* @api private
*/

Manager.prototype.getRandomBytes = function(bytes) {

var BUFFER_SIZE = 4096
var self = this;

bytes = bytes || 12;

if (bytes > BUFFER_SIZE) {
return crypto.randomBytes(bytes);
}

var bytesInBuffer = parseInt(BUFFER_SIZE/bytes);
var threshold = parseInt(bytesInBuffer*0.85);

if (!threshold) {
return crypto.randomBytes(bytes);
}

if (this.bytesBufferIndex == null) {
this.bytesBufferIndex = -1;
}

if (this.bytesBufferIndex == bytesInBuffer) {
this.bytesBuffer = null;
this.bytesBufferIndex = -1;
}

// No buffered bytes available
if (this.bytesBufferIndex == -1 || this.bytesBufferIndex > threshold) {

if (!this.isGeneratingBytes) {
this.isGeneratingBytes = true;
crypto.randomBytes(BUFFER_SIZE, function(err, bytes) {
self.bytesBuffer = bytes;
self.bytesBufferIndex = 0;
self.isGeneratingBytes = false;
});
}
return crypto.randomBytes(bytes);
}

var result = this.bytesBuffer.slice(bytes*this.bytesBufferIndex, bytes*(this.bytesBufferIndex+1));
this.bytesBufferIndex++;

return result;
}

/**
* Generates a session id
*
* @api private
*/
Expand All @@ -744,7 +797,7 @@ Manager.prototype.generateId = function () {
this.sequenceNumber = (this.sequenceNumber + 1) | 0;
rand.writeInt32BE(this.sequenceNumber, 11);
if (crypto.randomBytes) {
crypto.randomBytes(12).copy(rand);
this.getRandomBytes(12).copy(rand);
} else {
// not secure for node 0.4
[0, 4, 8].forEach(function(i) {
Expand Down

0 comments on commit a10e963

Please sign in to comment.