VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
LazyHook.cpp
Go to the documentation of this file.
3#include <utility>
4
5namespace VoltMod
6{
7
8LazyHook::LazyHook(std::string name, std::function<Result<Subscription>()> install)
9 : _name(std::move(name)), _install(std::move(install))
10{}
11
13{
14 // Never leave a handler pointing into state that is going away.
15 if (_listening != 0)
16 {
17 Log::Error("{}: {} event(s) still had handlers when the hook went away; one may dangle.", _name, _listening);
18 }
19}
20
22{
23 return {.OnFirst = [this] { return AddListener(); }, .OnLast = [this] { RemoveListener(); }};
24}
25
26bool LazyHook::AddListener()
27{
28 if (_listening == 0)
29 {
30 auto hook = _install();
31 if (!hook)
32 {
33 Log::Warn("{}: {}; its handlers will not fire.", _name, hook.error().Detail);
34 return false;
35 }
36 _hook = std::move(*hook);
37 }
38
39 ++_listening;
40 return true;
41}
42
43void LazyHook::RemoveListener()
44{
45 if (_listening > 0 && --_listening == 0)
46 {
47 _hook.Reset();
48 }
49}
50
51} // namespace VoltMod
LazyHook(std::string name, std::function< Result< Subscription >()> install)
Definition LazyHook.cpp:8
EventLifecycle ForEvent()
Definition LazyHook.cpp:21
void Error(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:97
void Warn(std::format_string< Args... > fmt, Args &&... args)
Definition Log.hpp:88
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
std::function< bool()> OnFirst
Definition Event.hpp:23