Class: N::LRUCache

Inherits:
Hash
  • Object
show all
Defined in:
lib/n/utils/cache.rb

Overview

LRUCache

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

Instance Method Summary collapse

Constructor Details

#initialize(max_items) ⇒ LRUCache

Returns a new instance of LRUCache.



46
47
48
49
# File 'lib/n/utils/cache.rb', line 46

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

Instance Attribute Details

#headObject (readonly)

the head sentinel



40
41
42
# File 'lib/n/utils/cache.rb', line 40

def head
  @head
end

#max_itemsObject

the maximum number of items in the cache



37
38
39
# File 'lib/n/utils/cache.rb', line 37

def max_items
  @max_items
end

#tailObject (readonly)

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



42
43
44
# File 'lib/n/utils/cache.rb', line 42

def tail
  @tail
end

Instance Method Details

#[](key) ⇒ Object

Lookup an item in the cache



53
54
55
56
57
# File 'lib/n/utils/cache.rb', line 53

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

#[]=(key, item) ⇒ Object

The inserted item is considered mru!



61
62
63
64
65
# File 'lib/n/utils/cache.rb', line 61

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

#clearObject

Clear the cache



77
78
79
80
# File 'lib/n/utils/cache.rb', line 77

def clear
	super
	lru_clear()
end

#delete(key) ⇒ Object

Delete an item from the cache



69
70
71
72
73
# File 'lib/n/utils/cache.rb', line 69

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

#firstObject

The first (mru) element in the cache



84
85
86
# File 'lib/n/utils/cache.rb', line 84

def first
	@head.lru_next
end

#lastObject Also known as: lru

The last (lru) element in the cache



90
91
92
# File 'lib/n/utils/cache.rb', line 90

def last
	@tail.lru_prev
end