53 lines
1.1 KiB
C
53 lines
1.1 KiB
C
|
|
#pragma once
|
||
|
|
|
||
|
|
#include <assets/handle.h>
|
||
|
|
#include <mutex>
|
||
|
|
#include <shared_mutex>
|
||
|
|
#include <string>
|
||
|
|
#include <unordered_map>
|
||
|
|
|
||
|
|
namespace extra2d {
|
||
|
|
|
||
|
|
template <typename T> class AssetCache {
|
||
|
|
public:
|
||
|
|
Handle<T> find(const std::string &key) const {
|
||
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||
|
|
auto it = map_.find(key);
|
||
|
|
if (it == map_.end()) {
|
||
|
|
return Handle<T>::invalid();
|
||
|
|
}
|
||
|
|
return it->second;
|
||
|
|
}
|
||
|
|
|
||
|
|
void set(const std::string &key, Handle<T> handle) {
|
||
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||
|
|
map_[key] = handle;
|
||
|
|
}
|
||
|
|
|
||
|
|
void erase(const std::string &key) {
|
||
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||
|
|
map_.erase(key);
|
||
|
|
}
|
||
|
|
|
||
|
|
void clear() {
|
||
|
|
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||
|
|
map_.clear();
|
||
|
|
}
|
||
|
|
|
||
|
|
std::string findKeyByHandle(Handle<T> handle) const {
|
||
|
|
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||
|
|
for (const auto &pair : map_) {
|
||
|
|
if (pair.second == handle) {
|
||
|
|
return pair.first;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return "";
|
||
|
|
}
|
||
|
|
|
||
|
|
private:
|
||
|
|
std::unordered_map<std::string, Handle<T>> map_;
|
||
|
|
mutable std::shared_mutex mutex_;
|
||
|
|
};
|
||
|
|
|
||
|
|
} // namespace extra2d
|