PcapPlusPlus
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 
8 
13 namespace pcpp
14 {
15 
23  template<typename T>
24  class LRUList
25  {
26  public:
27 
28  typedef typename std::list<T>::iterator ListIterator;
29  typedef typename std::map<T, ListIterator>::iterator MapIterator;
30 
35  LRUList(size_t maxSize)
36  {
37  m_MaxSize = maxSize;
38  }
39 
49  T* put(const T& element)
50  {
51  m_CacheItemsList.push_front(element);
52  MapIterator iter = m_CacheItemsMap.find(element);
53  if (iter != m_CacheItemsMap.end())
54  m_CacheItemsList.erase(iter->second);
55  m_CacheItemsMap[element] = m_CacheItemsList.begin();
56 
57  if (m_CacheItemsList.size() > m_MaxSize)
58  {
59  ListIterator lruIter = m_CacheItemsList.end();
60  lruIter--;
61  T* deletedValue = new T(*lruIter);
62  m_CacheItemsMap.erase(*lruIter);
63  m_CacheItemsList.erase(lruIter);
64 
65  return deletedValue;
66  }
67 
68  return NULL;
69  }
70 
75  const T& getMRUElement()
76  {
77  return m_CacheItemsList.front();
78  }
79 
84  const T& getLRUElement()
85  {
86  return m_CacheItemsList.back();
87  }
88 
93  void eraseElement(const T& element)
94  {
95  MapIterator iter = m_CacheItemsMap.find(element);
96  if (iter == m_CacheItemsMap.end())
97  return;
98 
99  m_CacheItemsList.erase(iter->second);
100  m_CacheItemsMap.erase(element);
101  }
102 
106  inline size_t getMaxSize() { return m_MaxSize; }
107 
111  inline size_t getSize() { return m_CacheItemsMap.size(); }
112 
113  private:
114  std::list<T> m_CacheItemsList;
115  std::map<T, ListIterator> m_CacheItemsMap;
116  size_t m_MaxSize;
117  };
118 
119 } // namespace pcpp
120 
121 #endif /* PCAPPP_LRU_LIST */
Definition: LRUList.h:24
LRUList(size_t maxSize)
Definition: LRUList.h:35
const T & getLRUElement()
Definition: LRUList.h:84
The main namespace for the PcapPlusPlus lib.
void eraseElement(const T &element)
Definition: LRUList.h:93
size_t getSize()
Definition: LRUList.h:111
size_t getMaxSize()
Definition: LRUList.h:106
T * put(const T &element)
Definition: LRUList.h:49
const T & getMRUElement()
Definition: LRUList.h:75