VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
Cooldown.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4#include <map>
5#include <unordered_map>
6#include <utility>
7
8namespace VoltMod
9{
10
11/**
12 * @brief A per-key cooldown, such as one notice per player per minute.
13 *
14 * A slot key resets when a player rejoins into another slot; a SteamID key does not.
15 */
16template <class TKey, class TMap = std::unordered_map<TKey, int64_t>>
18{
19public:
20 Cooldown() = default;
21 explicit Cooldown(int64_t seconds) : _seconds(seconds) {}
22
23 /** Starts @p key's cooldown and returns true, or false while it is still running. 0 seconds never blocks. */
25 {
26 if (SecondsLeft(key, nowSec, seconds) > 0)
27 {
28 return false;
29 }
30 _startedAt[key] = nowSec;
31 return true;
32 }
33
34 bool TryStart(const TKey& key, int64_t nowSec) { return TryStart(key, nowSec, _seconds); }
35
36 /** 0 when @p key is free, also after the clock jumped back. */
38 {
39 if (seconds <= 0)
40 {
41 return 0;
42 }
43 auto it = _startedAt.find(key);
44 if (it == _startedAt.end())
45 {
46 return 0;
47 }
48 const int64_t elapsed = nowSec - it->second;
50 {
51 return 0;
52 }
53 return seconds - elapsed;
54 }
55
56 int64_t SecondsLeft(const TKey& key, int64_t nowSec) const { return SecondsLeft(key, nowSec, _seconds); }
57
58 /** Starts it without checking, for a caller that already checked. */
59 void Start(const TKey& key, int64_t nowSec) { _startedAt[key] = nowSec; }
60
61 void Reset(const TKey& key) { _startedAt.erase(key); }
62
63 /** Removes keys started more than @p maxAgeSec ago. */
65 {
66 std::erase_if(_startedAt, [&](const auto& entry) { return nowSec - entry.second > maxAgeSec; });
67 }
68
69private:
70 int64_t _seconds = 0;
71 TMap _startedAt;
72};
73
74/** std::pair has no std::hash, so pair keys use an ordered map. */
75template <class TFirst, class TSecond>
76using PairCooldown = Cooldown<std::pair<TFirst, TSecond>, std::map<std::pair<TFirst, TSecond>, int64_t>>;
77
78} // namespace VoltMod
A per-key cooldown, such as one notice per player per minute.
Definition Cooldown.hpp:18
void RemoveExpired(int64_t nowSec, int64_t maxAgeSec)
Definition Cooldown.hpp:64
Cooldown()=default
bool TryStart(const TKey &key, int64_t nowSec, int64_t seconds)
Definition Cooldown.hpp:24
Cooldown(int64_t seconds)
Definition Cooldown.hpp:21
void Start(const TKey &key, int64_t nowSec)
Definition Cooldown.hpp:59
int64_t SecondsLeft(const TKey &key, int64_t nowSec) const
Definition Cooldown.hpp:56
int64_t SecondsLeft(const TKey &key, int64_t nowSec, int64_t seconds) const
Definition Cooldown.hpp:37
void Reset(const TKey &key)
Definition Cooldown.hpp:61
bool TryStart(const TKey &key, int64_t nowSec)
Definition Cooldown.hpp:34
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56