2018-06-26 17:47:44 +02:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <QMap>
|
|
|
|
#include <QMutex>
|
|
|
|
#include <QMutexLocker>
|
|
|
|
|
|
|
|
#include <functional>
|
|
|
|
#include <map>
|
|
|
|
#include <memory>
|
|
|
|
|
|
|
|
namespace chatterino {
|
|
|
|
|
|
|
|
template <typename TKey, typename TValue>
|
|
|
|
class ConcurrentMap
|
|
|
|
{
|
|
|
|
public:
|
|
|
|
ConcurrentMap() = default;
|
|
|
|
|
|
|
|
bool tryGet(const TKey &name, TValue &value) const
|
|
|
|
{
|
|
|
|
QMutexLocker lock(&this->mutex);
|
|
|
|
|
|
|
|
auto a = this->data.find(name);
|
2018-10-21 13:43:02 +02:00
|
|
|
if (a == this->data.end())
|
|
|
|
{
|
2018-06-26 17:47:44 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
value = a.value();
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
TValue getOrAdd(const TKey &name, std::function<TValue()> addLambda)
|
|
|
|
{
|
|
|
|
QMutexLocker lock(&this->mutex);
|
|
|
|
|
|
|
|
auto a = this->data.find(name);
|
2018-10-21 13:43:02 +02:00
|
|
|
if (a == this->data.end())
|
|
|
|
{
|
2018-06-26 17:47:44 +02:00
|
|
|
TValue value = addLambda();
|
|
|
|
this->data.insert(name, value);
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
|
|
|
|
return a.value();
|
|
|
|
}
|
|
|
|
|
|
|
|
TValue &operator[](const TKey &name)
|
|
|
|
{
|
|
|
|
QMutexLocker lock(&this->mutex);
|
|
|
|
|
|
|
|
return this->data[name];
|
|
|
|
}
|
|
|
|
|
|
|
|
void clear()
|
|
|
|
{
|
|
|
|
QMutexLocker lock(&this->mutex);
|
|
|
|
|
|
|
|
this->data.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
void insert(const TKey &name, const TValue &value)
|
|
|
|
{
|
|
|
|
QMutexLocker lock(&this->mutex);
|
|
|
|
|
|
|
|
this->data.insert(name, value);
|
|
|
|
}
|
|
|
|
|
2018-08-06 21:17:03 +02:00
|
|
|
void each(
|
|
|
|
std::function<void(const TKey &name, const TValue &value)> func) const
|
2018-06-26 17:47:44 +02:00
|
|
|
{
|
|
|
|
QMutexLocker lock(&this->mutex);
|
|
|
|
|
|
|
|
QMapIterator<TKey, TValue> it(this->data);
|
|
|
|
|
2018-10-21 13:43:02 +02:00
|
|
|
while (it.hasNext())
|
|
|
|
{
|
2018-06-26 17:47:44 +02:00
|
|
|
it.next();
|
|
|
|
func(it.key(), it.value());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void each(std::function<void(const TKey &name, TValue &value)> func)
|
|
|
|
{
|
|
|
|
QMutexLocker lock(&this->mutex);
|
|
|
|
|
|
|
|
QMutableMapIterator<TKey, TValue> it(this->data);
|
|
|
|
|
2018-10-21 13:43:02 +02:00
|
|
|
while (it.hasNext())
|
|
|
|
{
|
2018-06-26 17:47:44 +02:00
|
|
|
it.next();
|
|
|
|
func(it.key(), it.value());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
mutable QMutex mutex;
|
|
|
|
QMap<TKey, TValue> data;
|
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace chatterino
|