VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
PerSlot.hpp
Go to the documentation of this file.
1#pragma once
2
6#include <array>
7#include <cassert>
8#include <cstdint>
9
10namespace VoltMod
11{
12
13/**
14 * @brief Per-player-slot value store that never leaks state across occupants.
15 *
16 * A plain `std::array<T, MaxPlayers>`. Constructed with the slot-change feed, the entry for a
17 * slot is value-reset whenever a player joins or leaves it: `PerSlot<State> _state{runtime.Slots};`.
18 * Default construction is inert, for an owner that resets entries itself.
19 *
20 * Takes @ref SlotEvents rather than the runtime so a plugin translation unit
21 * that includes only this header still compiles.
22 */
23template <class T>
25{
26public:
27 PerSlot() = default;
28 /** Resets a slot's entry on player connect/disconnect. @p slots must outlive this object. */
29 explicit PerSlot(SlotEvents& slots) : _listener(slots.Changed += [this](int slot) { Reset(slot); }) {}
30 /** Unsubscribes directly, so the feed cannot reset entries that are going away. */
31 ~PerSlot() { _listener.Reset(); }
32 PerSlot(const PerSlot&) = delete;
33 PerSlot& operator=(const PerSlot&) = delete;
34
35 /** @pre IsValidSlot(slot); asserted, not checked - callers that can receive an unvalidated
36 * slot (console callers, CallerSlot() == -1) must check IsValidSlot before indexing. */
38 {
40 return _items[slot];
41 }
42 const T& operator[](int slot) const
43 {
45 return _items[slot];
46 }
47
48 void Reset(int slot)
49 {
50 if (IsValidSlot(slot))
51 {
52 _items[slot] = T{};
53 }
54 }
55
56 /** Assigned one by one rather than through `fill`, which would copy: the common T here is
57 * move-only (a Subscription), and dropping one is exactly what cancels it. */
58 void ResetAll()
59 {
60 for (T& item : _items)
61 {
62 item = T{};
63 }
64 }
65
66private:
67 std::array<T, MaxPlayers> _items{};
68 Subscription _listener;
69};
70
71} // namespace VoltMod
Per-player-slot value store that never leaks state across occupants.
Definition PerSlot.hpp:25
const T & operator[](int slot) const
Definition PerSlot.hpp:42
PerSlot & operator=(const PerSlot &)=delete
void Reset(int slot)
Definition PerSlot.hpp:48
PerSlot()=default
PerSlot(SlotEvents &slots)
Definition PerSlot.hpp:29
T & operator[](int slot)
Definition PerSlot.hpp:37
PerSlot(const PerSlot &)=delete
"The occupant of this slot changed" - raised by PlayerManager, consumed below it.
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56
constexpr bool IsValidSlot(int slot)
Definition Slot.hpp:13