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