VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
LazyHook.hpp
Go to the documentation of this file.
1#pragma once
2
6#include <functional>
7#include <string>
8
9namespace VoltMod
10{
11
12/**
13 * @brief An engine hook that exists only while one of its events has handlers.
14 *
15 * The first event to gain a handler calls @p install and keeps the hook it returns; the last one to
16 * go quiet removes it. An install error is logged under @p name and refuses that subscription, so a
17 * later subscriber retries.
18 *
19 * @code
20 * Damage::Damage(...)
21 * : _hook("Damage", [this] { return HookFunction("Damage", _bindings.TakeDamage, ...); }),
22 * Before(_hook.ForEvent())
23 * @endcode
24 *
25 * Adapters borrow this object, so declare it before the events they belong to. Destroying it with
26 * handlers still attached is an ownership error that can leave a hook in an unloading module; the
27 * destructor logs it.
28 */
30{
31public:
32 LazyHook(std::string name, std::function<Result<Subscription>()> install);
33 ~LazyHook();
34
35 LazyHook(const LazyHook&) = delete;
36 LazyHook& operator=(const LazyHook&) = delete;
37
39
40 bool Installed() const noexcept { return static_cast<bool>(_hook); }
41
42 /** Number of adapted events with at least one handler. For diagnostics and tests only. */
43 int ListeningEvents() const noexcept { return _listening; }
44
45private:
46 bool AddListener();
47 void RemoveListener();
48
49 std::string _name;
50 std::function<Result<Subscription>()> _install;
51 Subscription _hook;
52 int _listening = 0;
53};
54
55} // namespace VoltMod
An engine hook that exists only while one of its events has handlers.
Definition LazyHook.hpp:30
bool Installed() const noexcept
Definition LazyHook.hpp:40
LazyHook & operator=(const LazyHook &)=delete
LazyHook(const LazyHook &)=delete
EventLifecycle ForEvent()
Definition LazyHook.cpp:21
int ListeningEvents() const noexcept
Definition LazyHook.hpp:43
Owns one registration and releases it on destruction.
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56
std::expected< T, Error > Result
Definition Result.hpp:64
Starting and stopping an Event source, driven by whether anything is listening.
Definition Event.hpp:22