Class: Jpzip::MemoryLRU

Inherits:
Object
  • Object
show all
Defined in:
lib/jpzip/cache.rb

Overview

MemoryLRU is the L1 in-memory cache, bounded by a fixed number of prefix entries. It is safe for concurrent use.

Constant Summary collapse

DEFAULT_CAPACITY =
100

Instance Method Summary collapse

Constructor Details

#initialize(capacity = DEFAULT_CAPACITY) ⇒ MemoryLRU

Returns a new instance of MemoryLRU.



38
39
40
41
42
43
44
# File 'lib/jpzip/cache.rb', line 38

def initialize(capacity = DEFAULT_CAPACITY)
  @capacity = capacity < 1 ? 1 : capacity
  # Ruby's Hash preserves insertion order, so it doubles as an LRU index:
  # touch on read by deleting + re-inserting at the tail.
  @items = {}
  @mu = Monitor.new
end

Instance Method Details

#clearObject



69
70
71
72
# File 'lib/jpzip/cache.rb', line 69

def clear
  @mu.synchronize { @items.clear }
  nil
end

#delete(key) ⇒ Object



65
66
67
# File 'lib/jpzip/cache.rb', line 65

def delete(key)
  @mu.synchronize { @items.delete(key) }
end

#get(key) ⇒ Object



46
47
48
49
50
51
52
53
54
# File 'lib/jpzip/cache.rb', line 46

def get(key)
  @mu.synchronize do
    return nil unless @items.key?(key)

    value = @items.delete(key)
    @items[key] = value
    value
  end
end

#set(key, value) ⇒ Object



56
57
58
59
60
61
62
63
# File 'lib/jpzip/cache.rb', line 56

def set(key, value)
  @mu.synchronize do
    @items.delete(key) if @items.key?(key)
    @items[key] = value
    @items.shift while @items.size > @capacity
    nil
  end
end

#sizeObject



74
75
76
# File 'lib/jpzip/cache.rb', line 74

def size
  @mu.synchronize { @items.size }
end