mustermann 0.2.0 → 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,46 +0,0 @@
1
- module Mustermann
2
- # A simple wrapper around ObjectSpace::WeakMap that allows matching keys by equality rather than identity.
3
- # Used for caching.
4
- #
5
- # @see #fetch
6
- # @!visibility private
7
- class EqualityMap
8
- # @!visibility private
9
- def initialize
10
- @keys = {}
11
- @map = ObjectSpace::WeakMap.new
12
- end
13
-
14
- # @param [Array<#hash>] key for caching
15
- # @yield block that will be called to populate entry if missing
16
- # @return value stored in map or result of block
17
- # @!visibility private
18
- def fetch(*key)
19
- identity = @keys[key.hash]
20
- key = identity == key ? identity : key
21
-
22
- # it is ok that this is not thread-safe, worst case it has double cost in
23
- # generating, object equality is not guaranteed anyways
24
- @map[key] ||= track(key, yield)
25
- end
26
-
27
- # @param [#hash] key for identifying the object
28
- # @param [Object] object to be stored
29
- # @return [Object] same as the second parameter
30
- def track(key, object)
31
- ObjectSpace.define_finalizer(object, finalizer(hash))
32
- @keys[key.hash] = key
33
- object
34
- end
35
-
36
- # Finalizer proc needs to be generated in different scope so it doesn't keep a reference to the object.
37
- #
38
- # @param [Fixnum] hash for key
39
- # @return [Proc] finalizer callback
40
- def finalizer(hash)
41
- proc { @keys.delete(hash) }
42
- end
43
-
44
- private :track, :finalizer
45
- end
46
- end