SILICON
Loading...
Searching...
No Matches
callbackRegistry.hpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#pragma once
19
20#include <cstdint>
21#include <exception>
22#include <functional>
23#include <unordered_map>
24#include <utility>
25#include <vector>
26
27#include <logging/logger.hpp>
28
29namespace SILICON::core {
30
31template <typename... Args> class CallbackRegistry {
32public:
33 using Callback = std::function<void(Args...)>;
34
35 [[nodiscard]] std::uint64_t add(Callback callback)
36 {
37 const auto id = ++nextId;
38 callbacks.emplace(id, std::move(callback));
39 return id;
40 }
41
42 void remove(const std::uint64_t id) { callbacks.erase(id); }
43
44 void notify(Args... args) const noexcept
45 {
46 try {
47 std::vector<Callback> snapshot;
48 snapshot.reserve(callbacks.size());
49 for (const auto& [id, callback] : callbacks) {
50 static_cast<void>(id);
51 snapshot.push_back(callback);
52 }
53 for (auto& callback : snapshot) {
54 try {
55 callback(args...);
56 } catch (const std::exception& error) {
57 reportFailure(error.what());
58 } catch (...) {
59 reportFailure("Unknown callback exception");
60 }
61 }
62 } catch (const std::exception& error) {
63 reportFailure(error.what());
64 } catch (...) {
65 reportFailure("Unknown callback notification failure");
66 }
67 }
68
69private:
70 static void reportFailure(const std::string_view message) noexcept
71 {
72 try {
73 SILICON::logging::Logger::error("callbacks", message);
74 } catch (...) {
75 // Observer reporting must not escape the notification boundary either.
76 }
77 }
78
79 std::unordered_map<std::uint64_t, Callback> callbacks;
80 std::uint64_t nextId = 0;
81};
82
83} // namespace SILICON::core
std::uint64_t add(Callback callback)
void notify(Args... args) const noexcept
static void reportFailure(const std::string_view message) noexcept
std::unordered_map< std::uint64_t, Callback > callbacks
void remove(const std::uint64_t id)
std::function< void(Args...)> Callback
static void error(std::string_view category, std::string_view message)
Definition logger.cpp:292