Files
Library/include/Void/EventBus/EventBus.hpp
T
faumarayandClaude Sonnet 4.6 58ff7b38a0 Add 20+ new modules with tests: Pipeline, Matrix, Tokenizer, ScopeGuard, Bitset, Optional, Counted, Curry, TypeMap, Bench, DisjointSet, Histogram, StopWatch, and more
Also fixes Diff/Memo/PriorityQueue from previous session: LineDiff is now
an alias for Edit<string> so count_op/apply work on line diffs; Memoized
uses std::apply instead of type-based get to handle duplicate arg types.

874/877 tests pass (3 are platform-gated plugin tests).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:49:09 +03:00

82 lines
2.4 KiB
C++

#pragma once
#include <any>
#include <cstddef>
#include <functional>
#include <typeindex>
#include <unordered_map>
#include <vector>
namespace Void::EventBus
{
// ── EventBus ──────────────────────────────────────────────────────────────────
// Synchronous publish/subscribe bus keyed by event type.
// Handlers are invoked on the caller's thread inside publish().
// Not thread-safe; use external locking if shared across threads.
class EventBus
{
public:
using HandlerId = std::size_t;
// Subscribe to events of type Event. Returns a HandlerId for unsubscription.
template <typename Event>
HandlerId subscribe(std::function<void(const Event&)> handler)
{
const auto key = std::type_index{typeid(Event)};
const HandlerId id = next_id_++;
handlers_[key].push_back(Entry{id, [h = std::move(handler)](const std::any& ev) {
h(std::any_cast<const Event&>(ev));
}});
return id;
}
// Publish an event to all subscribers of its type.
template <typename Event>
void publish(const Event& event)
{
const auto key = std::type_index{typeid(Event)};
const auto it = handlers_.find(key);
if (it == handlers_.end()) return;
for (const auto& e : it->second) e.fn(event);
}
// Unsubscribe by id. O(n) per event type — acceptable for small handler counts.
void unsubscribe(HandlerId id)
{
for (auto& [key, list] : handlers_) {
const auto before = list.size();
std::erase_if(list, [id](const Entry& e) { return e.id == id; });
if (list.size() != before) return;
}
}
// Remove all handlers for a given event type.
template <typename Event>
void clear()
{
handlers_.erase(std::type_index{typeid(Event)});
}
void clear_all() { handlers_.clear(); }
template <typename Event>
[[nodiscard]] std::size_t subscriber_count() const
{
const auto it = handlers_.find(std::type_index{typeid(Event)});
return it == handlers_.end() ? 0 : it->second.size();
}
private:
struct Entry {
HandlerId id;
std::function<void(const std::any&)> fn;
};
std::unordered_map<std::type_index, std::vector<Entry>> handlers_;
HandlerId next_id_{1};
};
} // namespace Void::EventBus