Cache.h
Go to the documentation of this file.
1 #ifndef _utl_Cache_h_
2 #define _utl_Cache_h_
3 
4 #include <boost/smart_ptr.hpp>
5 
6 
7 namespace utl {
8 
9  template<typename AResult, class Functor, typename AArgument>
10  class Cache {
11  public:
12  Cache() { }
13 
14  Cache(const Functor* const functorPtr, const unsigned int maxSize)
15  : fFunctorPtr(functorPtr), fMaxSize(maxSize) { }
16 
17  Cache(const Cache& other)
18  : fFunctorPtr(other.fFunctorPtr), fMaxSize(other.fMaxSize) { }
19 
20  Cache&
21  operator=(const Cache& other)
22  {
23  if (this != &other) {
24  Reset();
25  fFunctorPtr = other.fFunctorPtr;
26  fMaxSize = other.fMaxSize;
27  }
28  return *this;
29  }
30 
31  ~Cache() { Reset(); }
32 
33  void
35  {
36  fSize = 0;
37  Node* curr = fRoot;
38  while (curr != nullptr) {
39  Node* const node = curr;
40  curr = curr->next;
41  delete node;
42  }
43  fRoot = nullptr;
44  }
45 
46  AResult
47  operator()(const AArgument& arg)
48  {
49  if (!fRoot) {
50  fRoot = new Node;
51  fRoot->arg = arg;
52  fRoot->res = (*fFunctorPtr.get())(arg);
53  ++fSize;
54  return fRoot->res;
55  }
56 
57  if (fRoot->arg == arg)
58  return fRoot->res;
59 
60  Node* prev = nullptr;
61  Node* curr = fRoot;
62  while (curr->next) {
63  prev = curr;
64  curr = curr->next;
65  if (curr->arg == arg) {
66  // move curr to front
67  prev->next = curr->next;
68  curr->next = fRoot;
69  fRoot = curr;
70  return curr->res;
71  }
72  }
73 
74  // cache miss, curr is last valid element
75  if (fSize < fMaxSize) {
76  // cache is not full: push to front
77  Node* const node = new Node;
78  node->next = fRoot;
79  node->arg = arg;
80  node->res = (*fFunctorPtr.get())(arg);
81  fRoot = node;
82  ++fSize;
83  } else {
84  // cache is full: recycle last element
85  prev->next = nullptr;
86  curr->next = fRoot;
87  curr->arg = arg;
88  curr->res = (*fFunctorPtr.get())(arg);
89  fRoot = curr;
90  }
91 
92  return fRoot->res;
93  }
94 
95  protected:
96  struct Node {
97  AArgument arg;
98  AResult res;
99  Node* next = nullptr;
100  };
101 
102  boost::shared_ptr<const Functor> fFunctorPtr;
103  unsigned int fMaxSize = 0;
104  unsigned int fSize = 0;
105  Node* fRoot = nullptr;
106  };
107 
108 }
109 
110 
111 #endif
unsigned int fSize
Definition: Cache.h:104
AResult operator()(const AArgument &arg)
Definition: Cache.h:47
Node * next
Definition: Cache.h:99
AResult res
Definition: Cache.h:98
~Cache()
Definition: Cache.h:31
boost::shared_ptr< const Functor > fFunctorPtr
Definition: Cache.h:102
Cache & operator=(const Cache &other)
Definition: Cache.h:21
void Reset()
Definition: Cache.h:34
unsigned int fMaxSize
Definition: Cache.h:103
Cache()
Definition: Cache.h:12
Node * fRoot
Definition: Cache.h:105
Cache(const Cache &other)
Definition: Cache.h:17
AArgument arg
Definition: Cache.h:97
Cache(const Functor *const functorPtr, const unsigned int maxSize)
Definition: Cache.h:14

, generated on Tue Sep 26 2023.