discord-rpc/src/backoff.h

41 lines
806 B
C
Raw Normal View History

2017-07-18 19:10:39 +01:00
#pragma once
#include <algorithm>
#include <random>
2017-11-10 06:38:59 +00:00
#include <stdint.h>
2017-07-28 21:52:34 +01:00
#include <time.h>
2017-07-18 19:10:39 +01:00
2017-07-25 17:27:48 +01:00
struct Backoff {
2017-07-18 19:10:39 +01:00
int64_t minAmount;
int64_t maxAmount;
int64_t current;
int fails;
std::mt19937_64 randGenerator;
std::uniform_real_distribution<> randDistribution;
2017-07-25 17:27:48 +01:00
double rand01() { return randDistribution(randGenerator); }
2017-07-18 19:10:39 +01:00
Backoff(int64_t min, int64_t max)
2017-07-25 17:27:48 +01:00
: minAmount(min)
, maxAmount(max)
, current(min)
, fails(0)
, randGenerator((uint64_t)time(0))
2017-07-25 17:27:48 +01:00
{
}
2017-07-18 19:10:39 +01:00
void reset()
{
fails = 0;
current = minAmount;
}
int64_t nextDelay()
{
++fails;
int64_t delay = (int64_t)((double)current * 2.0 * rand01());
current = std::min(current + delay, maxAmount);
return current;
}
};