]> git.ipfire.org Git - thirdparty/snort3.git/commitdiff
Merge pull request #1887 in SNORT/snort3 from ~ANTOROZC/snort3:duapalme_lru_cache...
authorSteve Chew (stechew) <stechew@cisco.com>
Tue, 10 Dec 2019 22:11:14 +0000 (22:11 +0000)
committerSteve Chew (stechew) <stechew@cisco.com>
Tue, 10 Dec 2019 22:11:14 +0000 (22:11 +0000)
Squashed commit of the following:

commit 34fe7d4675a47b58c4fc6f9c5d3305f59d7ef999
Author: Duane Palmer <duapalme@cisco.com>
Date:   Thu Nov 14 15:04:28 2019 -0600

    lru_cache_shared: added find_else_insert to add user managed objects to the cache

src/hash/lru_cache_shared.h
src/hash/test/lru_cache_shared_test.cc

index 16bc26cfba5a499860cd48eb75acd48b54e3fcf2..155bee1abe247dc8cf501e9ece8df943c2060dc4 100644 (file)
@@ -73,6 +73,9 @@ public:
     // Same as operator[]; additionally, sets the boolean if a new entry is created.
     Data find_else_create(const Key& key, bool* new_data);
 
+    // Returns true if found, takes a ref to a user managed entry
+    bool find_else_insert(const Key& key, std::shared_ptr<Value>& data);
+
     // Return all data from the LruCache in order (most recently used to least)
     std::vector<std::pair<Key, Data> > get_all_data();
 
@@ -264,6 +267,38 @@ find_else_create(const Key& key, bool* new_data)
     return data;
 }
 
+template<typename Key, typename Value, typename Hash>
+bool LruCacheShared<Key, Value, Hash>::
+find_else_insert(const Key& key, std::shared_ptr<Value>& data)
+{
+    LruMapIter map_iter;
+
+    std::list<Data> tmp_data;
+    std::lock_guard<std::mutex> cache_lock(cache_mutex);
+
+    map_iter = map.find(key);
+    if (map_iter != map.end())
+    {
+        stats.find_hits++;
+        list.splice(list.begin(), list, map_iter->second); // update LRU
+        return true;
+    }
+
+    stats.find_misses++;
+    stats.adds++;
+
+    //  Add key/data pair to front of list.
+    list.emplace_front(std::make_pair(key, data));
+    increase_size();
+
+    //  Add list iterator for the new entry to map.
+    map[key] = list.begin();
+
+    prune(tmp_data);
+
+    return false;
+}
+
 template<typename Key, typename Value, typename Hash>
 std::vector< std::pair<Key, std::shared_ptr<Value>> >
 LruCacheShared<Key, Value, Hash>::get_all_data()
index 3df194b0b932f3e4b1d679af716b77d393c3c736..3993a6cd49d8aa77545d10f328f6a9cccd6f72ec 100644 (file)
@@ -144,6 +144,18 @@ TEST(lru_cache_shared, remove_test)
     CHECK(vec[1].first == 1 and *vec[1].second == "one");
 }
 
+TEST(lru_cache_shared, find_else_insert)
+{
+    std::shared_ptr<std::string> data(new std::string("12345"));
+    LruCacheShared<int, std::string, std::hash<int> > lru_cache(1);
+
+    CHECK(false == lru_cache.find_else_insert(1,data)); 
+    CHECK(1 == lru_cache.size());
+
+    CHECK(true == lru_cache.find_else_insert(1,data)); 
+    CHECK(1 == lru_cache.size());
+}
+
 //  Test statistics counters.
 TEST(lru_cache_shared, stats_test)
 {