AUI Framework  master
Cross-platform module-based framework for developing C++20 desktop applications
Cache.h
1/*
2 * AUI Framework - Declarative UI toolkit for modern C++20
3 * Copyright (C) 2020-2024 Alex2772 and Contributors
4 *
5 * SPDX-License-Identifier: MPL-2.0
6 *
7 * This Source Code Form is subject to the terms of the Mozilla Public
8 * License, v. 2.0. If a copy of the MPL was not distributed with this
9 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 */
11
12#pragma once
13
14#include "AUI/Common/AString.h"
15#include "AUI/Common/AMap.h"
16#include "AUI/Common/SharedPtr.h"
17#include "AUI/Thread/AMutex.h"
18
19template<typename T, typename Container, typename K = AString>
20class Cache {
21private:
22 AMap<K, _<T>> mContainer;
23 AMutex mSync;
24
25protected:
26 virtual _<T> load(const K& key) = 0;
27
28 virtual bool isShouldBeCached(const K& key, const _<T>& image) {
29 return true;
30 }
31
32public:
33
34 static _<T> get(const K& key) {
35 Cache& i = Container::inst();
36 {
37 std::unique_lock lock(i.mSync);
38 if (auto i = Container::inst().mContainer.contains(key)) {
39 return i->second;
40 }
41 }
42 auto value = i.load(key);
43 if (i.isShouldBeCached(key, value)) {
44 put(key, value);
45 }
46 return value;
47 }
48
49 static void put(const K& key, _<T> value) {
50 std::unique_lock lock(Container::inst().mSync);
51 Container::inst().mContainer[key] = value;
52 }
53
54 static void cleanup() {
55 std::unique_lock lock(Container::inst().mSync);
56 Container::inst().mContainer.clear();
57 }
58};
A std::map with AUI extensions.
Definition: AMap.h:218
Definition: Cache.h:20
An std::weak_ptr with AUI extensions.
Definition: SharedPtrTypes.h:177
Basic syscall-based synchronization primitive.
Definition: AMutex.h:33