lib/timed_lru.rb in timed_lru-0.3.2 vs lib/timed_lru.rb in timed_lru-0.4.0

- old
+ new

@@ -26,19 +26,19 @@ # @option opts [Boolean] thread_safe # true by default, set to false if you are not using threads a *really* need # that extra bit of performance # @option opts [Integer] ttl # the TTL in seconds - def initialize(opts = {}) + def initialize(opts={}) super() # MonitorMixin @hash = {} @max_size = Integer(opts[:max_size] || 100) @ttl = Integer(opts[:ttl]) if opts[:ttl] - raise ArgumentError, "Option :max_size must be > 0" unless max_size > 0 - raise ArgumentError, "Option :ttl must be > 0" unless ttl.nil? || ttl > 0 + raise ArgumentError, 'Option :max_size must be > 0' unless max_size.positive? + raise ArgumentError, 'Option :ttl must be > 0' unless ttl.nil? || ttl.positive? extend ThreadUnsafe if opts[:thread_safe] == false end # Stores a `value` by `key` @@ -46,17 +46,17 @@ # @param [Object] value the associated value # @return [Object] the value def store(key, value) mon_synchronize do node = (@hash[key] ||= Node.new(key)) - node.value = value + node.value = value touch(node) compact! node.value end end - alias_method :[]=, :store + alias []= store # Retrieves a `value` by `key` # @param [Object] key the storage key # @return [Object,NilClass] value the associated value (or nil) def fetch(key) @@ -66,11 +66,11 @@ touch(node) node.value end end - alias_method :[], :fetch + alias [] fetch # Deletes by `key` # @param [Object] key the storage key # @return [Object,NilClass] value the deleted value (or nil) def delete(key) @@ -80,40 +80,38 @@ end end private - def compact! - while @hash.size > max_size - remove(@tail) - end + def compact! + remove(@tail) while @hash.size > max_size - while ttl && @tail.expires_at < Time.now.to_i - remove(@tail) - end - end + remove(@tail) while ttl && @tail.expires_at < Time.now.to_i + end - def remove(node) - @hash.delete(node.key) - left, right = node.left, node.right - left.nil? ? @head = right : left.right = right - right.nil? ? @tail = left : right.left = left - node - end + def remove(node) + @hash.delete(node.key) + left = node.left + right = node.right + left.nil? ? @head = right : left.right = right + right.nil? ? @tail = left : right.left = left + node + end - def touch(node) - node.expires_at = Time.now.to_i + ttl if ttl - return if node == @head + def touch(node) + node.expires_at = Time.now.to_i + ttl if ttl + return if node == @head - left, right = node.left, node.right - node.left, node.right = nil, @head - @head.left = node if @head + left = node.left + right = node.right + node.left = nil + node.right = @head + @head.left = node if @head - left.right = right if left - right.left = left if right + left.right = right if left + right.left = left if right - @tail = left if @tail == node - @head = node - @tail = @head unless @tail - end - + @tail = left if @tail == node + @head = node + @tail ||= @head + end end