Class: LRUCache

Inherits:
Hash show all
Defined in:
lib/mega/lru_cache.rb

Overview

:title: Least Recently Used Cache

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.

Usage

TODO: If you have an example of using this, please submit. -T

Author(s)

Defined Under Namespace

Modules: Item Classes: Sentinel

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DupReplaceSnapshotMixin

#restore_snapshot, #take_snapshot

Constructor Details

#initialize(max_items) ⇒ LRUCache

Returns a new instance of LRUCache.



63
64
65
66
# File 'lib/mega/lru_cache.rb', line 63

def initialize(max_items)
  @max_items = max_items
  lru_clear()
end

Instance Attribute Details

#headObject (readonly)

the head sentinel and the tail sentinel, tail.prev points to the lru item.



61
62
63
# File 'lib/mega/lru_cache.rb', line 61

def head
  @head
end

#max_itemsObject

the maximum number of items in the cache.



57
58
59
# File 'lib/mega/lru_cache.rb', line 57

def max_items
  @max_items
end

#tailObject (readonly)

the head sentinel and the tail sentinel, tail.prev points to the lru item.



61
62
63
# File 'lib/mega/lru_cache.rb', line 61

def tail
  @tail
end

Instance Method Details

#[](key) ⇒ Object

Lookup an item in the cache.



70
71
72
73
74
# File 'lib/mega/lru_cache.rb', line 70

def [](key)
  if item = super
    return lru_touch(item)
  end
end

#[]=(key, item) ⇒ Object

The inserted item is considered mru!



78
79
80
81
82
# File 'lib/mega/lru_cache.rb', line 78

def []=(key, item)
  item = super
  item.lru_key = key
  lru_insert(item)
end

#clearObject

Clear the cache.



94
95
96
97
# File 'lib/mega/lru_cache.rb', line 94

def clear
  super
  lru_clear()
end

#delete(key) ⇒ Object

Delete an item from the cache.



86
87
88
89
90
# File 'lib/mega/lru_cache.rb', line 86

def delete(key)
  if item = super
    lru_delete(item)
  end
end

#firstObject

The first (mru) element in the cache.



101
102
103
# File 'lib/mega/lru_cache.rb', line 101

def first
  @head.lru_next
end

#lastObject Also known as: lru

The last (lru) element in the cache.



107
108
109
# File 'lib/mega/lru_cache.rb', line 107

def last
  @tail.lru_prev
end