My Project 3.7.1
C++ Distributed Hash Table
Loading...
Searching...
No Matches
rate_limiter.h
1// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
2// SPDX-License-Identifier: MIT
3#pragma once
4
5#include "utils.h"
6#include <queue>
7
8namespace dht {
9
10class RateLimiter
11{
12public:
13 RateLimiter(size_t quota, const duration& period = std::chrono::seconds(1))
14 : quota_(quota)
15 , period_(period)
16 {}
17
19 size_t maintain(const time_point& now)
20 {
21 auto limit = now - period_;
22 while (not records.empty() and records.front() < limit)
23 records.pop();
24 return records.size();
25 }
26
27 bool limit(const time_point& now)
28 {
29 if (quota_ == std::numeric_limits<size_t>::max())
30 return true;
31 if (maintain(now) >= quota_)
32 return false;
33 records.emplace(now);
34 return true;
35 }
36 bool empty() const { return records.empty(); }
37
38private:
39 const size_t quota_;
40 const duration period_;
41 std::queue<time_point> records {};
42};
43
44} // namespace dht
bool limit(const time_point &now)
size_t maintain(const time_point &now)