@@ -33,6 +33,18 @@ private:
33
33
Data data;
34
34
LRU lru;
35
35
36
+ /* *
37
+ * Move this item to the back of the LRU list.
38
+ */
39
+ void promote (LRU::iterator it)
40
+ {
41
+ /* Think of std::list iterators as stable pointers to the list node,
42
+ * which never get invalidated. Thus, we can reuse the same lru list
43
+ * element and just splice it to the back of the list without the need
44
+ * to update its value in the key -> list iterator map. */
45
+ lru.splice (/* pos=*/ lru.end (), /* other=*/ lru, it);
46
+ }
47
+
36
48
public:
37
49
38
50
LRUCache (size_t capacity)
@@ -83,28 +95,40 @@ public:
83
95
/* *
84
96
* Look up an item in the cache. If it exists, it becomes the most
85
97
* recently used item.
86
- * */
98
+ *
99
+ * @returns corresponding cache entry, std::nullopt if it's not in the cache
100
+ */
87
101
template <typename K>
88
102
std::optional<Value> get (const K & key)
89
103
{
90
104
auto i = data.find (key);
91
105
if (i == data.end ())
92
106
return {};
93
107
94
- /* *
95
- * Move this item to the back of the LRU list.
96
- *
97
- * Think of std::list iterators as stable pointers to the list node,
98
- * which never get invalidated. Thus, we can reuse the same lru list
99
- * element and just splice it to the back of the list without the need
100
- * to update its value in the key -> list iterator map.
101
- */
102
108
auto & [it, value] = i->second ;
103
- lru.splice (/* pos=*/ lru.end (), /* other=*/ lru, it.it );
104
-
109
+ promote (it.it );
105
110
return value;
106
111
}
107
112
113
+ /* *
114
+ * Look up an item in the cache. If it exists, it becomes the most
115
+ * recently used item.
116
+ *
117
+ * @returns mutable pointer to the corresponding cache entry, nullptr if
118
+ * it's not in the cache
119
+ */
120
+ template <typename K>
121
+ Value * getOrNullptr (const K & key)
122
+ {
123
+ auto i = data.find (key);
124
+ if (i == data.end ())
125
+ return nullptr ;
126
+
127
+ auto & [it, value] = i->second ;
128
+ promote (it.it );
129
+ return &value;
130
+ }
131
+
108
132
size_t size () const noexcept
109
133
{
110
134
return data.size ();
0 commit comments