Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions src/minilru.nim
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,12 @@ func tableBucket(s: LruCache, key: auto): Opt[uint32] =
s.tableBucket(hash(key).toSubhash(), key)

func tableGet(s: LruCache, key: auto): Opt[uint32] =
let bucket = ?s.tableBucket(key)
if s.nodes.len == 0:
Opt.none(uint32)
else:
let bucket = ?s.tableBucket(key)

Opt.some(s.buckets[bucket].index)
Opt.some(s.buckets[bucket].index)

func tableDel(s: var seq[LruBucket], idx: uint32) =
let mask = s.lenu32 - 1
Expand Down Expand Up @@ -344,9 +347,6 @@ func pop*[K, V](s: var LruCache[K, V], key: auto): Opt[V] =

func get*[K, V](s: var LruCache[K, V], key: auto): Opt[V] =
## Retrieve item and move it to the front of the LRU cache
if s.buckets.len == 0:
return Opt.none(V)

let index = ?s.tableGet(key)

s.moveToFront(index)
Expand All @@ -355,19 +355,13 @@ func get*[K, V](s: var LruCache[K, V], key: auto): Opt[V] =

func peek*[K, V](s: var LruCache[K, V], key: auto): Opt[V] =
## Retrieve item without moving it to the front
if s.buckets.len == 0:
return Opt.none(V)

let index = ?s.tableGet(key)

Opt.some(s.nodes[index].value)

func update*(s: var LruCache, key: auto, value: auto): bool =
## Update and move an existing item to the front of the LRU cache - returns
## true if the item was updated, false if it was not in the cache
if s.nodes.len() == 0:
return false

let index = s.tableGet(key).valueOr:
return false

Expand All @@ -377,6 +371,16 @@ func update*(s: var LruCache, key: auto, value: auto): bool =

true

func refresh*(s: var LruCache, key: auto, value: auto): bool =
## Update existing item without moving it to the front of the LRU cache -
## returns true if the item was refreshed, false if it was not in the cache
let index = s.tableGet(key).valueOr:
return false

s.nodes[index].value = value

true

func put*(s: var LruCache, key: auto, value: auto) =
## Insert a new item in the cache, replacing the least recently used one.
##
Expand Down
3 changes: 3 additions & 0 deletions tests/test_minilru.nim
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ suite "minilru":

check:
not lru.update(100, 100)
not lru.refresh(100, 100)

lru.del(5)

Expand All @@ -92,9 +93,11 @@ suite "minilru":
11 in lru

lru.update(1, 100)
lru.refresh(0, 101)

1 in lru
lru.get(1) == Opt.some(100)
lru.peek(0) == Opt.some(101)

lru.put(12, 12)

Expand Down
Loading