Class: Datadog::Core::Utils::LRUCache

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/datadog/core/utils/lru_cache.rb

Overview

An LRU (Least Recently Used) cache implementation that relies on the Ruby 1.9+ ‘Hash` implementation that guarantees insertion order.

WARNING: This implementation is NOT thread-safe and should be used

in a single-threaded context or guarded by Mutex.

Instance Method Summary collapse

Constructor Details

#initialize(max_size) ⇒ LRUCache

Returns a new instance of LRUCache.

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
# File 'lib/datadog/core/utils/lru_cache.rb', line 18

def initialize(max_size)
  raise ArgumentError, 'max_size must be an Integer' unless max_size.is_a?(Integer)
  raise ArgumentError, 'max_size must be greater than 0' if max_size <= 0

  @max_size = max_size
  @store = {}
end

Instance Method Details

#[](key) ⇒ Object

NOTE: Accessing a key moves it to the end of the list.



27
28
29
30
31
# File 'lib/datadog/core/utils/lru_cache.rb', line 27

def [](key)
  if (entry = @store.delete(key))
    @store[key] = entry
  end
end

#[]=(key, value) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/datadog/core/utils/lru_cache.rb', line 33

def []=(key, value)
  if @store.delete(key)
    @store[key] = value
  else
    # NOTE: evict the oldest entry if store reached the maximum allowed size
    @store.shift if @store.size >= @max_size
    @store[key] = value
  end
end