add AbstractCache::forEach()

This commit is contained in:
Günter Obiltschnig
2021-04-11 15:55:47 +02:00
parent d126e51ec3
commit 8625b29f9f
3 changed files with 42 additions and 0 deletions

View File

@@ -176,6 +176,23 @@ public:
return result; return result;
} }
template <typename Fn>
void forEach(Fn&& fn) const
/// Iterates over all key-value pairs in the
/// cache, using a functor or lambda expression.
///
/// The given functor must take the key and value
/// as parameters. Note that the value is passed
/// as the actual value (or reference),
/// not a Poco::SharedPtr.
{
typename TMutex::ScopedLock lock(_mutex);
for (const auto& p: _data)
{
fn(p.first, *p.second);
}
}
protected: protected:
mutable FIFOEvent<ValidArgs<TKey>> IsValid; mutable FIFOEvent<ValidArgs<TKey>> IsValid;
mutable FIFOEvent<KeySet> Replace; mutable FIFOEvent<KeySet> Replace;

View File

@@ -221,6 +221,29 @@ void LRUCacheTest::testUpdate()
} }
void LRUCacheTest::testForEach()
{
LRUCache<int, int> aCache(3);
std::map<int, int> values;
aCache.add(1, 100);
aCache.add(2, 200);
aCache.add(3, 300);
aCache.forEach(
[&values](int key, int value)
{
values[key] = value;
}
);
assertEquals (values.size(), 3);
assertEquals (values[1], 100);
assertEquals (values[2], 200);
assertEquals (values[3], 300);
}
void LRUCacheTest::onUpdate(const void* pSender, const Poco::KeyValueArgs<int, int>& args) void LRUCacheTest::onUpdate(const void* pSender, const Poco::KeyValueArgs<int, int>& args)
{ {
++updateCnt; ++updateCnt;
@@ -260,6 +283,7 @@ CppUnit::Test* LRUCacheTest::suite()
CppUnit_addTest(pSuite, LRUCacheTest, testCacheSizeN); CppUnit_addTest(pSuite, LRUCacheTest, testCacheSizeN);
CppUnit_addTest(pSuite, LRUCacheTest, testDuplicateAdd); CppUnit_addTest(pSuite, LRUCacheTest, testDuplicateAdd);
CppUnit_addTest(pSuite, LRUCacheTest, testUpdate); CppUnit_addTest(pSuite, LRUCacheTest, testUpdate);
CppUnit_addTest(pSuite, LRUCacheTest, testForEach);
return pSuite; return pSuite;
} }

View File

@@ -31,6 +31,7 @@ public:
void testCacheSizeN(); void testCacheSizeN();
void testDuplicateAdd(); void testDuplicateAdd();
void testUpdate(); void testUpdate();
void testForEach();
void setUp(); void setUp();
void tearDown(); void tearDown();