#pragma once #include #include #include #include #include namespace VWeb { template struct SafeMap { explicit SafeMap(size_t maxSize = -1UL) : m_MaxSize(maxSize), m_End(false){}; bool Add(const T &t, S &x) { std::unique_lock 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 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 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 lck(m_Mutex); std::unordered_map empty; std::swap(m_Data, empty); m_CVFull.notify_all(); }; bool Has(T t) { std::unique_lock lck(m_Mutex); return m_Data.contains(t); }; S &Get(T t) { std::unique_lock lck(m_Mutex); return m_Data[t]; }; int Size() { return m_Data.size(); }; private: std::unordered_map m_Data{}; std::mutex m_Mutex{}; std::condition_variable m_CVFull{}; const size_t m_MaxSize{}; std::atomic m_End{}; }; }