Woman, Life, Freedom


Adaptive AUTOSAR
ARA public interface header documentation
memory_cache.h
1#ifndef MEMORY_CACHE_H
2#define MEMORY_CACHE_H
3
4#include <chrono>
5#include <map>
6
7namespace application
8{
9 namespace helper
10 {
15 template <typename K, typename T>
17 {
18 private:
19 const std::chrono::seconds cLifetime;
20 std::map<K, std::pair<const std::chrono::system_clock::time_point, const T>> mCachedItems;
21
22 public:
25 explicit MemoryCache(std::chrono::seconds lifetime) : cLifetime{lifetime}
26 {
27 }
28
32 void Add(K key, const T &item)
33 {
34 mCachedItems.emplace(
35 key, std::make_pair(std::chrono::system_clock::now(), item));
36 }
37
43 bool TryGet(K key, T &item)
44 {
45 auto _cachedItemItr{mCachedItems.find(key)};
46
47 if (_cachedItemItr != mCachedItems.end())
48 {
49 const auto cNow{std::chrono::system_clock::now()};
50 if (cNow - _cachedItemItr->second.first < cLifetime)
51 {
52 item = _cachedItemItr->second.second;
53 return true;
54 }
55 else
56 {
57 // Remove the item if it is already expired
58 mCachedItems.erase(_cachedItemItr);
59 return false;
60 }
61 }
62 else
63 {
64 return false;
65 }
66 }
67 };
68 }
69}
70
71#endif
Memory cache helper class with expiration time.
Definition: memory_cache.h:17
bool TryGet(K key, T &item)
Try to get an item from the cache.
Definition: memory_cache.h:43
MemoryCache(std::chrono::seconds lifetime)
Constructor.
Definition: memory_cache.h:25
void Add(K key, const T &item)
Add an item to the cache.
Definition: memory_cache.h:32
AUTOSAR application namespace.
Definition: diag_message_handler.cpp:5