userver: userver/cache/lru_set.hpp Source File
Loading...
Searching...
No Matches
lru_set.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/cache/lru_set.hpp
4/// @brief @copybrief cache::LruSet
5
6#include <userver/cache/impl/lru.hpp>
7
8USERVER_NAMESPACE_BEGIN
9
10namespace cache {
11
12/// @ingroup userver_universal userver_containers
13///
14/// LRU set, thread safety matches Standard Library thread safety
15template <typename T, typename Hash = std::hash<T>, typename Equal = std::equal_to<T>>
16class LruSet final {
17public:
18 explicit LruSet(size_t max_size, const Hash& hash = Hash(), const Equal& equal = Equal())
19 : impl_(max_size, hash, equal) {}
20
21 LruSet(LruSet&& lru) noexcept = default;
22 LruSet(const LruSet& lru) = delete;
23 LruSet& operator=(LruSet&& lru) noexcept = default;
24 LruSet& operator=(const LruSet& lru) = delete;
25
26 /// Adds key to the LRU or updates its usage
27 /// @returns true if key is a new one
28 bool Put(const T& key) { return impl_.Put(key, {}); }
29
30 /// Removes key from LRU
31 void Erase(const T& key) { return impl_.Erase(key); }
32
33 /// Checks whether the key in LRU and updates its usage
34 bool Has(const T& key) { return impl_.Get(key); }
35
36 /// Sets the max size of the LRU, truncates values if new_max_size < GetSize()
37 void SetMaxSize(size_t new_max_size) { return impl_.SetMaxSize(new_max_size); }
38
39 /// Removes all the elements
40 void Invalidate() { return impl_.Invalidate(); }
41
42 /// Call Function(const T&) for all items
43 template <typename Function>
44 void VisitAll(Function&& func) const {
45 impl_.VisitAll([&func](const auto& key, const auto& /*value*/) mutable { func(key); });
46 }
47
48 size_t GetSize() const { return impl_.GetSize(); }
49
50 /// Returns pointer to the least recently used element
51 /// or nullptr if LruSet is empty.
52 /// @warning Returned pointer may be freed on the next set access!
53 const T* GetLeastUsed() { return impl_.GetLeastUsedKey(); }
54
55private:
56 impl::LruBase<T, impl::EmptyPlaceholder, Hash, Equal> impl_;
57};
58
59} // namespace cache
60
61USERVER_NAMESPACE_END