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
16 changes: 16 additions & 0 deletions chia/_tests/core/util/test_lru_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import unittest

import pytest

from chia.util.lru_cache import LRUCache


Expand Down Expand Up @@ -54,3 +56,17 @@ def test_lru_cache(self):
assert len(cache.cache) == 5
assert cache.get(b"0") is None
assert cache.get(b"1") == 1


@pytest.mark.parametrize(argnames="capacity", argvalues=[-10, -1, 0])
def test_with_zero_capacity(capacity: int) -> None:
cache: LRUCache[bytes, int] = LRUCache(capacity=capacity)
cache.put(b"0", 1)
assert cache.get(b"0") is None
assert len(cache.cache) == 0


@pytest.mark.parametrize(argnames="capacity", argvalues=[-10, -1, 0, 1, 5, 10])
def test_get_capacity(capacity: int) -> None:
cache: LRUCache[object, object] = LRUCache(capacity=capacity)
assert cache.get_capacity() == capacity
12 changes: 8 additions & 4 deletions chia/util/lru_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,14 @@ def get(self, key: K) -> Optional[V]:
return self.cache[key]

def put(self, key: K, value: V) -> None:
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
if self.capacity > 0:
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)

def remove(self, key: K) -> None:
self.cache.pop(key)

def get_capacity(self) -> int:
return self.capacity
Loading