Class: Texd::Cache

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

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

#capacityObject (readonly)

Returns the value of attribute capacity.



45
46
47
# File 'lib/texd/cache.rb', line 45

def capacity
  @capacity
end

#countObject (readonly)

Returns the value of attribute count.



45
46
47
# File 'lib/texd/cache.rb', line 45

def count
  @count
end

#listObject (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