PcapPlusPlus  24.09
LRUList.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <list>
4 #include <unordered_map>
5 
6 #if __cplusplus > 199711L || _MSC_VER >= 1800
7 # include <utility>
8 #endif
9 
11 
16 namespace pcpp
17 {
18 
26  template <typename T> class LRUList
27  {
28  public:
29  typedef typename std::list<T>::iterator ListIterator;
30  typedef typename std::unordered_map<T, ListIterator>::iterator MapIterator;
31 
36  explicit LRUList(size_t maxSize)
37  {
38  m_MaxSize = maxSize;
39  }
40 
53  int put(const T& element, T* deletedValue = nullptr)
54  {
55  m_CacheItemsList.push_front(element);
56 
57  // Inserting a new element. If an element with an equivalent key already exists the method returns an
58  // iterator to the element that prevented the insertion
59  std::pair<MapIterator, bool> pair =
60  m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin()));
61  if (pair.second == false) // already exists
62  {
63  m_CacheItemsList.erase(pair.first->second);
64  pair.first->second = m_CacheItemsList.begin();
65  }
66 
67  if (m_CacheItemsMap.size() > m_MaxSize)
68  {
69  ListIterator lruIter = m_CacheItemsList.end();
70  --lruIter;
71 
72  if (deletedValue != nullptr)
73 #if __cplusplus > 199711L || _MSC_VER >= 1800
74  *deletedValue = std::move(*lruIter);
75 #else
76  *deletedValue = *lruIter;
77 #endif
78  m_CacheItemsMap.erase(*lruIter);
79  m_CacheItemsList.erase(lruIter);
80  return 1;
81  }
82 
83  return 0;
84  }
85 
90  const T& getMRUElement() const
91  {
92  return m_CacheItemsList.front();
93  }
94 
99  const T& getLRUElement() const
100  {
101  return m_CacheItemsList.back();
102  }
103 
108  void eraseElement(const T& element)
109  {
110  MapIterator iter = m_CacheItemsMap.find(element);
111  if (iter == m_CacheItemsMap.end())
112  return;
113 
114  m_CacheItemsList.erase(iter->second);
115  m_CacheItemsMap.erase(iter);
116  }
117 
121  size_t getMaxSize() const
122  {
123  return m_MaxSize;
124  }
125 
129  size_t getSize() const
130  {
131  return m_CacheItemsMap.size();
132  }
133 
134  private:
135  std::list<T> m_CacheItemsList;
136  std::unordered_map<T, ListIterator> m_CacheItemsMap;
137  size_t m_MaxSize;
138  };
139 
140 } // namespace pcpp
Definition: LRUList.h:27
LRUList(size_t maxSize)
Definition: LRUList.h:36
size_t getMaxSize() const
Definition: LRUList.h:121
const T & getLRUElement() const
Definition: LRUList.h:99
int put(const T &element, T *deletedValue=nullptr)
Definition: LRUList.h:53
const T & getMRUElement() const
Definition: LRUList.h:90
void eraseElement(const T &element)
Definition: LRUList.h:108
size_t getSize() const
Definition: LRUList.h:129
The main namespace for the PcapPlusPlus lib.