Class: Datadog::AppSec::APISecurity::LRUCache

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/datadog/appsec/api_security/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.

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/appsec/api_security/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/appsec/api_security/lru_cache.rb', line 27

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

#fetch_or_store(key) ⇒ Object

NOTE: If the key exists, it’s moved to the end of the list and

if does not, the given block will be executed and the result
will be stored (which will add it to the end of the list).


36
37
38
39
40
41
42
43
44
45
# File 'lib/datadog/appsec/api_security/lru_cache.rb', line 36

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

  # NOTE: evict the oldest entry if store reached the maximum allowed size
  @store.shift if @store.size >= @max_size

  @store[key] ||= yield
end