aboutsummaryrefslogtreecommitdiff
path: root/examples/simple_repeater/RateLimiter.h
blob: a6633c0a26864d3f7ad052ef852d03b2a020c5fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#pragma once

#include <stdint.h>

class RateLimiter {
  uint32_t _start_timestamp;
  uint32_t _secs;
  uint16_t _maximum, _count;

public:
  RateLimiter(uint16_t maximum, uint32_t secs): _maximum(maximum), _secs(secs), _start_timestamp(0), _count(0) { }

  bool allow(uint32_t now) {
    if (now < _start_timestamp + _secs) {
      _count++;
      if (_count > _maximum) return false;   // deny
    } else {   // time window now expired
      _start_timestamp = now;
      _count = 1;
    }
    return true;
  }
};