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 module SBDB
# See http://eigenclass.org/hiki/deferred-finalizers-in-Ruby # See http://eigenclass.org/hiki/deferred-finalizers-in-Ruby
# Not threadsafe.
class WeakHash class WeakHash
attr_reader :cache attr_reader :cache
def initialize( cache = Hash.new ) def initialize cache = Hash.new
@cache = cache @cache = cache
@key_map = {} @key_map = {}
@rev_cache = Hash.new{|h,k| h[k] = {}} @rev_cache = Hash.new{|h,k| h[k] = {}}
@ -21,28 +22,41 @@ class WeakHash
end end
end end
def []( key ) def []= key, value
value_id = @cache[key] case key
return ObjectSpace._id2ref(value_id) unless value_id.nil? when Fixnum, Symbol, true, false
nil key2 = key
rescue RangeError else
nil key2 = key.dup
end end
@rev_cache[value.object_id][key2] = true
@cache[key2] = value.object_id
@key_map[key.object_id] = key2
def []=( key, value ) ObjectSpace.define_finalizer(value, @reclaim_value)
case key ObjectSpace.define_finalizer(key, @reclaim_key)
when Fixnum, Symbol, true, false end
key2 = key
else
key2 = key.dup
end
@rev_cache[value.object_id][key2] = true
@cache[key2] = value.object_id
@key_map[key.object_id] = key2
ObjectSpace.define_finalizer(value, @reclaim_value) def [] key
ObjectSpace.define_finalizer(key, @reclaim_key) value_id = @cache[key]
end 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
end end