class LRUCache(K, V)

Overview

LRU cache (Least Recently Used). LRUCache supports lifecycle, a global item size limit and an expiration time can be set for each item.

If a max_size is defined, the LRU cache can only contain max_size items. Beyond max_size, items are deleted from the oldest to the most recently used.

Defined in:

lru-cache.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(*, max_size : Int32? = nil) #

Creates a new LRUCache instance. If max_size is defined, the LRU cache can only contain max_size items. Beyond max_size, items are deleted from the oldest to the most recently used.


Instance Method Detail

def [](key : K) : V #

Same as #get!(key).


def []=(key : K, item : Tuple(V, Time?)) : LRUCache #

Same as set!(key, item)


def []=(key : K, value : V) : LRUCache #

Same as #set(key, value).


def []?(key : K) : V? #

Same as #get(key).


def add!(key : K, item : Tuple(V, Time?)) : LRUCache #

Adds an item in the cache. If key exists, this methods raises a KeyError exception.


def add!(key : K, value : V, expire_at : Time? = nil) : LRUCache #

Adds a value in the cache. If key exists, this methods raises a KeyError exception.


def clear : LRUCache #

Empties the cache.


def delete(key : K) : Tuple(V, Time?)? #

Deletes an item from the cache. Returns the deleted item or nil.


def expire_at!(key : K) : Time? #

Returns the expiration time of a key.


def get(key : K) : V? #

Get a value by its key. Returns the item value or nil.


def get!(key : K) : V #

If key does not exist, this methods raises a KeyError exception.


def has?(key : K) : Bool #

Checks if the cache has an item by its key. This method checks the item expiration but does not consider the item to be used (the order in the LRU cache is inchanged).


def items : Hash(K, Tuple(V, Time?)) #

Returns the Hash containing all items. The Hash can be handled normally without affecting the behavior of the LRU cache.


def keys : Array(K) #

Returns all keys.


def max_size : Int32? #

Returns the max items allowed in the cache.


def set(key : K, value : V, expire_at : Time? = nil) : LRUCache #

Sets a value in the cache.


def set(key : K, item : Tuple(V, Time?)) : LRUCache #

Sets an item in the cache.


def size : Int32 #

Returns the cache size (numbers of items in the cache).


def touch(key : K) : Bool #

Given that the LRU cache purge the items least-recently-used, this method touches an item to consider it as recent use. This makes it possible to up an old element. If the item does not exist, nothing happens.

Returns true if the existing item has been touched, false if not (because does not exist).