VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
ConVarOverrides.hpp
Go to the documentation of this file.
1#pragma once
2
4#include <algorithm>
5#include <string>
6#include <string_view>
7#include <vector>
8
9namespace VoltMod
10{
11
12/**
13 * Server-wide convar overrides that restore the first observed value on destruction.
14 * Writes use the console so FCVAR_REPLICATED changes reach clients. Use @ref ConVar::SetFor for
15 * one client.
16 */
18{
19public:
20 /** @p conVars must outlive this object. */
21 explicit ConVarOverrides(ConVars& conVars) : _conVars(conVars) {}
25
26 /** Set and snapshot on first use. Later calls reapply without replacing the snapshot. */
27 template <class T>
28 bool Set(ConVar<T>& cvar, const T& value)
29 {
30 if (!cvar)
31 {
32 return false;
33 }
34
35 const auto name = cvar.Name();
36 if (std::ranges::find(_saved, name, &Snapshot::Name) == _saved.end())
37 {
38 _saved.push_back({.Name = std::string(name), .Value = ConVarText(cvar.Get())});
39 }
40
41 return cvar.Set(value).has_value();
42 }
43
44 /** Restore and forget one override. */
45 template <class T>
46 void Restore(const ConVar<T>& cvar)
47 {
48 Restore(cvar.Name());
49 }
50
51 /** Restore all overrides in insertion order. */
52 void RestoreAll();
53
54private:
55 struct Snapshot
56 {
57 std::string Name;
58 std::string Value;
59 };
60
61 // Names remain valid if callers move or destroy their handles.
62 void Restore(std::string_view name);
63 void Write(std::string_view name, std::string_view value);
64
65 ConVars& _conVars;
66 std::vector<Snapshot> _saved;
67};
68
69} // namespace VoltMod
ConVarOverrides & operator=(const ConVarOverrides &)=delete
ConVarOverrides(ConVars &conVars)
bool Set(ConVar< T > &cvar, const T &value)
void Restore(const ConVar< T > &cvar)
ConVarOverrides(const ConVarOverrides &)=delete
std::string ConVarText(const T &value)
constexpr std::string_view Name(E value) noexcept
Definition EnumNames.hpp:33
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56