You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.7 KiB

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