Class: Mayu::RefCounter
- Inherits:
-
Object
- Object
- Mayu::RefCounter
- Extended by:
- T::Generic, T::Sig
- Defined in:
- lib/mayu/ref_counter.rb
Constant Summary collapse
- Elem =
type_member
Instance Method Summary collapse
- #acquire(key, &block) ⇒ Object
- #acquire!(key) ⇒ Object
- #count(key) ⇒ Object
-
#initialize ⇒ RefCounter
constructor
A new instance of RefCounter.
- #keys ⇒ Object
- #release(key) ⇒ Object
Constructor Details
#initialize ⇒ RefCounter
Returns a new instance of RefCounter.
11 12 13 |
# File 'lib/mayu/ref_counter.rb', line 11 def initialize @refs = T.let(Hash.new { |h, k| h[k] = 0 }, T::Hash[Elem, Integer]) end |
Instance Method Details
#acquire(key, &block) ⇒ Object
35 36 37 38 39 40 41 42 43 |
# File 'lib/mayu/ref_counter.rb', line 35 def acquire(key, &block) acquire!(key) begin yield ensure release(key) end end |
#acquire!(key) ⇒ Object
26 27 28 |
# File 'lib/mayu/ref_counter.rb', line 26 def acquire!(key) @refs[key] = @refs[key].to_i + 1 end |
#count(key) ⇒ Object
16 17 18 |
# File 'lib/mayu/ref_counter.rb', line 16 def count(key) @refs.fetch(key, 0) end |
#keys ⇒ Object
21 22 23 |
# File 'lib/mayu/ref_counter.rb', line 21 def keys @refs.sort_by { _2 }.map(&:first) end |
#release(key) ⇒ Object
46 47 48 49 50 51 52 53 54 55 |
# File 'lib/mayu/ref_counter.rb', line 46 def release(key) count = @refs.fetch(key, nil) return unless count if count > 1 @refs[key] = count - 1 else @refs.delete(key) end end |