| 1 | /*! |
| 2 | * ws: a node.js websocket client |
| 3 | * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> |
| 4 | * MIT Licensed |
| 5 | */ |
| 6 | |
| 7 | var util = require('util'); |
| 8 | |
| 9 | function BufferPool(initialSize, growStrategy, shrinkStrategy) { |
| 10 | if (this instanceof BufferPool === false) { |
| 11 | throw new TypeError("Classes can't be function-called"); |
| 12 | } |
| 13 | |
| 14 | if (typeof initialSize === 'function') { |
| 15 | shrinkStrategy = growStrategy; |
| 16 | growStrategy = initialSize; |
| 17 | initialSize = 0; |
| 18 | } |
| 19 | else if (typeof initialSize === 'undefined') { |
| 20 | initialSize = 0; |
| 21 | } |
| 22 | this._growStrategy = (growStrategy || function(db, size) { |
| 23 | return db.used + size; |
| 24 | }).bind(null, this); |
| 25 | this._shrinkStrategy = (shrinkStrategy || function(db) { |
| 26 | return initialSize; |
| 27 | }).bind(null, this); |
| 28 | this._buffer = initialSize ? new Buffer(initialSize) : null; |
| 29 | this._offset = 0; |
| 30 | this._used = 0; |
| 31 | this._changeFactor = 0; |
| 32 | this.__defineGetter__('size', function(){ |
| 33 | return this._buffer == null ? 0 : this._buffer.length; |
| 34 | }); |
| 35 | this.__defineGetter__('used', function(){ |
| 36 | return this._used; |
| 37 | }); |
| 38 | } |
| 39 | |
| 40 | BufferPool.prototype.get = function(length) { |
| 41 | if (this._buffer == null || this._offset + length > this._buffer.length) { |
| 42 | var newBuf = new Buffer(this._growStrategy(length)); |
| 43 | this._buffer = newBuf; |
| 44 | this._offset = 0; |
| 45 | } |
| 46 | this._used += length; |
| 47 | var buf = this._buffer.slice(this._offset, this._offset + length); |
| 48 | this._offset += length; |
| 49 | return buf; |
| 50 | } |
| 51 | |
| 52 | BufferPool.prototype.reset = function(forceNewBuffer) { |
| 53 | var len = this._shrinkStrategy(); |
| 54 | if (len < this.size) this._changeFactor -= 1; |
| 55 | if (forceNewBuffer || this._changeFactor < -2) { |
| 56 | this._changeFactor = 0; |
| 57 | this._buffer = len ? new Buffer(len) : null; |
| 58 | } |
| 59 | this._offset = 0; |
| 60 | this._used = 0; |
| 61 | } |
| 62 | |
| 63 | module.exports = BufferPool; |