// Generated by IcedCoffeeScript 1.7.1-c
(function() {
  var Buffer, Ring;

  Buffer = require('buffer').Buffer;

  exports.Ring = Ring = (function() {
    "A Ring of buffers. Every so often you'll have to compress buffers into\nsmaller buffers, but try to limit that as much as possible....";
    function Ring() {
      this._bufs = [];
      this._len = 0;
    }

    Ring.prototype.buffer = function(b) {
      this._bufs.push(b);
      return this._len += b.length;
    };

    Ring.prototype.len = function() {
      return this._len;
    };

    Ring.prototype.grab = function(n_wanted) {
      var b, first_pos, n, n_grabbed, num_bufs, ret, _i, _j, _len, _len1, _ref, _ref1;
      if (!(n_wanted <= this.len())) {
        return null;
      }
      if (this._bufs.length && this._bufs[0].length >= n_wanted) {
        return this._bufs[0];
      }
      n_grabbed = 0;
      num_bufs = 0;
      _ref = this._bufs;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        b = _ref[_i];
        n_grabbed += b.length;
        num_bufs++;
        if (n_grabbed >= n_wanted) {
          break;
        }
      }
      ret = new Buffer(n_grabbed);
      n = 0;
      _ref1 = this._bufs.slice(0, num_bufs);
      for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
        b = _ref1[_j];
        b.copy(ret, n, 0, b.length);
        n += b.length;
      }
      first_pos = num_bufs - 1;
      this._bufs[first_pos] = ret;
      this._bufs = this._bufs.slice(first_pos);
      return ret;
    };

    Ring.prototype.consume = function(n) {
      var b;
      if (this._bufs.length === 0 || (b = this._bufs[0]).length < n) {
        throw new Error("Ring underflow; can't remove " + n + " bytes");
      }
      if (b.length === n) {
        this._bufs = this._bufs.slice(1);
      } else {
        this._bufs[0] = b.slice(n);
      }
      return this._len -= n;
    };

    return Ring;

  })();

}).call(this);
