lib/lru_redux/cache.rb in lru_redux-0.8.1 vs lib/lru_redux/cache.rb in lru_redux-0.8.2
- old
+ new
@@ -26,21 +26,21 @@
node = @data[key]
if node
move_to_head(node)
node[2]
else
- self[key] = yield
+ self[key] = yield
end
end
def fetch(key)
node = @data[key]
if node
move_to_head(node)
node[2]
else
- yield if block_given?
+ yield if block_given?
end
end
def [](key)
node = @data[key]
@@ -61,31 +61,49 @@
end
val
end
def each
- if n = @head
+ a = to_a
+ a.each do |pair|
+ yield pair
+ end
+ end
+
+ def each_unsafe
+ n = @head
+ if n
while n
yield [n[1], n[2]]
n = n[0]
end
end
end
- # used further up the chain, non thread safe each
- alias_method :each_unsafe, :each
-
def to_a
a = []
self.each_unsafe do |k,v|
a << [k,v]
end
a
end
- def delete(k)
- if node = @data.delete(k)
+ def delete(key)
+ node = @data.delete(key)
+ return unless node
+
+ if node[3].nil?
+ @head = @head[0]
+ if @head.nil?
+ @tail = nil
+ else
+ @head[3] = nil
+ end
+ elsif node[0].nil?
+ @tail = @tail[3]
+ @tail[0] = nil
+ else
prev = node[0]
nex = node[3]
prev[3] = nex if prev
nex[0] = prev if nex
@@ -96,23 +114,21 @@
@data.clear
@head = @tail = nil
end
def count
- @data.count
+ @data.size
end
# for cache validation only, ensures all is sound
def valid?
- expected = {}
-
count = 0
self.each_unsafe do |k,v|
return false if @data[k][2] != v
count += 1
end
- count == @data.count
+ count == @data.size
end
protected
def add_to_head(key,val)
@@ -151,7 +167,6 @@
@tail = @tail[3]
@tail[0] = nil
true
end
end
-
end