diff options
author | Ben Longbons <b.r.longbons@gmail.com> | 2013-06-11 21:55:13 -0700 |
---|---|---|
committer | Ben Longbons <b.r.longbons@gmail.com> | 2013-06-11 23:27:33 -0700 |
commit | 8b5370313dcc00a45ea5c3e8b4c497bc00fd8e13 (patch) | |
tree | 15e8a4841af992e17794f26fc7991ed40c35bd51 /src/common/db.hpp | |
parent | 8c6072df499ef9068346fbe8313b63dbba1e4e82 (diff) | |
download | tmwa-8b5370313dcc00a45ea5c3e8b4c497bc00fd8e13.tar.gz tmwa-8b5370313dcc00a45ea5c3e8b4c497bc00fd8e13.tar.bz2 tmwa-8b5370313dcc00a45ea5c3e8b4c497bc00fd8e13.tar.xz tmwa-8b5370313dcc00a45ea5c3e8b4c497bc00fd8e13.zip |
Allegedly remove all manual memory management
Diffstat (limited to 'src/common/db.hpp')
-rw-r--r-- | src/common/db.hpp | 69 |
1 files changed, 63 insertions, 6 deletions
diff --git a/src/common/db.hpp b/src/common/db.hpp index bd47928..927db22 100644 --- a/src/common/db.hpp +++ b/src/common/db.hpp @@ -22,6 +22,7 @@ # include "sanity.hpp" # include <map> +# include <memory> template<class K, class V> class Map @@ -56,7 +57,7 @@ public: return nullptr; return &it->second; } - void insert(K k, V v) + void insert(const K& k, V v) { // As far as I can tell, this is the simplest way to // implement move-only insert-with-replacement. @@ -69,7 +70,7 @@ public: return (void)&it->second; } - V *init(K k) + V *init(const K& k) { return &impl[k]; } @@ -81,10 +82,14 @@ public: { impl.clear(); } - bool empty() + bool empty() const { return impl.empty(); } + size_t size() const + { + return impl.size(); + } }; template<class K, class V> @@ -102,22 +107,74 @@ public: const_iterator begin() const { return impl.begin(); } const_iterator end() const { return impl.end(); } - V get(K k) + // const V& ? with a static default V? + V get(const K& k) { V *vp = impl.search(k); return vp ? *vp : V(); } - void put(K k, V v) + void put(const K& k, V v) { if (v == V()) impl.erase(k); else - impl.insert(k, v); + impl.insert(k, std::move(v)); } void clear() { impl.clear(); } + bool empty() const + { + return impl.empty(); + } + size_t size() const + { + return impl.size(); + } +}; + +template<class K, class V> +class UPMap +{ + typedef std::unique_ptr<V> U; + typedef Map<K, U> Impl; + + Impl impl; +public: + typedef typename Impl::iterator iterator; + typedef typename Impl::const_iterator const_iterator; + + iterator begin() { return impl.begin(); } + iterator end() { return impl.end(); } + const_iterator begin() const { return impl.begin(); } + const_iterator end() const { return impl.end(); } + + // const V& ? with a static default V? + V *get(const K& k) + { + U *up = impl.search(k); + return up ? up->get() : nullptr; + } + void put(const K& k, U v) + { + if (!v) + impl.erase(k); + else + impl.insert(k, std::move(v)); + } + void clear() + { + impl.clear(); + } + bool empty() const + { + return impl.empty(); + } + size_t size() const + { + return impl.size(); + } }; #endif // DB_HPP |