2 * ws: a node.js websocket client
3 * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
7 var util = require('util');
9 function BufferPool(initialSize, growStrategy, shrinkStrategy) {
10 if (typeof initialSize === 'function') {
11 shrinkStrategy = growStrategy;
12 growStrategy = initialSize;
15 else if (typeof initialSize === 'undefined') {
18 this._growStrategy = (growStrategy || function(db, size) {
19 return db.used + size;
21 this._shrinkStrategy = (shrinkStrategy || function(db) {
24 this._buffer = initialSize ? new Buffer(initialSize) : null;
27 this._changeFactor = 0;
28 this.__defineGetter__('size', function(){
29 return this._buffer == null ? 0 : this._buffer.length;
31 this.__defineGetter__('used', function(){
36 BufferPool.prototype.get = function(length) {
37 if (this._buffer == null || this._offset + length > this._buffer.length) {
38 var newBuf = new Buffer(this._growStrategy(length));
39 this._buffer = newBuf;
43 var buf = this._buffer.slice(this._offset, this._offset + length);
44 this._offset += length;
48 BufferPool.prototype.reset = function(forceNewBuffer) {
49 var len = this._shrinkStrategy();
50 if (len < this.size) this._changeFactor -= 1;
51 if (forceNewBuffer || this._changeFactor < -2) {
52 this._changeFactor = 0;
53 this._buffer = len ? new Buffer(len) : null;
59 module.exports = BufferPool;