16#ifndef AEONGAMES_RESOURCECACHE_H
17#define AEONGAMES_RESOURCECACHE_H
21#include "aeongames/UniqueAnyPtr.hpp"
27 template<
class B,
class K,
class D = B,
typename... Args>
28 const std::shared_ptr<B> Get (
const K& key, Args... args )
31 static std::unordered_map<K, std::weak_ptr<B >> cache;
33 std::lock_guard<std::mutex> hold ( m );
34 auto iter = cache.find ( key );
35 if ( iter == cache.end() )
37 auto retval = std::shared_ptr<B> ( std::make_unique<D> ( args... ).release(), [key] ( B * t )
40 cache.erase ( cache.find ( key ) );
45 return iter->second.lock();
65 template<
class K,
class B>
69 ResourceCache() =
default;
70 ~ResourceCache() =
default;
71 ResourceCache (
const ResourceCache& ) =
delete;
72 ResourceCache ( ResourceCache&& ) =
delete;
73 ResourceCache& operator= (
const ResourceCache& ) =
delete;
74 ResourceCache& operator= ( ResourceCache&& ) =
delete;
75 template<
class D = B,
typename... Args>
76 static const std::shared_ptr<B> Get (
const K& aKey, Args... args )
79 std::lock_guard<std::mutex> hold ( mMutex );
80 auto iter = mCache.find ( aKey );
81 if ( iter == mCache.end() )
83 auto retval = std::shared_ptr<B> ( std::make_unique<D> ( args... ).release(), [aKey] ( B * t )
86 mCache.erase ( mCache.find ( aKey ) );
88 mCache[aKey] = retval;
91 return iter->second.lock();
93 static const K& GetKey (
const std::shared_ptr<B>& aValue )
95 std::lock_guard<std::mutex> hold ( mMutex );
96 auto i = std::find_if ( mCache.begin(), mCache.end(), [&aValue] (
const std::pair<
const K, std::weak_ptr<B >> & aPair )
98 return aPair.second.lock() == aValue;
100 if ( i != mCache.end() )
104 throw std::runtime_error (
"Resource not found in cache." );
108 static std::unordered_map<K, std::weak_ptr<B >> mCache;
109 static std::mutex mMutex;
111 template<
class K,
class B>
112 std::unordered_map<K, std::weak_ptr<B >> ResourceCache<K, B>::mCache;
113 template<
class K,
class B>
114 std::mutex ResourceCache<K, B>::mMutex;
Identifies a resource by its type and path CRC32 hashes.
A type-erased owning smart pointer with unique ownership semantics.
<- This is here just for the literals
DLL const UniqueAnyPtr & StoreResource(uint32_t aKey, UniqueAnyPtr &&pointer)
Store a resource in the cache.
DLL UniqueAnyPtr DisposeResource(uint32_t aKey)
Remove and return a resource from the cache.
DLL const UniqueAnyPtr & GetResource(uint32_t aKey)
Retrieve a cached resource by key.
DLL void EnumerateResources(const std::function< bool(uint32_t, const UniqueAnyPtr &) > &aEnumerator)
Enumerate all cached resources.
DLL void ClearAllResources()
Remove all resources from the cache.