16#ifndef AEONGAMES_FLYWEIGHT_STORE_H
17#define AEONGAMES_FLYWEIGHT_STORE_H
19#include <unordered_map>
28 template<
class Key,
class Value>
32 FlyWeight() =
default;
33 FlyWeight (
const FlyWeight& aFlyWeight ) : mKey{}
37 FlyWeight ( FlyWeight&& aFlyWeight ) : mKey ( std::move ( aFlyWeight.mKey ) )
40 std::lock_guard<std::mutex> hold ( m );
42 aFlyWeight.mKey = Key{};
45 const FlyWeight& operator= (
const FlyWeight& aFlyWeight )
48 if ( &aFlyWeight !=
this )
54 const FlyWeight& operator= ( FlyWeight&& aFlyWeight )
56 if ( &aFlyWeight !=
this )
59 std::lock_guard<std::mutex> hold ( m );
61 aFlyWeight.mKey = Key{};
62 mKey = std::move ( aFlyWeight.mKey );
67 FlyWeight (
const Key& aKey ) : mKey ( aKey )
76 static std::unordered_map<Key, FlyWeight<Key, Value>*> mStore;
87 Handle (
const Key& aKey ) : mKey{aKey}
91 throw std::runtime_error (
"The null/empty key is reserved for unpacked objects." );
97 const Value*
const Get()
const
99 auto it = FlyWeight<Key, Value>::mStore.find ( mKey );
100 if ( it != FlyWeight<Key, Value>::mStore.end() )
102 return reinterpret_cast<Value*
> ( it->second );
118 return Get() !=
nullptr;
129 throw std::runtime_error (
"Invalid FlyWeight Object." );
142 throw std::runtime_error (
"Invalid FlyWeight Object." );
155 throw std::runtime_error (
"Invalid FlyWeight Object." );
168 std::lock_guard<std::mutex> hold ( m );
171 throw std::runtime_error (
"The null/empty key is reserved for unpacked objects." );
177 throw std::runtime_error (
"An object with the same key has already been packed." );
186 std::lock_guard<std::mutex> hold ( m );
187 mStore.erase ( mKey );
198 throw std::runtime_error (
"Object is not packed." );
204 template <
class Key,
class Value>
205 std::unordered_map<Key, FlyWeight<Key, Value>*> FlyWeight<Key, Value>::mStore{};
Lightweight handle providing read-only access to a packed FlyWeight object.
const Handle GetHandle() const
Get a copy of this Handle.
const Value *const operator&() const
Address-of operator for obtaining a pointer to the stored Value.
bool IsValid() const
Check whether the referenced FlyWeight object is currently packed.
const Value *const operator->() const
Arrow operator for accessing the stored Value.
const Value & operator*() const
Dereference operator for accessing the stored Value.
const Value *const Get() const
Retrieve a pointer to the stored Value.
Handle(const Key &aKey)
Construct a Handle for the given key.
const Handle Pack(const Key &aKey)
Register this object in the store with the given key.
void Unpack()
Remove this object from the store and reset its key.
const Handle GetHandle() const
Obtain a Handle to this packed object.
<- This is here just for the literals