21 std::atomic<uint32_t> refs{0};
22 std::once_flag created;
27 friend class ResourceCache;
29 Entry* entry =
nullptr;
33 explicit Ref(Entry* entry) : entry(entry) {
35 entry->refs.fetch_add(1, std::memory_order_relaxed);
38 explicit Ref(std::nullptr_t) : entry(
nullptr) {}
39 Ref(
const Ref& other) : Ref(other.entry) {}
40 Ref(Ref&& other) noexcept : entry(std::exchange(other.entry,
nullptr)) {}
42 Ref& operator=(std::nullptr_t other) {
43 if (entry !=
nullptr) {
44 entry->refs.fetch_sub(1, std::memory_order_acq_rel);
51 Ref& operator=(
const Ref& other) {
52 if (other.entry != entry) {
53 if (other.entry !=
nullptr) {
54 other.entry->refs.fetch_add(1, std::memory_order_relaxed);
57 if (entry !=
nullptr) {
58 entry->refs.fetch_sub(1, std::memory_order_acq_rel);
67 Ref& operator=(Ref&& other)
noexcept {
68 if (other.entry != entry) {
69 if (entry !=
nullptr) {
70 entry->refs.fetch_sub(1, std::memory_order_acq_rel);
73 entry = std::exchange(other.entry,
nullptr);
79 bool operator==(
const Ref& other)
const {
80 return entry == other.entry;
83 bool operator!=(
const Ref& other)
const {
84 return entry != other.entry;
87 bool IsValid()
const {
88 return entry !=
nullptr;
93 entry->refs.fetch_sub(1, std::memory_order_acq_rel);
96 Value operator->()
const {
113 using Factory = std::function<Value(
const Key&)>;
114 using Deleter = std::function<void(Value)>;
118 GS_ASSERT_WITH_MESSAGE(cache.empty(),
"ResourceCache handles outlive cache.");
122 Ref GetOrCreate(
const Key& key) {
125 std::unique_lock lock(mutex);
126 auto [it, inserted] = cache.try_emplace(key);
127 Entry* entry = &it->second;
134 std::call_once(ref.entry->created, [&]{ ref.entry->value = constructCallback(key); });
140 void Trim(Grindstone::DeferredDeletionQueue* deferredDeletionQueue) {
141 std::unique_lock lock(mutex);
142 for (
auto it = cache.begin(); it != cache.end();) {
143 if (it->second.refs.load() == 0) {
144 deferredDeletionQueue->PushDeletion(
145 [resource=it->second.value, destroyCallback=this->destroyCallback]() {
146 destroyCallback(resource);
149 it = cache.erase(it);
157 void TrimImmediately() {
158 std::unique_lock lock(mutex);
159 for (
auto it = cache.begin(); it != cache.end();) {
160 if (it->second.refs.load() == 0) {
161 destroyCallback(it->second.value);
162 it = cache.erase(it);
169 void SetFactory(Factory factory) { constructCallback = factory; }
170 void SetDeleter(Deleter deleter) { destroyCallback = deleter; }
174 Factory constructCallback;
175 Deleter destroyCallback;
178 std::unordered_map<Key, Entry, Hash> cache;