Nix
2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Toggle main menu visibility
Loading...
Searching...
No Matches
lru-cache.hh
Go to the documentation of this file.
1
#pragma once
3
4
#include <cassert>
5
#include <map>
6
#include <list>
7
#include <optional>
8
9
namespace
nix {
10
14
template
<
typename
Key,
typename
Value,
typename
Compare = std::less<>>
15
class
LRUCache
16
{
17
private
:
18
19
size_t
capacity;
20
21
// Stupid wrapper to get around circular dependency between Data
22
// and LRU.
23
struct
LRUIterator;
24
25
using
Data = std::map<Key, std::pair<LRUIterator, Value>, Compare>;
26
using
LRU = std::list<typename Data::iterator>;
27
28
struct
LRUIterator
29
{
30
typename
LRU::iterator it;
31
};
32
33
Data data;
34
LRU lru;
35
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
48
public
:
49
50
LRUCache(
size_t
capacity)
51
: capacity(capacity)
52
{
53
}
54
58
template
<
typename
K>
59
void
upsert
(
const
K & key,
const
Value
& value)
60
{
61
if
(capacity == 0)
62
return
;
63
64
erase(key);
65
66
if
(data.size() >= capacity) {
70
auto
oldest = lru.begin();
71
data.erase(*oldest);
72
lru.erase(oldest);
73
}
74
75
auto
res = data.emplace(key, std::make_pair(LRUIterator(), value));
76
assert(res.second);
77
auto
& i(res.first);
78
79
auto
j = lru.insert(lru.end(), i);
80
81
i->second.first.it = j;
82
}
83
84
template
<
typename
K>
85
bool
erase(
const
K & key)
86
{
87
auto
i = data.find(key);
88
if
(i == data.end())
89
return
false
;
90
lru.erase(i->second.first.it);
91
data.erase(i);
92
return
true
;
93
}
94
101
template
<
typename
K>
102
std::optional<Value>
get
(
const
K & key)
103
{
104
auto
i = data.find(key);
105
if
(i == data.end())
106
return
{};
107
108
auto
& [it, value] = i->second;
109
promote(it.it);
110
return
value;
111
}
112
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
132
size_t
size() const noexcept
133
{
134
return
data.size();
135
}
136
137
void
clear() noexcept
138
{
139
data.clear();
140
lru.clear();
141
}
142
};
143
144
}
// namespace nix
nix::LRUCache::upsert
void upsert(const K &key, const Value &value)
Definition
lru-cache.hh:59
nix::LRUCache::get
std::optional< Value > get(const K &key)
Definition
lru-cache.hh:102
nix::LRUCache::getOrNullptr
Value * getOrNullptr(const K &key)
Definition
lru-cache.hh:121
nix::Value
Definition
value.hh:1166
libutil
include
nix
util
lru-cache.hh
Generated by
1.18.0