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 <
16 typename T,
17 typename Hash = std::hash<impl::StringToStringView<T>>,
18 typename Equal = std::equal_to<impl::StringToStringView<T>>>
19class LruSet final {
20public:
21 explicit LruSet(size_t max_size, const Hash& hash = Hash(), const Equal& equal = Equal())
22 : impl_(max_size, hash, equal) {}
23
24 LruSet(LruSet&& lru) noexcept = default;
25 LruSet(const LruSet& lru) = delete;
26 LruSet& operator=(LruSet&& lru) noexcept = default;
27 LruSet& operator=(const LruSet& lru) = delete;
28
29 /// Adds key to the LRU or updates its usage
30 /// @returns true if key is a new one
31 bool Put(const T& key) { return impl_.Put(key, {}); }
32
33 /// Removes key from LRU
34 void Erase(const T& key) { return impl_.Erase(key); }
35
36 /// Checks whether the key in LRU and updates its usage
37 bool Has(const T& key) { return impl_.Get(key); }
38
39 /// Sets the max size of the LRU, truncates values if new_max_size < GetSize()
40 void SetMaxSize(size_t new_max_size) { return impl_.SetMaxSize(new_max_size); }
41
42 /// Removes all the elements
43 void Invalidate() { return impl_.Invalidate(); }
44
45 /// Call Function(const T&) for all items
46 template <typename Function>
47 void VisitAll(Function&& func) const {
48 impl_.VisitAll([&func](const auto& key, const auto& /*value*/) mutable { func(key); });
49 }
50
51 size_t GetSize() const { return impl_.GetSize(); }
52
53 /// Returns pointer to the least recently used element
54 /// or nullptr if LruSet is empty.
55 /// @warning Returned pointer may be freed on the next set access!
56 const T* GetLeastUsed() { return impl_.GetLeastUsedKey(); }
57
58private:
59 impl::LruBase<T, impl::EmptyPlaceholder, Hash, Equal> impl_;
60};
61
62} // namespace cache
63
64USERVER_NAMESPACE_END