From 430cb5bc5b9f36c4eda2ba8181af8a5e877db619 Mon Sep 17 00:00:00 2001 From: neru Date: Mon, 11 May 2026 07:59:19 -0300 Subject: [PATCH] feat: add event library --- CMakeLists.txt | 2 +- src/lib/seallib/events.h | 76 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 src/lib/seallib/events.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 5faa3c6..c784762 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,7 +32,7 @@ if (SEALLIB_ASSERT) endif() if (SEALLIB_EVENTS) - list(APPEND SEALLIB_SOURCES "src/lib/seallib/events.cpp" "src/lib/seallib/events.h") + list(APPEND SEALLIB_SOURCES "src/lib/seallib/events.h") endif() if (SEALLIB_LOG) diff --git a/src/lib/seallib/events.h b/src/lib/seallib/events.h new file mode 100644 index 0000000..2fced8b --- /dev/null +++ b/src/lib/seallib/events.h @@ -0,0 +1,76 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace seallib +{ + template class Event + { + public: + using CallbackFunc = std::function; + using ConnectionId = size_t; + + ConnectionId addListener(CallbackFunc listener) + { + std::lock_guard lock(_mtx); + ConnectionId id = ++_nextId; + _listeners.push_back({id, std::move(listener)}); + return id; + } + + bool removeListener(ConnectionId id) + { + std::lock_guard lock(_mtx); + + auto it = + std::find_if(_listeners.begin(), _listeners.end(), [id](const Listener& l) { return l.id == id; }); + + if (it != _listeners.end()) + { + _listeners.erase(it); + return true; + } + return false; + } + + template void run(Args&&... args) + { + std::vector snapshot; + + { + std::lock_guard lock(_mtx); + snapshot.reserve(_listeners.size()); + for (const auto& l : _listeners) + { + snapshot.push_back(l.func); + } + } + + for (auto& func : snapshot) + { + func(std::forward(args)...); + } + } + + void clear() + { + std::lock_guard lock(_mtx); + _listeners.clear(); + } + + private: + struct Listener + { + ConnectionId id; + CallbackFunc func; + }; + + std::vector _listeners; + std::mutex _mtx; + std::atomic _nextId{0}; + }; +} // namespace seallib