LRT14  1.0
 All Classes Namespaces Functions Variables Enumerations Enumerator
CachedValue.h
1 #ifndef CACHED_VALUE_H_
2 #define CACHED_VALUE_H_
3 
9 template<class T>
11 {
12 public:
18  CachedValue(T initialValue, int cacheCycles = 12);
19 
23  CachedValue();
24 
29  void setValue(T newValue);
30 
35  T getValue();
36 
41  T peek();
42 
46  void uncache();
47 
51  void incrementCounter();
52 
57  void enableCaching(int cacheCycles = -1);
58 
62  void disableCaching();
63 
68  bool hasNewValue();
69 
74  bool hasValue();
75 
80  bool isCaching();
81 
82 private:
83  volatile T m_value;
84  volatile T m_previous_value;
85  bool m_has_new_value;
86  bool m_is_caching;
87  bool m_has_been_set;
88  int m_counter;
89  int m_cache_cycles;
90 };
91 
92 template<class T>
93 CachedValue<T>::CachedValue(T initialValue, int cacheCycles)
94 {
95  m_value = initialValue;
96  m_cache_cycles = cacheCycles;
97  enableCaching(cacheCycles);
98  uncache();
99  m_has_been_set = true;
100 }
101 
102 template<class T>
104 {
105  enableCaching(12);
106  m_has_new_value = false;
107  m_has_been_set = false;
108  m_counter = 0;
109  m_previous_value = T();
110  m_value = T();
111 }
112 
113 template<class T>
114 void CachedValue<T>::setValue(T newValue)
115 {
116  m_has_been_set = true;
117  // value is already cached, ignore input
118  if (m_previous_value == newValue)
119  {
120  return;
121  }
122 
123  // set new item flag
124  m_value = newValue;
125  uncache();
126 }
127 
128 template<class T>
130 {
131  m_has_new_value = false;
132  m_previous_value = m_value;
133  return m_value;
134 }
135 
136 template<class T>
138 {
139  return m_value;
140 }
141 
142 template<class T>
144 {
145  m_has_new_value = true;
146  m_counter = 0;
147 }
148 
149 template<class T>
151 {
152  if (!m_is_caching || ++m_counter >= m_cache_cycles)
153  {
154  uncache();
155  }
156 }
157 
158 template<class T>
159 void CachedValue<T>::enableCaching(int cacheCycles)
160 {
161  m_is_caching = true;
162 
163  if (cacheCycles != -1)
164  {
165  m_cache_cycles = cacheCycles;
166  }
167 }
168 
169 template<class T>
171 {
172  m_is_caching = false;
173 }
174 
175 template<class T>
177 {
178  return m_has_been_set && (m_has_new_value || !m_is_caching);
179 }
180 
181 template<class T>
183 {
184  return m_has_been_set;
185 }
186 
187 template<class T>
189 {
190  return m_is_caching;
191 }
193 #endif