Skip to content

Commit

Permalink
Add an LRU cache
Browse files Browse the repository at this point in the history
  • Loading branch information
joeldrapper committed Feb 2, 2024
1 parent 29fb05b commit d47ae75
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/phlex.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ module Phlex
autoload :Unbuffered, "phlex/unbuffered"
autoload :ConcurrentMap, "phlex/concurrent_map"
autoload :BlackHole, "phlex/black_hole"
autoload :LRU, "phlex/lru"

# Included in all Phlex exceptions allowing you to match any Phlex error.
# @example Rescue any Phlex error:
Expand Down
69 changes: 69 additions & 0 deletions lib/phlex/lru.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# frozen_string_literal: true

class Phlex::LRU
def initialize(max_byte_size)
@hash = {}
@mutex = Mutex.new

@size = 0
@max_byte_size = max_byte_size
end

def [](key)
@mutex.synchronize do
if (value = @hash[key])
@hash.delete(key)
@hash[key] = value
end
end
end

def []=(key, value)
@mutex.synchronize do
old_value = @hash.delete(key)
@hash[key] = value

@size += value.bytesize - (old_value ? old_value.bytesize : 0)

while @size > @max_byte_size
key, value = @hash.shift
@size -= value.bytesize
end
end
end

def delete(key)
@mutex.synchronize do
old_value = @hash.delete(key)
@size -= old_value.bytesize if old_value
end
end

def include?(key)
@hash.include?(key)
end

def fetch(key)
@mutex.synchronize do
if (value = @hash[key])
value
else
@hash[key] = yield
end
end
end

def size
@hash.size
end

def empty?
@hash.empty?
end

def clear
@mutex.synchronize do
@hash.clear
end
end
end

0 comments on commit d47ae75

Please sign in to comment.