[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / lib / weakref.rb
bloba8da39a26aba2431daf61e01f10177061a641974
1 # frozen_string_literal: true
2 require "delegate"
4 # Weak Reference class that allows a referenced object to be
5 # garbage-collected.
7 # A WeakRef may be used exactly like the object it references.
9 # Usage:
11 #   foo = Object.new            # create a new object instance
12 #   p foo.to_s                  # original's class
13 #   foo = WeakRef.new(foo)      # reassign foo with WeakRef instance
14 #   p foo.to_s                  # should be same class
15 #   GC.start                    # start the garbage collector
16 #   p foo.to_s                  # should raise exception (recycled)
19 class WeakRef < Delegator
20   VERSION = "0.1.3"
22   ##
23   # RefError is raised when a referenced object has been recycled by the
24   # garbage collector
26   class RefError < StandardError
27   end
29   @@__map = ::ObjectSpace::WeakMap.new
31   ##
32   # Creates a weak reference to +orig+
34   def initialize(orig)
35     case orig
36     when true, false, nil
37       @delegate_sd_obj = orig
38     else
39       @@__map[self] = orig
40     end
41     super
42   end
44   def __getobj__ # :nodoc:
45     @@__map[self] or defined?(@delegate_sd_obj) ? @delegate_sd_obj :
46       Kernel::raise(RefError, "Invalid Reference - probably recycled", Kernel::caller(2))
47   end
49   def __setobj__(obj) # :nodoc:
50   end
52   ##
53   # Returns true if the referenced object is still alive.
55   def weakref_alive?
56     @@__map.key?(self) or defined?(@delegate_sd_obj)
57   end
58 end