# Copyright: Copyright (c) 2004 Nicolas Despres. All rights reserved. # Author: Nicolas Despres . # License: Gnu General Public License. # $LastChangedBy: ertai $ # $Id: spring_set.rb 186 2005-04-03 00:07:45Z ertai $ require 'spring' class SpringSet def initialize(*springs) @springs = {} springs.flatten.each do |s| @springs[s.object_id] = { :spring => s, :num_collecter => s.num_collecter, :size => s.size } s.add_observer(self) end end def update(spring_id, msg, collecter_id) case msg when Spring::SIGN_UP @springs[spring_id][:num_collecter] += 1 when Spring::GET @springs[spring_id][:size] -= 1 if @springs[spring_id][:size] > 0 end end def get_most_free calc_stat(:num_collecter) { |a, b| a < b } end def get_most_busy calc_stat(:num_collecter) { |a, b| a > b } end def get_most_full calc_stat(:size) { |a, b| a > b } end def get_most_empty calc_stat(:size) { |a, b| a < b } end def size @springs.size end alias length size def num_collecter(spring_id) @springs[spring_id][:num_collecter] end def spring_size(spring_id) @springs[spring_id][:size] end alias spring_length spring_size def each @springs.values.each { |v| yield(v[:spring]) } end protected def calc_stat(field, &cmp) spring = nil @springs.values.each do |s| if spring.nil? or cmp[s[field], spring[field]] spring = s end end return spring[:spring] end end # class SpringSet # # Unit test suite # if defined? TEST_MODE or $0 == __FILE__ require 'test/unit/ui/yaml/testrunner' class SpringSetTest < Test::Unit::TestCase # # tests # def test_simple s1 = Spring.new('hello', 'world') s2 = Spring.new('bonjour', 'tout', 'monde') s = SpringSet.new(s1, s2) assert_equal(s1.num_collecter, s.num_collecter(s1.object_id)) assert_equal(s2.num_collecter, s.num_collecter(s2.object_id)) assert_equal(s1.size, s.spring_size(s1.object_id)) assert_equal(s2.length, s.spring_length(s2.object_id)) thread = Thread.new do sleep(0.0001) assert_equal(2, s.size) assert_equal(2, s.length) assert_equal(s2, s.get_most_full) assert_equal(s1, s.get_most_empty) s1.sign_up(thread.object_id) assert_equal(s1.num_collecter, s.num_collecter(s1.object_id)) assert_equal(s1, s.get_most_busy) assert_equal(s2, s.get_most_free) s2.sign_up(thread.object_id) assert_equal(s2.num_collecter, s.num_collecter(s2.object_id), 'bad num collecter') assert_equal('bonjour', s2.get(thread.object_id)) assert_equal(s2.size, s.spring_size(s2.object_id), 'bad size') assert_equal('tout', s2.get(thread.object_id)) assert_equal(s2.size, s.spring_size(s2.object_id)) assert_equal('monde', s2.get(thread.object_id)) assert_equal(s2.size, s.spring_size(s2.object_id)) assert_equal(nil, s2.get(thread.object_id)) assert_equal(s2.size, s.spring_size(s2.object_id)) assert_equal(0, s.spring_size(s2.object_id)) assert_equal(s1, s.get_most_full) assert_equal(s2, s.get_most_empty) end thread.join end end # class SpringSetTest end