QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
GstHwImportCache.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <functional>
5#include <list>
6#include <unordered_map>
7
8namespace GstHw {
9
13template <class Key, class Resource, class KeyHash = std::hash<Key>>
15{
16public:
17 using Deleter = std::function<void(const Key&, Resource&)>;
18
19 GstHwImportCache(std::size_t capacity, Deleter deleter) : _capacity(capacity), _deleter(std::move(deleter)) {}
20
22
25
28 Resource* find(const Key& key)
29 {
30 auto it = _map.find(key);
31 if (it == _map.end()) {
32 return nullptr;
33 }
34 _order.splice(_order.begin(), _order, it->second.lru);
35 return &it->second.resource;
36 }
37
40 void insert(const Key& key, Resource resource)
41 {
42 if (auto existing = _map.find(key); existing != _map.end()) {
43 _deleter(existing->first, existing->second.resource);
44 existing->second.resource = std::move(resource);
45 _order.splice(_order.begin(), _order, existing->second.lru);
46 return;
47 }
48 if (_map.size() >= _capacity && !_order.empty()) {
49 const Key victimKey = _order.back();
50 if (auto victim = _map.find(victimKey); victim != _map.end()) {
51 _deleter(victim->first, victim->second.resource);
52 _map.erase(victim);
53 }
54 _order.pop_back();
55 }
56 _order.push_front(key);
57 _map.emplace(key, Entry{std::move(resource), _order.begin()});
58 }
59
61 template <class Pred>
62 void eraseIf(Pred pred)
63 {
64 for (auto it = _map.begin(); it != _map.end();) {
65 if (pred(it->first, it->second.resource)) {
66 _deleter(it->first, it->second.resource);
67 _order.erase(it->second.lru);
68 it = _map.erase(it);
69 } else {
70 ++it;
71 }
72 }
73 }
74
75 void clear()
76 {
77 for (auto it = _map.begin(); it != _map.end(); ++it) {
78 _deleter(it->first, it->second.resource);
79 }
80 _map.clear();
81 _order.clear();
82 }
83
84 bool empty() const noexcept { return _map.empty(); }
85
86 std::size_t size() const noexcept { return _map.size(); }
87
88private:
89 struct Entry
90 {
91 Resource resource;
92 typename std::list<Key>::iterator lru;
93 };
94
95 std::size_t _capacity;
96 Deleter _deleter;
97 std::unordered_map<Key, Entry, KeyHash> _map;
98 std::list<Key> _order;
99};
100
101} // namespace GstHw
void insert(const Key &key, Resource resource)
std::size_t size() const noexcept
std::function< void(const Key &, Resource &)> Deleter
bool empty() const noexcept
GstHwImportCache(std::size_t capacity, Deleter deleter)
GstHwImportCache(const GstHwImportCache &)=delete
GstHwImportCache & operator=(const GstHwImportCache &)=delete
void eraseIf(Pred pred)
Erase every entry whose key or resource satisfies pred, deleting each via the configured deleter.
Resource * find(const Key &key)