5#include <unordered_map>
16template <
class TKey,
class TMap = std::unordered_map<TKey,
int64_t>>
21 explicit Cooldown(int64_t seconds) : _seconds(seconds) {}
24 bool TryStart(
const TKey& key, int64_t nowSec, int64_t seconds)
30 _startedAt[key] = nowSec;
34 bool TryStart(
const TKey& key, int64_t nowSec) {
return TryStart(key, nowSec, _seconds); }
37 int64_t
SecondsLeft(
const TKey& key, int64_t nowSec, int64_t seconds)
const
43 auto it = _startedAt.find(key);
44 if (it == _startedAt.end())
48 const int64_t elapsed = nowSec - it->second;
49 if (elapsed < 0 || elapsed >= seconds)
53 return seconds - elapsed;
59 void Start(
const TKey& key, int64_t nowSec) { _startedAt[key] = nowSec; }
61 void Reset(
const TKey& key) { _startedAt.erase(key); }
66 std::erase_if(_startedAt, [&](
const auto& entry) {
return nowSec - entry.second > maxAgeSec; });
75template <
class TFirst,
class TSecond>
A per-key cooldown, such as one notice per player per minute.
void RemoveExpired(int64_t nowSec, int64_t maxAgeSec)
bool TryStart(const TKey &key, int64_t nowSec, int64_t seconds)
Cooldown(int64_t seconds)
void Start(const TKey &key, int64_t nowSec)
int64_t SecondsLeft(const TKey &key, int64_t nowSec) const
int64_t SecondsLeft(const TKey &key, int64_t nowSec, int64_t seconds) const
void Reset(const TKey &key)
bool TryStart(const TKey &key, int64_t nowSec)
Cooldown< std::pair< TFirst, TSecond >, std::map< std::pair< TFirst, TSecond >, int64_t > > PairCooldown