mirror of
https://github.com/zoriya/Bomberman.git
synced 2026-06-09 20:25:31 +00:00
cache system add lonely functionnality
This commit is contained in:
@@ -10,6 +10,9 @@
|
||||
#include <unordered_map>
|
||||
#include <functional>
|
||||
#include <raylib.h>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
namespace RAY {
|
||||
//! @brief A templated class used to cache ressources, indexed with a string
|
||||
@@ -31,16 +34,26 @@ namespace RAY {
|
||||
Cache &operator=(const Cache &) = default;
|
||||
|
||||
//! @param path path of the file
|
||||
//! @param lonely: should be set to true if the loaded data must be held by no other active entites
|
||||
//! @return a newly loaded ressource if it hasn't be previously loaded, or one from cache
|
||||
std::shared_ptr<T>fetch(const std::string &path)
|
||||
std::shared_ptr<T>fetch(const std::string &path, bool lonely = false)
|
||||
{
|
||||
if (this->_cache.find(path) == this->_cache.end())
|
||||
this->_cache.emplace(path, std::shared_ptr<T>(
|
||||
new T(this->_dataLoader(path.c_str())), [this](T *p) {
|
||||
this->_dataUnloader(*p);
|
||||
delete p;
|
||||
}));
|
||||
return _cache[path];
|
||||
if (!this->_cache.contains(path))
|
||||
this->_cache.emplace(path, std::vector<std::shared_ptr<T>>());
|
||||
std::vector<std::shared_ptr<T>> &matchingDataVector = this->_cache.at(path);
|
||||
|
||||
for (std::shared_ptr<T> &i: matchingDataVector) {
|
||||
if (!lonely)
|
||||
return i;
|
||||
if (lonely && i.use_count() == 1)
|
||||
return i;
|
||||
}
|
||||
matchingDataVector.emplace_back(std::shared_ptr<T>(
|
||||
new T(this->_dataLoader(path.c_str())), [this](T *p) {
|
||||
this->_dataUnloader(*p);
|
||||
delete p;
|
||||
}));
|
||||
return matchingDataVector.back();
|
||||
};
|
||||
private:
|
||||
//! @brief function to call to load data
|
||||
@@ -50,7 +63,7 @@ namespace RAY {
|
||||
std::function<void(T)> _dataUnloader;
|
||||
|
||||
//! @brief map storing shared ptr of caches
|
||||
std::unordered_map<std::string, std::shared_ptr<T>> _cache;
|
||||
std::unordered_map<std::string, std::vector<std::shared_ptr<T>>> _cache;
|
||||
};
|
||||
|
||||
template<>
|
||||
|
||||
Reference in New Issue
Block a user