#pragma once #include #include #include namespace ylib { template class map:private std::map { public: map() {} ~map() {} const std::map to_stl() { std::unique_lock __guard_lock__(m_mutex); return *this; } bool add(const KEY& key_, const VAL val, bool lock = true) { if (lock) this->m_mutex.lock(); typename std::map::iterator iter = ::std::map::find(key_); if (iter != ::std::map::end()) { if (lock) this->m_mutex.unlock(); return false; } ::std::map::insert(std::pair(key_, val)); if (lock) this->m_mutex.unlock(); return true; } bool exist(const KEY& key_, bool lock = true) { if (lock) this->m_mutex.lock(); auto iter = ::std::map::find(key_); bool ret = iter != ::std::map::end(); if (lock) this->m_mutex.unlock(); return ret; } bool set(const KEY& key_, VAL val, bool insert = false) { std::unique_lock __guard_lock__(m_mutex); typename std::map::iterator iter = ::std::map::find(key_); if (iter == ::std::map::end()) { if (insert == true) { ::std::map::insert(std::pair(key_, val)); return true; } else { return false; } } else { iter->second = val; return true; } } bool get(const KEY& key_, VAL& val, bool lock = true) { if (lock) this->m_mutex.lock(); typename std::map::iterator iter = ::std::map::find(key_); if (iter == ::std::map::end()) { if (lock) this->m_mutex.unlock(); return false; } val = iter->second; if (lock) this->m_mutex.unlock(); return true; } bool del(const KEY& key_,bool locked = true) { if(locked) m_mutex.lock(); typename std::map::iterator iter = ::std::map::find(key_); if (iter == ::std::map::end()){ if(locked) m_mutex.unlock(); return false; } ::std::map::erase(iter); if(locked) m_mutex.unlock(); return true; } void clear() { std::unique_lock __guard_lock__(m_mutex); //::std::map::swap(); ::std::map::clear(); } size_t size() { std::unique_lock __guard_lock__(m_mutex); return ::std::map::size(); } void lock() { this->m_mutex.lock(); } void unlock() { this->m_mutex.unlock(); } VAL operator[](const KEY& key) { std::unique_lock __guard_lock__(m_mutex); VAL val; get(key, val,false); return val; } bool find(std::function delegate) { std::unique_lock __guard_lock__(m_mutex); for_iter(iter, (*this)) { if (delegate(iter->first, iter->second)) return true; } return false; } void loop(std::function callback) { std::unique_lock __guard_lock__(m_mutex); for_iter(iter, (*this)) { callback(iter->first,iter->second); } } std::map* parent() { return this; } public: std::mutex m_mutex; }; }