Bitcoin Core
32.1.0
P2P Digital Currency
Toggle main menu visibility
Loading...
Searching...
No Matches
src
util
tokenbucket.h
Go to the documentation of this file.
1
// Copyright (c) The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#ifndef BITCOIN_UTIL_TOKENBUCKET_H
6
#define BITCOIN_UTIL_TOKENBUCKET_H
7
8
#include <util/time.h>
9
10
namespace
util
{
11
22
template
<
typename
Clock>
23
class
TokenBucket
24
{
25
public
:
26
using
clock
= Clock;
27
using
time_point
=
typename
Clock::time_point;
28
using
duration
=
typename
Clock::duration;
29
30
const
double
m_rate
{1};
31
const
double
m_cap
{0};
32
36
TokenBucket
(
double
rate,
double
value
,
double
cap) :
m_rate
{rate},
m_cap
{cap},
m_value
{
std
::min(
value
, cap)} {}
37
40
void
increment
(
const
time_point
& now)
41
{
42
if
(now >
m_last_updated
) {
43
if
(
m_value < m_cap && m_last_updated >
MIN_TIME
) {
44
double
inc =
m_rate
* std::chrono::duration_cast<SecondsDouble>(now -
m_last_updated
).count();
45
m_value
= std::min(
m_cap
,
m_value
+ inc);
46
}
47
}
48
m_last_updated
= now;
49
}
50
52
bool
decrement
(
double
n = 1.0,
double
floor = 0.0)
53
{
54
m_value
-= n;
55
return
(
m_value
> floor);
56
}
57
59
double
value
()
const
{
return
m_value
; }
60
61
private
:
62
static
constexpr
time_point
MIN_TIME
{time_point::min()};
63
time_point
m_last_updated
{
MIN_TIME
};
64
double
m_value
{0};
65
};
66
67
}
// namespace util
68
69
#endif
// BITCOIN_UTIL_TOKENBUCKET_H
util::TokenBucket::m_cap
const double m_cap
Maximum token balance.
Definition
tokenbucket.h:31
util::TokenBucket::MIN_TIME
static constexpr time_point MIN_TIME
Definition
tokenbucket.h:62
util::TokenBucket::TokenBucket
TokenBucket(double rate, double value, double cap)
Definition
tokenbucket.h:36
util::TokenBucket::m_last_updated
time_point m_last_updated
Definition
tokenbucket.h:63
util::TokenBucket::time_point
typename Clock::time_point time_point
Definition
tokenbucket.h:27
util::TokenBucket::duration
typename Clock::duration duration
Definition
tokenbucket.h:28
util::TokenBucket::decrement
bool decrement(double n=1.0, double floor=0.0)
Consume n tokens.
Definition
tokenbucket.h:52
util::TokenBucket::m_value
double m_value
Definition
tokenbucket.h:64
util::TokenBucket::m_rate
const double m_rate
Tokens added per second.
Definition
tokenbucket.h:30
util::TokenBucket::increment
void increment(const time_point &now)
Refill tokens based on elapsed time since last call.
Definition
tokenbucket.h:40
util::TokenBucket::clock
Clock clock
Definition
tokenbucket.h:26
util::TokenBucket::value
double value() const
Current token balance.
Definition
tokenbucket.h:59
std
Definition
transaction.h:420
util
Definition
httpserver.h:27
Generated on
for Bitcoin Core by
1.18.0