Created
November 15, 2011 00:18
-
-
Save eric/1365667 to your computer and use it in GitHub Desktop.
Generational hash table — useful for in-memory caches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# by Eric Lindvall <[email protected]> | |
# | |
class LruGenerationalHash | |
attr_reader :max_size | |
def initialize(max_size, generations = 2) | |
@generations = generations.times.collect { Hash.new } | |
@max_size = max_size | |
end | |
def clear | |
@generations.each { |hash| hash.clear } | |
end | |
def max_size=(value) | |
@max_size = value | |
rotate | |
@max_size | |
end | |
def size | |
@generations.inject(0) { |memo, hash| memo + hash.size } | |
end | |
def []=(key, value) | |
rotate | |
@generations.each_with_index do |hash, idx| | |
if idx == @generations.length - 1 | |
hash[key] = value | |
else | |
hash.delete(key) | |
end | |
end | |
value | |
end | |
def [](key) | |
@generations.each_with_index do |hash, idx| | |
if idx == 0 | |
if value = hash[key] | |
return value | |
end | |
else | |
if value = hash.delete(key) | |
@generations[idx - 1][key] = value | |
return value | |
end | |
end | |
end | |
nil | |
end | |
def delete(key) | |
@generations.each do |hash| | |
hash.delete(key) | |
end | |
end | |
def merge!(hash) | |
hash.each { |k,v| self[k] = v } | |
end | |
private | |
def rotate | |
if size >= @max_size | |
@generations.unshift(Hash.new) | |
@generations.pop | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment