lib/phlex/fifo.rb

Lines

90%

39 of 43 covered

Branches

84%

11 of 13 covered

Methods

88%

8 of 9 covered

Not run
74-77
Never called
1# frozen_string_literal: true
2
3# @api private
41class Phlex::FIFO
5 # The byte limits account for cached values, excluding keys and object overhead.
61 def initialize(max_bytesize: 2_000, max_value_bytesize: 2_000)
7126 @store = {}
8126 @max_bytesize = max_bytesize
9126 @max_value_bytesize = max_value_bytesize
10126 @bytesize = 0
11126 @mutex = Monitor.new
12 end
13
141 attr_reader :bytesize, :max_bytesize
15
161 def expand(bytes)
17123 @mutex.synchronize do
18123 @max_bytesize += bytes
19 end
20 end
21
221 def grow_to(bytes)
23803 @mutex.synchronize do
24803 @max_bytesize = bytes if bytes > @max_bytesize
25 end
26 end
27
281 def [](key)
29242 k, v = @store[key.hash]
30242 v if k.eql?(key)
31 end
32
33 # Returns the cached value for `key`, or yields to generate it and caches the
34 # result. Unlike `fifo[key] ||= value`, the key is only hashed once.
351 def fetch(key)
361010 digest = key.hash
371010 if (entry = @store[digest])
386 k, v = entry
396 return v if k.eql?(key)else never taken
40 end
41
421004 value = yield
431004 store(digest, key, value)
441004 value
45 end
46
471 def []=(key, value)
481222 store(key.hash, key, value)
49 end
50
511 private def store(digest, key, value)
522474 bytesize = value.bytesize
53 # Empty values would retain keys without consuming the eviction budget.
542474 return if bytesize.zero? || bytesize > @max_value_bytesize
55
56471 @mutex.synchronize do
57 # Check the key definitely doesn't exist now we have the lock
58471 return if @store[digest]then never taken
59
60471 @store[digest] = [key, value].freeze
61471 @bytesize += bytesize
62
63471 while @bytesize > @max_bytesize
6498 _k, v = @store.shift
6598 @bytesize -= v[1].bytesize
66 end
67 end
68 end
69
701 def size
7111 @store.size
72 end
73
740 def clear
750 @mutex.synchronize do
760 @store.clear
770 @bytesize = 0
78 end
79 end
80end