allow altering the max size of o3tl::lru_cache

Change-Id: Id119b70275e1c88a8c57f89d915241427be9dbf5
Reviewed-on: https://gerrit.libreoffice.org/c/core/+/116927
Tested-by: Jenkins
Reviewed-by: Luboš Luňák <l.lunak@collabora.com>
This commit is contained in:
Luboš Luňák 2021-06-09 17:10:42 +02:00
parent e9838a1d1d
commit 62b58e88d8
2 changed files with 22 additions and 1 deletions

View File

@ -50,7 +50,7 @@ private:
list_t mLruList; list_t mLruList;
map_t mLruMap; map_t mLruMap;
const size_t mMaxSize; size_t mMaxSize;
void checkLRU() void checkLRU()
{ {
@ -80,6 +80,13 @@ public:
list_t().swap(mLruList); list_t().swap(mLruList);
} }
void setMaxSize(size_t nMaxSize)
{
mMaxSize = nMaxSize ? nMaxSize : std::min(mLruMap.max_size(), mLruList.max_size());
while (mLruMap.size() > mMaxSize)
checkLRU();
}
void insert(key_value_pair_t& rPair) void insert(key_value_pair_t& rPair)
{ {
map_iterator_t i = mLruMap.find(rPair.first); map_iterator_t i = mLruMap.find(rPair.first);

View File

@ -29,6 +29,7 @@ public:
void testCustomHash(); void testCustomHash();
void testRemoveIf(); void testRemoveIf();
void testNoAutoCleanup(); void testNoAutoCleanup();
void testChangeMaxSize();
CPPUNIT_TEST_SUITE(lru_map_test); CPPUNIT_TEST_SUITE(lru_map_test);
CPPUNIT_TEST(testBaseUsage); CPPUNIT_TEST(testBaseUsage);
@ -38,6 +39,7 @@ public:
CPPUNIT_TEST(testCustomHash); CPPUNIT_TEST(testCustomHash);
CPPUNIT_TEST(testRemoveIf); CPPUNIT_TEST(testRemoveIf);
CPPUNIT_TEST(testNoAutoCleanup); CPPUNIT_TEST(testNoAutoCleanup);
CPPUNIT_TEST(testChangeMaxSize);
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
}; };
@ -310,6 +312,18 @@ void lru_map_test::testNoAutoCleanup()
} }
} }
void lru_map_test::testChangeMaxSize()
{
o3tl::lru_map<int, int> lru(3);
CPPUNIT_ASSERT_EQUAL(size_t(0), lru.size());
lru.insert({ 0, 0 });
lru.insert({ 1, 1 });
lru.insert({ 2, 2 });
CPPUNIT_ASSERT_EQUAL(size_t(3), lru.size());
lru.setMaxSize(1);
CPPUNIT_ASSERT_EQUAL(size_t(1), lru.size());
}
CPPUNIT_TEST_SUITE_REGISTRATION(lru_map_test); CPPUNIT_TEST_SUITE_REGISTRATION(lru_map_test);
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */