SlHelpers
Ratelimit.h
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 #pragma once
4 
5 #include <chrono>
6 
7 namespace SlHelpers {
8 
12 class Ratelimit {
13 public:
15  using Clock = std::chrono::steady_clock;
16 
17  Ratelimit() = delete;
18 
23  Ratelimit(const std::chrono::milliseconds &dur) : dur(dur), last(Clock::time_point{}) { }
24 
26  void reset() { last = Clock::time_point{}; }
27 
32  bool limit() {
33  const auto now = Clock::now();
34  if (last + dur < now) {
35  last = now;
36  return true;
37  }
38 
39  return false;
40  }
41 private:
42  const std::chrono::milliseconds dur;
43  Clock::time_point last;
44 };
45 
46 }
void reset()
Start counting from now.
Definition: Ratelimit.h:26
Rate-limit some actions.
Definition: Ratelimit.h:12
bool limit()
Limit actions to one per constructor&#39;s dur.
Definition: Ratelimit.h:32
Ratelimit(const std::chrono::milliseconds &dur)
Construct new Ratelimit, allowing action to be once per dur.
Definition: Ratelimit.h:23
std::chrono::steady_clock Clock
Clock used for measuring.
Definition: Ratelimit.h:15
Definition: Color.h:8