Created
May 20, 2013 11:26
-
-
Save rkh/5611706 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EqualityMap | |
def initialize | |
@keys = {} | |
@map = ObjectSpace::WeakMap.new | |
end | |
def fetch(*key) | |
identity = @keys[key.hash] | |
key = identity == key ? identity : key | |
@map[key] ||= track(key, yield) | |
end | |
def track(key, object) | |
ObjectSpace.define_finalizer(object, finalizer(hash)) | |
@keys[key.hash] = key | |
object | |
end | |
def finalizer(hash) | |
proc { @keys.delete(hash) } | |
end | |
private :track, :finalizer | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment