Class: HexaPDF::Utils::LRUCache

Inherits:
Object
  • Object
show all
Defined in:
lib/hexapdf/utils/lru_cache.rb

Overview

A simple least recently used (LRU) cache.

The cache relies on the fact that Ruby’s Hash class maintains insertion order. So deleting and re-inserting a key-value pair on access moves the key to the last position. When an entry is added and the cache is full, the first entry is removed.

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ LRUCache

Creates a new LRUCache that can hold size entries.



48
49
50
51
# File 'lib/hexapdf/utils/lru_cache.rb', line 48

def initialize(size)
  @size = size
  @cache = {}
end

Instance Method Details

#[](key) ⇒ Object

Returns the stored value for key or nil if no value was stored under the key.



54
55
56
# File 'lib/hexapdf/utils/lru_cache.rb', line 54

def [](key)
  (val = @cache.delete(key)).nil? ? nil : @cache[key] = val
end

#[]=(key, value) ⇒ Object

Stores the value under the key.



59
60
61
62
63
# File 'lib/hexapdf/utils/lru_cache.rb', line 59

def []=(key, value)
  @cache.delete(key)
  @cache[key] = value
  @cache.shift if @cache.length > @size
end