Object
Hash with LRU expiry policy. There are at most max_size elements in a LRUHash. When adding more elements old elements are removed according to LRU policy.
github.com/rklemme/muppet-laboratories/blob/master/lib/lruhash.rb Copyright (c) 2010 Robert Klemme
# File lib/hashery/lruhash.rb, line 80 def [](key) fetch(key) do |k| @default_proc ? @default_proc[self, k] : default end end
# File lib/hashery/lruhash.rb, line 116 def assoc(key) n = @h[key] if n front(n) [n.key, n.value] end end
# File lib/hashery/lruhash.rb, line 183 def clear until empty? delete_oldest end self end
# File lib/hashery/lruhash.rb, line 163 def delete(key) n = @h[key] and remove_node(n).value end
# File lib/hashery/lruhash.rb, line 167 def delete_if each_node do |n| remove_node n if yield n.key, n.value end end
# File lib/hashery/lruhash.rb, line 42 def each_key if block_given? each_node do |n| yield n.key end else enum_for :each_key end end
# File lib/hashery/lruhash.rb, line 30 def each_pair if block_given? each_node do |n| yield [n.key, n.value] end else enum_for :each_pair end end
# File lib/hashery/lruhash.rb, line 52 def each_value if block_given? each_node do |n| yield n.value end else enum_for :each_value end end
# File lib/hashery/lruhash.rb, line 66 def empty? @head.succ.equal? @tail end
# File lib/hashery/lruhash.rb, line 70 def fetch(key, &b) n = @h[key] if n front(n).value else (b || FETCH)[key] end end
# File lib/hashery/lruhash.rb, line 94 def has_key?(key) @h.has_key? key end
# File lib/hashery/lruhash.rb, line 102 def has_value?(value) each_pair do |k, v| return true if value.eql? v end false end
# File lib/hashery/lruhash.rb, line 135 def key(value) pair = rassoc(value) and pair.first end
# File lib/hashery/lruhash.rb, line 173 def max_size=(limit) limit = normalize_max(limit) while size > limit delete_oldest end @max_size = limit end
# File lib/hashery/lruhash.rb, line 125 def rassoc(value) each_node do |n| if value.eql? n.value front(n) return [n.key, n.value] end end nil end
# File lib/hashery/lruhash.rb, line 139 def store(key, value) # same optimization as in Hash key = key.dup.freeze if String === key && !key.frozen? n = @h[key] unless n if size == max_size # reuse node to optimize memory usage n = delete_oldest n.key = key n.value = value else n = Node.new key, value end @h[key] = n end front(n).value = value end
# File lib/hashery/lruhash.rb, line 191 def to_s s = nil each_pair {|k, v| (s ? (s << ', ') : s = '{') << k.to_s << '=>' << v.to_s} s ? (s << '}') : '{}' end
Generated with the Darkfish Rdoc Generator 2.