My Project
3.7.1
C++ Distributed Hash Table
Loading...
Searching...
No Matches
include
opendht
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
8
namespace
dht
{
9
10
class
RateLimiter
11
{
12
public
:
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
38
private
:
39
const
size_t
quota_;
40
const
duration period_;
41
std::queue<time_point> records {};
42
};
43
44
}
// namespace dht
dht::RateLimiter::limit
bool limit(const time_point &now)
Definition
rate_limiter.h:27
dht::RateLimiter::maintain
size_t maintain(const time_point &now)
Definition
rate_limiter.h:19
dht
Definition
callbacks.h:17
Generated on
for My Project by
1.15.0