PcapPlusPlus  20.08
LRUList.h
Go to the documentation of this file.
1 #ifndef PCAPPP_LRU_LIST
2 #define PCAPPP_LRU_LIST
3 
4 #include <map>
5 #include <list>
6 
7 #if __cplusplus > 199711L || _MSC_VER >= 1800
8 #include <utility>
9 #endif
10 
12 
17 namespace pcpp
18 {
19 
27  template<typename T>
28  class LRUList
29  {
30  public:
31 
32  typedef typename std::list<T>::iterator ListIterator;
33  typedef typename std::map<T, ListIterator>::iterator MapIterator;
34 
39  LRUList(size_t maxSize)
40  {
41  m_MaxSize = maxSize;
42  }
43 
54  int put(const T& element, T* deletedValue = NULL)
55  {
56  m_CacheItemsList.push_front(element);
57 
58  // Inserting a new element. If an element with an equivalent key already exists the method returns an iterator to the element that prevented the insertion
59  std::pair<MapIterator, bool> pair = m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin()));
60  if (pair.second == false) // already exists
61  {
62  m_CacheItemsList.erase(pair.first->second);
63  pair.first->second = m_CacheItemsList.begin();
64  }
65 
66  if (m_CacheItemsMap.size() > m_MaxSize)
67  {
68  ListIterator lruIter = m_CacheItemsList.end();
69  lruIter--;
70 
71  if (deletedValue != NULL)
72 #if __cplusplus > 199711L || _MSC_VER >= 1800
73  *deletedValue = std::move(*lruIter);
74 #else
75  *deletedValue = *lruIter;
76 #endif
77  m_CacheItemsMap.erase(*lruIter);
78  m_CacheItemsList.erase(lruIter);
79  return 1;
80  }
81 
82  return 0;
83  }
84 
89  const T& getMRUElement() const
90  {
91  return m_CacheItemsList.front();
92  }
93 
98  const T& getLRUElement() const
99  {
100  return m_CacheItemsList.back();
101  }
102 
107  void eraseElement(const T& element)
108  {
109  MapIterator iter = m_CacheItemsMap.find(element);
110  if (iter == m_CacheItemsMap.end())
111  return;
112 
113  m_CacheItemsList.erase(iter->second);
114  m_CacheItemsMap.erase(iter);
115  }
116 
120  size_t getMaxSize() const { return m_MaxSize; }
121 
125  size_t getSize() const { return m_CacheItemsMap.size(); }
126 
127  private:
128  std::list<T> m_CacheItemsList;
129  std::map<T, ListIterator> m_CacheItemsMap;
130  size_t m_MaxSize;
131  };
132 
133 } // namespace pcpp
134 
135 #endif /* PCAPPP_LRU_LIST */
pcpp::LRUList::getMaxSize
size_t getMaxSize() const
Definition: LRUList.h:120
pcpp::LRUList::eraseElement
void eraseElement(const T &element)
Definition: LRUList.h:107
pcpp::LRUList
Definition: LRUList.h:28
pcpp::LRUList::getMRUElement
const T & getMRUElement() const
Definition: LRUList.h:89
pcpp::LRUList::put
int put(const T &element, T *deletedValue=NULL)
Definition: LRUList.h:54
pcpp
The main namespace for the PcapPlusPlus lib.
pcpp::LRUList::LRUList
LRUList(size_t maxSize)
Definition: LRUList.h:39
pcpp::LRUList::getLRUElement
const T & getLRUElement() const
Definition: LRUList.h:98
pcpp::LRUList::getSize
size_t getSize() const
Definition: LRUList.h:125