lib/rufus/lru.rb in rufus-lru-1.0.7 vs lib/rufus/lru.rb in rufus-lru-1.1.0
- old
+ new
@@ -26,11 +26,11 @@
module Rufus
module Lru
- VERSION = '1.0.7'
+ VERSION = '1.1.0'
#
# A Hash that has a max size. After the maxsize has been reached, the
# least recently used entries (LRU hence), will be discared to make
# room for the new entries.
@@ -86,10 +86,12 @@
# * A lambda/proc can be set, it's thus called (and passed the removed
# value as argument) each time a removal occurs
#
def initialize(maxsize, opts={})
+ fail ArgumentError.new("maxsize must be >= 0") if maxsize < 0
+
super()
@maxsize = maxsize
@lru_keys = []
@@ -105,12 +107,11 @@
i
end
def auto_squeeze=(b)
- squeeze! if b
- @auto_squeeze = b
+ squeeze! if (@auto_squeeze = b)
end
def auto_squeeze?
@auto_squeeze
@@ -138,14 +139,13 @@
super
end
def []=(key, value)
- remove_lru if @auto_squeeze
- touch(key)
-
super
+ touch(key)
+ do_squeeze! if @auto_squeeze
end
def merge!(hash)
hash.each { |k, v| self[k] = v }
@@ -168,12 +168,11 @@
def to_h
{}.merge!(self)
end
- # public alias to remove_lru
- def squeeze!; remove_lru; end
+ def squeeze!; do_squeeze!; end
protected
# Puts the key on top of the lru 'stack'.
# The bottom being the lru place.
@@ -185,14 +184,14 @@
end
# Makes sure that the hash fits its maxsize. If not, will remove
# the least recently used items.
#
- def remove_lru
+ def do_squeeze!
- while size >= @maxsize
- delete(@lru_keys.delete_at(0))
+ while size > @maxsize
+ delete(@lru_keys.shift)
end
end
def call_on_removal(value)
@@ -227,10 +226,10 @@
@mutex.synchronize { super }
end
def squeeze!
- @mutex.synchronize { super }
+ @mutex.synchronize { do_squeeze! }
end
end
end
end