Class: Texd::Cache
- Inherits:
-
Object
- Object
- Texd::Cache
- Defined in:
- lib/texd/cache.rb
Overview
Cache is a simple LRU cache with a double linked list. If the cache is full the last element from the list will be removed.
Defined Under Namespace
Classes: LinkedList, Node
Instance Attribute Summary collapse
-
#capacity ⇒ Object
readonly
Returns the value of attribute capacity.
-
#count ⇒ Object
readonly
Returns the value of attribute count.
-
#list ⇒ Object
readonly
Returns the value of attribute list.
Instance Method Summary collapse
- #fetch(key) ⇒ Object
-
#initialize(capacity) ⇒ Cache
constructor
A new instance of Cache.
- #read(key) ⇒ Object
- #write(key, value) ⇒ Object
Constructor Details
#initialize(capacity) ⇒ Cache
Returns a new instance of Cache.
48 49 50 51 52 53 54 |
# File 'lib/texd/cache.rb', line 48 def initialize(capacity) @list = LinkedList.new @hash = {} @mtx = Mutex.new @count = 0 @capacity = capacity end |
Instance Attribute Details
#capacity ⇒ Object (readonly)
Returns the value of attribute capacity.
45 46 47 |
# File 'lib/texd/cache.rb', line 45 def capacity @capacity end |
#count ⇒ Object (readonly)
Returns the value of attribute count.
45 46 47 |
# File 'lib/texd/cache.rb', line 45 def count @count end |
#list ⇒ Object (readonly)
Returns the value of attribute list.
45 46 47 |
# File 'lib/texd/cache.rb', line 45 def list @list end |
Instance Method Details
#fetch(key) ⇒ Object
56 57 58 |
# File 'lib/texd/cache.rb', line 56 def fetch(key) read(key) || write(key, yield) end |
#read(key) ⇒ Object
60 61 62 63 64 65 66 67 68 69 |
# File 'lib/texd/cache.rb', line 60 def read(key) @mtx.synchronize do node = @hash[key] return unless node list.remove(node) list.add(node) node.value end end |
#write(key, value) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/texd/cache.rb', line 71 def write(key, value) @mtx.synchronize do node = @hash[key] if node list.remove(node) else node = add_node(key) end list.add(node) node.value = value end end |