1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use failure::_core::time::Duration;
use std::num::NonZeroU32;
use {
    algorithms::{Algorithm, RateLimitState},
    DirectRateLimiter, InconsistentCapacity, NegativeMultiDecision,
};

use std::time::Instant;

/// The most naive implementation of a rate-limiter ever: Always
/// allows every cell through.
/// # Example
/// ```
/// use ratelimit_meter::DirectRateLimiter;
/// use ratelimit_meter::example_algorithms::Allower;
/// let mut allower = Allower::ratelimiter();
/// assert!(allower.check().is_ok());
/// ```
#[derive(Default, Copy, Clone, Debug)]
pub struct Allower {}

impl Allower {
    /// Return a rate-limiter that lies, i.e. that allows all requests
    /// through.
    pub fn ratelimiter() -> DirectRateLimiter<Allower> {
        // These numbers are fake, but we make them up for convenience:
        DirectRateLimiter::per_second(nonzero!(1u32))
    }
}

impl RateLimitState<Allower> for () {
    fn last_touched(&self, _params: &Allower) -> Instant {
        Instant::now()
    }
}

#[derive(Fail, Debug, PartialEq)]
#[fail(display = "Should never happen")]
pub struct Impossible();

impl Algorithm for Allower {
    type BucketState = ();
    type NegativeDecision = Impossible;

    fn construct(
        _capacity: NonZeroU32,
        _cell_weight: NonZeroU32,
        _per_time_unit: Duration,
    ) -> Result<Self, InconsistentCapacity> {
        Ok(Allower {})
    }

    /// Allows all cells through unconditionally.
    fn test_n_and_update(
        &self,
        _state: &Self::BucketState,
        _n: u32,
        _t0: Instant,
    ) -> Result<(), NegativeMultiDecision<Impossible>> {
        Ok(())
    }
}