ledger-core
TTLCache.h
1 /*
2  *
3  * TTLCache
4  *
5  * Created by El Khalil Bellakrid on 22/11/2019.
6  *
7  * The MIT License (MIT)
8  *
9  * Copyright (c) 2019 Ledger
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a copy
12  * of this software and associated documentation files (the "Software"), to deal
13  * in the Software without restriction, including without limitation the rights
14  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15  * copies of the Software, and to permit persons to whom the Software is
16  * furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included in all
19  * copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  *
29  */
30 
31 
32 #pragma once
33 
34 #include <chrono>
35 #include <unordered_map>
36 #include <mutex>
37 #include <iostream>
38 #include "Option.hpp"
39 /*
40  * A really simple implementation of TTL cache
41  */
42 namespace ledger {
43  namespace core {
44  template <typename K, typename V, typename Duration = std::chrono::seconds>
45  class TTLCache {
46  public:
47  TTLCache(const Duration &ttl) : _ttl(ttl) {};
48 
49  Option<V> get(const K &key) {
50  std::lock_guard<std::mutex> lock(_lock);
51  auto it = _cache.find(key);
52  if (it == _cache.end()) {
53  return Option<V>();
54  } else if (getNowDurationSinceEpoch() - (*it).second.second > _ttl) {
55  // Clean the cache
56  _cache.erase(key);
57  return Option<V>();
58  }
59  return Option<V>((*it).second.first);
60  }
61 
62  void put(const K &key, const V &value) {
63  std::lock_guard<std::mutex> lock(_lock);
64  _cache.insert(
65  { key,
66  { value,
67  getNowDurationSinceEpoch()
68  }
69  });
70  }
71 
72  void erase(const K &key) {
73  std::lock_guard<std::mutex> lock(_lock);
74  _cache.erase(key);
75  }
76 
77  private:
78  Duration getNowDurationSinceEpoch() {
79  return std::chrono::duration_cast<Duration>(std::chrono::steady_clock::now().time_since_epoch());
80  }
81  Duration _ttl;
82  std::unordered_map<K, std::pair<V, Duration>> _cache;
83  std::mutex _lock;
84  };
85  }
86 }
Definition: Option.hpp:49
Definition: Account.cpp:8
Definition: TTLCache.h:45