1998-01-16 15:19:09 +03:00
|
|
|
# Weak Reference class that does not bother GCing.
|
|
|
|
#
|
|
|
|
# Usage:
|
|
|
|
# foo = Object.new
|
|
|
|
# foo.hash
|
|
|
|
# foo = WeakRef.new(foo)
|
|
|
|
# foo.hash
|
|
|
|
# ObjectSpace.garbage_collect
|
|
|
|
# foo.hash # => Raises WeakRef::RefError (because original GC'ed)
|
|
|
|
|
|
|
|
require "delegate"
|
|
|
|
|
1999-01-20 07:59:39 +03:00
|
|
|
class WeakRef<Delegator
|
1998-01-16 15:19:09 +03:00
|
|
|
|
1999-01-20 07:59:39 +03:00
|
|
|
class RefError<StandardError
|
|
|
|
end
|
1998-01-16 15:19:09 +03:00
|
|
|
|
|
|
|
ID_MAP = {}
|
|
|
|
ID_REV_MAP = {}
|
|
|
|
ObjectSpace.add_finalizer(lambda{|id|
|
|
|
|
rid = ID_MAP[id]
|
|
|
|
if rid
|
|
|
|
ID_REV_MAP[rid] = nil
|
|
|
|
ID_MAP[id] = nil
|
|
|
|
end
|
|
|
|
rid = ID_REV_MAP[id]
|
|
|
|
if rid
|
|
|
|
ID_REV_MAP[id] = nil
|
|
|
|
ID_MAP[rid] = nil
|
|
|
|
end
|
|
|
|
})
|
|
|
|
|
|
|
|
def initialize(orig)
|
|
|
|
super
|
1999-01-20 07:59:39 +03:00
|
|
|
@__id = orig.__id__
|
1998-01-16 15:19:09 +03:00
|
|
|
ObjectSpace.call_finalizer orig
|
1999-01-20 07:59:39 +03:00
|
|
|
ObjectSpace.call_finalizer self
|
|
|
|
ID_MAP[@__id] = self.__id__
|
|
|
|
ID_REV_MAP[self.id] = @__id
|
1998-01-16 15:19:09 +03:00
|
|
|
end
|
|
|
|
|
|
|
|
def __getobj__
|
1999-01-20 07:59:39 +03:00
|
|
|
unless ID_MAP[@__id]
|
|
|
|
raise RefError, "Illegal Reference - probably recycled", caller(2)
|
1998-01-16 15:19:09 +03:00
|
|
|
end
|
1999-01-20 07:59:39 +03:00
|
|
|
ObjectSpace._id2ref(@__id)
|
1998-01-16 15:19:09 +03:00
|
|
|
end
|
|
|
|
|
|
|
|
def weakref_alive?
|
1999-01-20 07:59:39 +03:00
|
|
|
if ID_MAP[@__id]
|
1998-01-16 15:19:09 +03:00
|
|
|
true
|
|
|
|
else
|
|
|
|
false
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def []
|
|
|
|
__getobj__
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
1999-01-20 07:59:39 +03:00
|
|
|
if __FILE__ == $0
|
|
|
|
foo = Object.new
|
|
|
|
p foo.hash # original's hash value
|
|
|
|
foo = WeakRef.new(foo)
|
|
|
|
p foo.hash # should be same hash value
|
|
|
|
ObjectSpace.garbage_collect
|
|
|
|
p foo.hash # should raise exception (recycled)
|
|
|
|
end
|