Chatterino
ConcurrentMap.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <QMap>
4 #include <QMutex>
5 #include <QMutexLocker>
6 
7 #include <functional>
8 #include <map>
9 #include <memory>
10 
11 namespace chatterino {
12 
13 template <typename TKey, typename TValue>
14 class ConcurrentMap
15 {
16 public:
17  ConcurrentMap() = default;
18 
19  bool tryGet(const TKey &name, TValue &value) const
20  {
21  QMutexLocker lock(&this->mutex_);
22 
23  auto a = this->data_.find(name);
24  if (a == this->data_.end())
25  {
26  return false;
27  }
28 
29  value = a.value();
30 
31  return true;
32  }
33 
34  TValue getOrAdd(const TKey &name, std::function<TValue()> addLambda)
35  {
36  QMutexLocker lock(&this->mutex_);
37 
38  auto a = this->data_.find(name);
39  if (a == this->data_.end())
40  {
41  TValue value = addLambda();
42  this->data_.insert(name, value);
43  return value;
44  }
45 
46  return a.value();
47  }
48 
49  TValue &operator[](const TKey &name)
50  {
51  QMutexLocker lock(&this->mutex_);
52 
53  return this->data_[name];
54  }
55 
56  void clear()
57  {
58  QMutexLocker lock(&this->mutex_);
59 
60  this->data_.clear();
61  }
62 
63  void insert(const TKey &name, const TValue &value)
64  {
65  QMutexLocker lock(&this->mutex_);
66 
67  this->data_.insert(name, value);
68  }
69 
70  void each(
71  std::function<void(const TKey &name, const TValue &value)> func) const
72  {
73  QMutexLocker lock(&this->mutex_);
74 
75  QMapIterator<TKey, TValue> it(this->data_);
76 
77  while (it.hasNext())
78  {
79  it.next();
80  func(it.key(), it.value());
81  }
82  }
83 
84  void each(std::function<void(const TKey &name, TValue &value)> func)
85  {
86  QMutexLocker lock(&this->mutex_);
87 
88  QMutableMapIterator<TKey, TValue> it(this->data_);
89 
90  while (it.hasNext())
91  {
92  it.next();
93  func(it.key(), it.value());
94  }
95  }
96 
97 private:
98  mutable QMutex mutex_;
99  QMap<TKey, TValue> data_;
100 };
101 
102 } // namespace chatterino
TValue getOrAdd(const TKey &name, std::function< TValue()> addLambda)
Definition: ConcurrentMap.hpp:34
Definition: Application.cpp:48
void insert(const TKey &name, const TValue &value)
Definition: ConcurrentMap.hpp:63
void clear()
Definition: ConcurrentMap.hpp:56
void each(std::function< void(const TKey &name, TValue &value)> func)
Definition: ConcurrentMap.hpp:84
void each(std::function< void(const TKey &name, const TValue &value)> func) const
Definition: ConcurrentMap.hpp:70
TValue & operator[](const TKey &name)
Definition: ConcurrentMap.hpp:49
QString name
Definition: Credentials.cpp:94
bool tryGet(const TKey &name, TValue &value) const
Definition: ConcurrentMap.hpp:19