added: Weakhash#each

This commit is contained in:
Denis Knauf 2010-02-02 10:50:04 +01:00
parent 0540eabcb4
commit 299978a9ed

View file

@ -1,10 +1,11 @@
module SBDB
# See http://eigenclass.org/hiki/deferred-finalizers-in-Ruby
# Not threadsafe.
class WeakHash
attr_reader :cache
def initialize( cache = Hash.new )
def initialize cache = Hash.new
@cache = cache
@key_map = {}
@rev_cache = Hash.new{|h,k| h[k] = {}}
@ -21,15 +22,7 @@ class WeakHash
end
end
def []( key )
value_id = @cache[key]
return ObjectSpace._id2ref(value_id) unless value_id.nil?
nil
rescue RangeError
nil
end
def []=( key, value )
def []= key, value
case key
when Fixnum, Symbol, true, false
key2 = key
@ -43,6 +36,27 @@ class WeakHash
ObjectSpace.define_finalizer(value, @reclaim_value)
ObjectSpace.define_finalizer(key, @reclaim_key)
end
def [] key
value_id = @cache[key]
return ObjectSpace._id2ref( value_id) unless value_id.nil?
nil
rescue RangeError
nil
end
def each &e
@cache.each do |k, vid|
unless vid.nil?
obj = begin
ObjectSpace._id2ref vid
rescue RangeError
next
end
yield k, obj
end
end
end
end
end