Blender V4.3
BLI_shared_cache.hh
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#pragma once
6
7#include "BLI_cache_mutex.hh"
8
9namespace blender {
10
29template<typename T> class SharedCache {
30 struct CacheData {
31 CacheMutex mutex;
32 T data;
33 CacheData() = default;
34 CacheData(const T &data) : data(data) {}
35 };
36 std::shared_ptr<CacheData> cache_;
37
38 public:
40 {
41 /* The cache should be allocated to trigger sharing of the cached data as early as possible. */
42 cache_ = std::make_shared<CacheData>();
43 }
44
46 void tag_dirty()
47 {
48 if (cache_.use_count() == 1) {
49 cache_->mutex.tag_dirty();
50 }
51 else {
52 cache_ = std::make_shared<CacheData>();
53 }
54 }
55
60 void ensure(FunctionRef<void(T &data)> compute_cache)
61 {
62 cache_->mutex.ensure([&]() { compute_cache(this->cache_->data); });
63 }
64
71 void update(FunctionRef<void(T &data)> compute_cache)
72 {
73 if (cache_.use_count() == 1) {
74 cache_->mutex.tag_dirty();
75 }
76 else {
77 cache_ = std::make_shared<CacheData>(cache_->data);
78 }
79 cache_->mutex.ensure([&]() { compute_cache(this->cache_->data); });
80 }
81
83 const T &data() const
84 {
85 BLI_assert(cache_->mutex.is_cached());
86 return cache_->data;
87 }
88
92 bool is_dirty() const
93 {
94 return cache_->mutex.is_dirty();
95 }
96
100 bool is_cached() const
101 {
102 return cache_->mutex.is_cached();
103 }
104};
105
106} // namespace blender
#define BLI_assert(a)
Definition BLI_assert.h:50
void update(FunctionRef< void(T &data)> compute_cache)
void ensure(FunctionRef< void(T &data)> compute_cache)
const T & data() const