Bitcoin Core 31.99.0
P2P Digital Currency
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
10namespace util {
11
22template <typename Clock>
24{
25public:
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
61private:
62 static constexpr time_point MIN_TIME{time_point::min()};
64 double m_value{0};
65};
66
67} // namespace util
68
69#endif // BITCOIN_UTIL_TOKENBUCKET_H
A token bucket rate limiter.
Definition: tokenbucket.h:24
const double m_cap
Maximum token balance.
Definition: tokenbucket.h:31
static constexpr time_point MIN_TIME
Definition: tokenbucket.h:62
TokenBucket(double rate, double value, double cap)
Definition: tokenbucket.h:36
time_point m_last_updated
Definition: tokenbucket.h:63
typename Clock::time_point time_point
Definition: tokenbucket.h:27
typename Clock::duration duration
Definition: tokenbucket.h:28
bool decrement(double n=1.0, double floor=0.0)
Consume n tokens.
Definition: tokenbucket.h:52
const double m_rate
Tokens added per second.
Definition: tokenbucket.h:30
void increment(const time_point &now)
Refill tokens based on elapsed time since last call.
Definition: tokenbucket.h:40
double value() const
Current token balance.
Definition: tokenbucket.h:59
std::conditional< std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock, std::chrono::steady_clock >::type Clock
Definition: nanobench.h:148