Blender V5.0
BLI_memory_cache_test.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: Apache-2.0 */
4
5#include "BLI_hash.hh"
6#include "BLI_memory_cache.hh"
8
9#include "testing/testing.h"
10
11#include "BLI_strict_flags.h" /* IWYU pragma: keep. Keep last. */
12
14
15class GenericIntKey : public GenericKey {
16 private:
17 int value_;
18
19 public:
20 GenericIntKey(int value) : value_(value) {}
21
22 uint64_t hash() const override
23 {
24 return get_default_hash(value_);
25 }
26
27 bool equal_to(const GenericKey &other) const override
28 {
29 if (const auto *other_typed = dynamic_cast<const GenericIntKey *>(&other)) {
30 return other_typed->value_ == value_;
31 }
32 return false;
33 }
34
35 std::unique_ptr<GenericKey> to_storable() const override
36 {
37 return std::make_unique<GenericIntKey>(*this);
38 }
39
40 public:
41 int value() const
42 {
43 return value_;
44 }
45};
46
48 public:
49 int value;
50
51 CachedInt(int initial_value) : value(initial_value) {}
52
53 void count_memory(MemoryCounter &memory) const override
54 {
55 memory.add(sizeof(int));
56 }
57};
58
60{
62 {
63 bool newly_computed = false;
65 newly_computed = true;
66 return std::make_unique<CachedInt>(4);
67 })->value);
68 EXPECT_TRUE(newly_computed);
69 }
70 {
71 bool newly_computed = false;
73 newly_computed = true;
74 return std::make_unique<CachedInt>(4);
75 })->value);
76 EXPECT_FALSE(newly_computed);
77 }
79 {
80 bool newly_computed = false;
82 newly_computed = true;
83 return std::make_unique<CachedInt>(4);
84 })->value);
85 EXPECT_TRUE(newly_computed);
86 }
87}
88
90{
92
93 memory_cache::get<CachedInt>(GenericIntKey(1), []() { return std::make_unique<CachedInt>(1); });
94 memory_cache::get<CachedInt>(GenericIntKey(2), []() { return std::make_unique<CachedInt>(2); });
95
96 memory_cache::remove_if([](const GenericKey &key) {
97 return dynamic_cast<const GenericIntKey *>(&key)->value() == 1;
98 });
99
101 return std::make_unique<CachedInt>(10);
102 })->value);
104 return std::make_unique<CachedInt>(10);
105 })->value);
106}
107
108} // namespace blender::memory_cache::tests
EXPECT_EQ(BLI_expr_pylike_eval(expr, nullptr, 0, &result), EXPR_PYLIKE_INVALID)
unsigned long long int uint64_t
void count_memory(MemoryCounter &memory) const override
bool equal_to(const GenericKey &other) const override
std::unique_ptr< GenericKey > to_storable() const override
void remove_if(FunctionRef< bool(const GenericKey &)> predicate)
std::shared_ptr< const T > get(const GenericKey &key, FunctionRef< std::unique_ptr< T >()> compute_fn)
uint64_t get_default_hash(const T &v, const Args &...args)
Definition BLI_hash.hh:233