309 lines
8.4 KiB
C++
309 lines
8.4 KiB
C++
#pragma once
|
|
|
|
#include <Void/Async/Detail/Types.hpp>
|
|
#include <Void/Functional/Result.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <concepts>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <deque>
|
|
#include <functional>
|
|
#include <memory>
|
|
#include <tuple>
|
|
#include <type_traits>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace Void::Observable
|
|
{
|
|
|
|
inline constexpr std::size_t kMaxPendingNotifications = 1024;
|
|
|
|
struct Handle {
|
|
std::uint64_t id{0};
|
|
[[nodiscard]] bool operator==(const Handle&) const noexcept = default;
|
|
};
|
|
|
|
namespace detail
|
|
{
|
|
struct EmptyQueue {};
|
|
} // namespace detail
|
|
|
|
/// Observable value container holding a T and notifying listeners on change.
|
|
/// Single-threaded (not thread-safe across threads), reentrancy-safe:
|
|
/// - Copyable T: nested set() updates the value immediately and queues (old, new)
|
|
/// notifications FIFO after the active pass (bounded at kMaxPendingNotifications).
|
|
/// - Move-only T: 1.x immediate recursive notification over a listener snapshot.
|
|
template <typename T>
|
|
class Observable
|
|
{
|
|
public:
|
|
using Listener = std::function<void(const T& old_val, const T& new_val)>;
|
|
|
|
explicit Observable(T initial = {})
|
|
: value_{std::move(initial)}
|
|
{
|
|
}
|
|
|
|
[[nodiscard]] const T& get() const noexcept { return value_; }
|
|
[[nodiscard]] operator const T&() const noexcept { return value_; }
|
|
|
|
void set(T new_val)
|
|
{
|
|
if (new_val == value_) {
|
|
return;
|
|
}
|
|
T old = std::move(value_);
|
|
value_ = std::move(new_val);
|
|
if constexpr (std::copy_constructible<T>) {
|
|
if (dispatch_depth_ > 0) {
|
|
if (pending_.size() < kMaxPendingNotifications) {
|
|
pending_.emplace_back(std::move(old), value_);
|
|
} else {
|
|
++dropped_notifications_;
|
|
}
|
|
return;
|
|
}
|
|
dispatch_fifo(std::move(old), value_);
|
|
} else {
|
|
notify_snapshot(old, value_);
|
|
}
|
|
}
|
|
|
|
/// Bounded reentrant update for copyable T: returns overloaded without
|
|
/// modifying value_ if the nested notification queue is full.
|
|
[[nodiscard]] Void::Result::Result<void> try_set(T new_val)
|
|
requires std::copy_constructible<T>
|
|
{
|
|
if (new_val == value_) {
|
|
return {};
|
|
}
|
|
if (dispatch_depth_ > 0 &&
|
|
pending_.size() >= kMaxPendingNotifications) {
|
|
return std::unexpected{Void::Async::make_async_error(
|
|
Void::Async::AsyncErrorCode::overloaded,
|
|
"Observable pending notification queue full")};
|
|
}
|
|
set(std::move(new_val));
|
|
return {};
|
|
}
|
|
|
|
Observable& operator=(T new_val)
|
|
{
|
|
set(std::move(new_val));
|
|
return *this;
|
|
}
|
|
|
|
Handle on_change(Listener fn)
|
|
{
|
|
const Handle h{next_id_++};
|
|
auto entry = std::make_shared<Entry>(Entry{h, true, std::move(fn)});
|
|
listeners_.push_back(std::move(entry));
|
|
return h;
|
|
}
|
|
|
|
bool unsubscribe(Handle h)
|
|
{
|
|
for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
|
|
if ((*it)->handle == h) {
|
|
(*it)->active = false;
|
|
auto dropped = std::move((*it)->fn);
|
|
listeners_.erase(it);
|
|
dropped = {};
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
[[nodiscard]] std::size_t listener_count() const noexcept
|
|
{
|
|
return listeners_.size();
|
|
}
|
|
|
|
[[nodiscard]] std::size_t dropped_notifications() const noexcept
|
|
{
|
|
return dropped_notifications_;
|
|
}
|
|
|
|
private:
|
|
struct Entry {
|
|
Handle handle{0};
|
|
bool active{true};
|
|
Listener fn{};
|
|
};
|
|
|
|
void notify_snapshot(const T& old_val, const T& new_val) const
|
|
{
|
|
auto snapshot = listeners_;
|
|
for (const auto& entry : snapshot) {
|
|
if (!entry->active || !entry->fn) {
|
|
continue;
|
|
}
|
|
auto fn = entry->fn;
|
|
fn(old_val, new_val);
|
|
fn = {};
|
|
}
|
|
}
|
|
|
|
void dispatch_fifo(T first_old, T first_new)
|
|
requires std::copy_constructible<T>
|
|
{
|
|
dispatch_depth_ = 1;
|
|
try {
|
|
notify_snapshot(first_old, first_new);
|
|
while (!pending_.empty()) {
|
|
auto next = std::move(pending_.front());
|
|
pending_.pop_front();
|
|
notify_snapshot(next.first, next.second);
|
|
}
|
|
} catch (...) {
|
|
dropped_notifications_ += pending_.size();
|
|
pending_.clear();
|
|
dispatch_depth_ = 0;
|
|
throw;
|
|
}
|
|
dispatch_depth_ = 0;
|
|
}
|
|
|
|
using QueueType = std::conditional_t<
|
|
std::copy_constructible<T>,
|
|
std::deque<std::pair<T, T>>,
|
|
detail::EmptyQueue>;
|
|
|
|
T value_;
|
|
std::vector<std::shared_ptr<Entry>> listeners_{};
|
|
QueueType pending_{};
|
|
std::size_t dispatch_depth_{0};
|
|
std::size_t dropped_notifications_{0};
|
|
std::uint64_t next_id_{1};
|
|
};
|
|
|
|
/// Typed multi-slot signal.
|
|
/// Single-threaded (not thread-safe across threads), reentrancy-safe:
|
|
/// snapshots connected slots and queues nested emit() calls FIFO when all
|
|
/// decayed Args are copy-constructible (bounded at kMaxPendingNotifications).
|
|
template <typename... Args>
|
|
class Signal
|
|
{
|
|
public:
|
|
using Slot = std::function<void(const Args&...)>;
|
|
|
|
Handle connect(Slot fn)
|
|
{
|
|
const Handle h{next_id_++};
|
|
auto entry = std::make_shared<Entry>(Entry{h, true, std::move(fn)});
|
|
slots_.push_back(std::move(entry));
|
|
return h;
|
|
}
|
|
|
|
bool disconnect(Handle h)
|
|
{
|
|
for (auto it = slots_.begin(); it != slots_.end(); ++it) {
|
|
if ((*it)->handle == h) {
|
|
(*it)->active = false;
|
|
auto dropped = std::move((*it)->fn);
|
|
slots_.erase(it);
|
|
dropped = {};
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void clear() noexcept
|
|
{
|
|
auto all = std::move(slots_);
|
|
slots_.clear();
|
|
for (auto& e : all) {
|
|
e->active = false;
|
|
e->fn = {};
|
|
}
|
|
}
|
|
|
|
void emit(const Args&... args) const
|
|
{
|
|
constexpr bool kAllCopyable =
|
|
(std::copy_constructible<std::decay_t<Args>> && ...);
|
|
if constexpr (kAllCopyable) {
|
|
if (dispatch_depth_ > 0) {
|
|
if (pending_.size() < kMaxPendingNotifications) {
|
|
pending_.emplace_back(args...);
|
|
} else {
|
|
++dropped_notifications_;
|
|
}
|
|
return;
|
|
}
|
|
dispatch_depth_ = 1;
|
|
try {
|
|
emit_snapshot(args...);
|
|
while (!pending_.empty()) {
|
|
auto next = std::move(pending_.front());
|
|
pending_.pop_front();
|
|
std::apply(
|
|
[this](const auto&... packed) {
|
|
emit_snapshot(packed...);
|
|
},
|
|
next);
|
|
}
|
|
} catch (...) {
|
|
dropped_notifications_ += pending_.size();
|
|
pending_.clear();
|
|
dispatch_depth_ = 0;
|
|
throw;
|
|
}
|
|
dispatch_depth_ = 0;
|
|
} else {
|
|
emit_snapshot(args...);
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] std::size_t slot_count() const noexcept
|
|
{
|
|
return slots_.size();
|
|
}
|
|
|
|
[[nodiscard]] std::size_t dropped_notifications() const noexcept
|
|
{
|
|
return dropped_notifications_;
|
|
}
|
|
|
|
private:
|
|
struct Entry {
|
|
Handle handle{0};
|
|
bool active{true};
|
|
Slot fn{};
|
|
};
|
|
|
|
void emit_snapshot(const Args&... args) const
|
|
{
|
|
auto snapshot = slots_;
|
|
for (const auto& entry : snapshot) {
|
|
if (!entry->active || !entry->fn) {
|
|
continue;
|
|
}
|
|
auto fn = entry->fn;
|
|
fn(args...);
|
|
fn = {};
|
|
}
|
|
}
|
|
|
|
static constexpr bool kCopyableArgs =
|
|
(std::copy_constructible<std::decay_t<Args>> && ...);
|
|
|
|
using TupleType = std::tuple<std::decay_t<Args>...>;
|
|
using QueueType = std::conditional_t<
|
|
kCopyableArgs,
|
|
std::deque<TupleType>,
|
|
detail::EmptyQueue>;
|
|
|
|
std::vector<std::shared_ptr<Entry>> slots_{};
|
|
mutable QueueType pending_{};
|
|
mutable std::size_t dispatch_depth_{0};
|
|
mutable std::size_t dropped_notifications_{0};
|
|
std::uint64_t next_id_{1};
|
|
};
|
|
|
|
} // namespace Void::Observable
|