Class: Literal::LRU

Inherits:
Object
  • Object
show all
Defined in:
lib/literal/lru.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size, key_type:, value_type:) ⇒ LRU

Returns a new instance of LRU.



4
5
6
7
8
9
10
11
12
# File 'lib/literal/lru.rb', line 4

def initialize(max_size, key_type:, value_type:)
	@hash = {}
	@mutex = Mutex.new
	@max_size = max_size
	@key_type = key_type
	@value_type = value_type

	freeze
end

Instance Attribute Details

#key_typeObject (readonly)

Returns the value of attribute key_type.



14
15
16
# File 'lib/literal/lru.rb', line 14

def key_type
  @key_type
end

#value_typeObject (readonly)

Returns the value of attribute value_type.



14
15
16
# File 'lib/literal/lru.rb', line 14

def value_type
  @value_type
end

Instance Method Details

#[](key) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/literal/lru.rb', line 16

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

#[]=(key, value) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/literal/lru.rb', line 25

def []=(key, value)
	unless @key_type === key
		raise Literal::TypeError.expected(key, to_be_a: @key_type)
	end

	unless @value_type === value
		raise Literal::TypeError.expected(value, to_be_a: @value_type)
	end

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

		@hash.shift if @hash.size > @max_size
	end
end

#clearObject



70
71
72
73
74
# File 'lib/literal/lru.rb', line 70

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

#compute_if_absent(key) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/literal/lru.rb', line 52

def compute_if_absent(key)
	@mutex.synchronize do
		if @hash.include?(key)
			@hash[key]
		else
			@hash[key] = yield
		end
	end
end

#delete(key) ⇒ Object



42
43
44
45
46
# File 'lib/literal/lru.rb', line 42

def delete(key)
	@mutex.synchronize do
		@hash.delete(key)
	end
end

#empty?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/literal/lru.rb', line 66

def empty?
	@hash.empty?
end

#include?(key) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/literal/lru.rb', line 48

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

#sizeObject



62
63
64
# File 'lib/literal/lru.rb', line 62

def size
	@hash.size
end