#
# recycle.rb
#
#   Copyright (c) 1999-2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
#
#   This program is free software.
#   You can distribute/modify this program under the terms of
#   the GNU General Public License version 2 or later.
#


module Recyclable

  BEGIN_GC_SIZE = 5


  def self.append_features( mod )
    super

    mod.module_eval %-
      @spare = []
      @begin_gc = 5
    -

    def mod.new( *args, &block )
      gavage_collect

      unless @spare.empty? then
        obj = @spare.pop  # recycle
        obj.reset( *args, &block )
      else
        obj = super         # create
      end

      obj
    end

    def mod.use_instance( *args )
      obj = new( *args )
      yield obj
      obj.type.finished obj
    end

    def mod.finished( obj )
      @spare.push obj
      gavage_collect
    end

    private

    def mod.gavage_collect
      if @spare.size > @begin_gc then
        @spare = @spare[ 0, @spare.size / 2 ]
      end
    end
  end

end
