VWeb/Includes/Map.h

59 lines
1.4 KiB
C
Raw Normal View History

#pragma once
#include <cassert>
#include <mutex>
#include <unordered_map>
#include <condition_variable>
#include <atomic>
namespace VWeb {
template <typename T, typename S> struct SafeMap {
explicit SafeMap(size_t maxSize = -1UL) : m_MaxSize(maxSize), m_End(false){};
bool Add(const T &t, S &x) {
std::unique_lock<std::mutex> lck(m_Mutex);
while (m_Data.size() == m_MaxSize && !m_End)
return false;
assert(!m_End);
m_Data.emplace(t, std::move(x));
return true;
};
bool Add(T &&t, S &&x) {
std::unique_lock<std::mutex> lck(m_Mutex);
while (m_Data.size() == m_MaxSize && !m_End)
return false;
assert(!m_End);
m_Data.push(std::move(t));
return true;
};
void Remove(T t) {
std::unique_lock<std::mutex> lck(m_Mutex);
if (m_Data.empty() || m_End)
return;
if (m_Data.contains(t))
m_Data.erase(t);
m_CVFull.notify_one();
};
void Clear() {
std::unique_lock<std::mutex> lck(m_Mutex);
std::unordered_map<T, S> empty;
std::swap(m_Data, empty);
m_CVFull.notify_all();
};
bool Has(T t) {
std::unique_lock<std::mutex> lck(m_Mutex);
return m_Data.contains(t);
};
S &Get(T t) {
std::unique_lock<std::mutex> lck(m_Mutex);
return m_Data[t];
};
int Size() { return m_Data.size(); };
private:
std::unordered_map<T, S> m_Data{};
std::mutex m_Mutex{};
std::condition_variable m_CVFull{};
const size_t m_MaxSize{};
std::atomic<bool> m_End{};
};
}