comunicationLeap/node_modules/ws/lib/BufferPool.js
node_modules/ws/lib/BufferPool.jsRaw
1/*!
2 * ws: a node.js websocket client
3 * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
4 * MIT Licensed
5 */
6
7var util = require('util');
8
9function BufferPool(initialSize, growStrategy, shrinkStrategy) {
10 if (typeof initialSize === 'function') {
11 shrinkStrategy = growStrategy;
12 growStrategy = initialSize;
13 initialSize = 0;
14 }
15 else if (typeof initialSize === 'undefined') {
16 initialSize = 0;
17 }
18 this._growStrategy = (growStrategy || function(db, size) {
19 return db.used + size;
20 }).bind(null, this);
21 this._shrinkStrategy = (shrinkStrategy || function(db) {
22 return initialSize;
23 }).bind(null, this);
24 this._buffer = initialSize ? new Buffer(initialSize) : null;
25 this._offset = 0;
26 this._used = 0;
27 this._changeFactor = 0;
28 this.__defineGetter__('size', function(){
29 return this._buffer == null ? 0 : this._buffer.length;
30 });
31 this.__defineGetter__('used', function(){
32 return this._used;
33 });
34}
35
36BufferPool.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;
40 this._offset = 0;
41 }
42 this._used += length;
43 var buf = this._buffer.slice(this._offset, this._offset + length);
44 this._offset += length;
45 return buf;
46}
47
48BufferPool.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;
54 }
55 this._offset = 0;
56 this._used = 0;
57}
58
59module.exports = BufferPool;