PcapPlusPlus  Next
LRUList.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <list>
4 #include <cstddef>
5 #include <unordered_map>
6 
7 #if __cplusplus > 199711L || _MSC_VER >= 1800
8 # include <utility>
9 #endif
10 
12 
15 namespace pcpp
16 {
17 
23  template <typename T> class LRUList
24  {
25  public:
26  typedef typename std::list<T>::iterator ListIterator;
27  typedef typename std::unordered_map<T, ListIterator>::iterator MapIterator;
28 
31  explicit LRUList(std::size_t maxSize)
32  {
33  m_MaxSize = maxSize;
34  }
35 
46  int put(const T& element, T* deletedValue = nullptr)
47  {
48  m_CacheItemsList.push_front(element);
49 
50  // Inserting a new element. If an element with an equivalent key already exists the method returns an
51  // iterator to the element that prevented the insertion
52  std::pair<MapIterator, bool> pair =
53  m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin()));
54  if (pair.second == false) // already exists
55  {
56  m_CacheItemsList.erase(pair.first->second);
57  pair.first->second = m_CacheItemsList.begin();
58  }
59 
60  if (m_CacheItemsMap.size() > m_MaxSize)
61  {
62  ListIterator lruIter = m_CacheItemsList.end();
63  --lruIter;
64 
65  if (deletedValue != nullptr)
66 #if __cplusplus > 199711L || _MSC_VER >= 1800
67  *deletedValue = std::move(*lruIter);
68 #else
69  *deletedValue = *lruIter;
70 #endif
71  m_CacheItemsMap.erase(*lruIter);
72  m_CacheItemsList.erase(lruIter);
73  return 1;
74  }
75 
76  return 0;
77  }
78 
81  const T& getMRUElement() const
82  {
83  return m_CacheItemsList.front();
84  }
85 
88  const T& getLRUElement() const
89  {
90  return m_CacheItemsList.back();
91  }
92 
95  void eraseElement(const T& element)
96  {
97  MapIterator iter = m_CacheItemsMap.find(element);
98  if (iter == m_CacheItemsMap.end())
99  return;
100 
101  m_CacheItemsList.erase(iter->second);
102  m_CacheItemsMap.erase(iter);
103  }
104 
106  size_t getMaxSize() const
107  {
108  return m_MaxSize;
109  }
110 
112  size_t getSize() const
113  {
114  return m_CacheItemsMap.size();
115  }
116 
117  private:
118  std::list<T> m_CacheItemsList;
119  std::unordered_map<T, ListIterator> m_CacheItemsMap;
120  size_t m_MaxSize;
121  };
122 
123 } // namespace pcpp
Definition: LRUList.h:24
size_t getMaxSize() const
Definition: LRUList.h:106
const T & getLRUElement() const
Definition: LRUList.h:88
int put(const T &element, T *deletedValue=nullptr)
Definition: LRUList.h:46
const T & getMRUElement() const
Definition: LRUList.h:81
void eraseElement(const T &element)
Definition: LRUList.h:95
LRUList(std::size_t maxSize)
Definition: LRUList.h:31
size_t getSize() const
Definition: LRUList.h:112
The main namespace for the PcapPlusPlus lib.