Class: N::LRUCache
Overview
A cache utilizing a simple LRU (Least Recently Used) policy. The items managed by this cache must respond to the #key method. Attempts to optimize reads rather than inserts!
LRU semantics are enforced by inserting the items in a queue. The lru item is always at the tail. Two special sentinels (head, tail) are used to simplify (?) the code.
Defined Under Namespace
Modules: Item Classes: Sentinel
Instance Attribute Summary collapse
-
#head ⇒ Object
readonly
the head sentinel.
-
#max_items ⇒ Object
the maximum number of items in the cache.
-
#tail ⇒ Object
readonly
the tail sentinel, tail.prev points to the lru item.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Lookup an item in the cache.
-
#[]=(key, item) ⇒ Object
The inserted item is considered mru!.
-
#clear ⇒ Object
Clear the cache.
-
#delete(key) ⇒ Object
Delete an item from the cache.
-
#first ⇒ Object
The first (mru) element in the cache.
-
#initialize(max_items) ⇒ LRUCache
constructor
A new instance of LRUCache.
-
#last ⇒ Object
(also: #lru)
The last (lru) element in the cache.
Constructor Details
#initialize(max_items) ⇒ LRUCache
Returns a new instance of LRUCache.
40 41 42 43 |
# File 'lib/glue/cache.rb', line 40 def initialize(max_items) @max_items = max_items lru_clear() end |
Instance Attribute Details
#head ⇒ Object (readonly)
the head sentinel
34 35 36 |
# File 'lib/glue/cache.rb', line 34 def head @head end |
#max_items ⇒ Object
the maximum number of items in the cache.
30 31 32 |
# File 'lib/glue/cache.rb', line 30 def max_items @max_items end |
#tail ⇒ Object (readonly)
the tail sentinel, tail.prev points to the lru item.
38 39 40 |
# File 'lib/glue/cache.rb', line 38 def tail @tail end |
Instance Method Details
#[](key) ⇒ Object
Lookup an item in the cache.
47 48 49 50 51 |
# File 'lib/glue/cache.rb', line 47 def [](key) if item = super return lru_touch(item) end end |
#[]=(key, item) ⇒ Object
The inserted item is considered mru!
55 56 57 58 59 |
# File 'lib/glue/cache.rb', line 55 def []=(key, item) item = super item.lru_key = key lru_insert(item) end |
#clear ⇒ Object
Clear the cache.
71 72 73 74 |
# File 'lib/glue/cache.rb', line 71 def clear super lru_clear() end |
#delete(key) ⇒ Object
Delete an item from the cache.
63 64 65 66 67 |
# File 'lib/glue/cache.rb', line 63 def delete(key) if item = super lru_delete(item) end end |
#first ⇒ Object
The first (mru) element in the cache.
78 79 80 |
# File 'lib/glue/cache.rb', line 78 def first @head.lru_next end |
#last ⇒ Object Also known as: lru
The last (lru) element in the cache.
84 85 86 |
# File 'lib/glue/cache.rb', line 84 def last @tail.lru_prev end |