lmms
Cross-platform music production software
Loading...
Searching...
No Matches
FileResourceCache.h
Go to the documentation of this file.
1/*
2 * FileResourceCache.h
3 *
4 * Copyright (c) 2026 saker <sakertooth@gmail.com>
5 *
6 * This file is part of LMMS - https://lmms.io
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public
19 * License along with this program (see COPYING); if not, write to the
20 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301 USA.
22 *
23 */
24
25#ifndef LMMS_FILE_RESOURCE_CACHE_H
26#define LMMS_FILE_RESOURCE_CACHE_H
27
28#include <filesystem>
29#include <memory>
30#include <type_traits>
31#include <unordered_map>
32
33namespace lmms {
34
43template <typename T> class FileResourceCache
44{
45public:
58 template <typename Factory>
59 requires(std::is_invocable_r_v<std::shared_ptr<const T>, Factory>)
60 auto fetch(const std::filesystem::path& path, Factory&& factory) -> std::shared_ptr<const T>
61 {
62 auto [it, inserted] = m_entries.try_emplace(path, Entry{});
63 auto& entry = it->second;
64 const auto lastWriteTime = std::filesystem::last_write_time(path);
65
66 if (!inserted && entry.lastWriteTime == lastWriteTime)
67 {
68 const auto resource = entry.resource.lock();
69 if (resource) { return resource; }
70 }
71
72 const auto resource = factory();
73 if (!resource) { return nullptr; }
74
75 entry.resource = resource;
76 entry.lastWriteTime = lastWriteTime;
77 return resource;
78 }
79
80private:
81 struct Entry
82 {
83 std::weak_ptr<const T> resource;
84 std::filesystem::file_time_type lastWriteTime;
85 };
86
87 std::unordered_map<std::filesystem::path, Entry> m_entries;
88};
89} // namespace lmms
90
91#endif // LMMS_FILE_RESOURCE_CACHE_H
A non-owning cache for resources loaded from file paths.
Definition FileResourceCache.h:44
std::unordered_map< std::filesystem::path, Entry > m_entries
Definition FileResourceCache.h:87
auto fetch(const std::filesystem::path &path, Factory &&factory) -> std::shared_ptr< const T >
Definition FileResourceCache.h:60
Definition RemotePluginBase.cpp:34
Definition FileResourceCache.h:82
std::filesystem::file_time_type lastWriteTime
Definition FileResourceCache.h:84
std::weak_ptr< const T > resource
Definition FileResourceCache.h:83