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
use aliri_clock::UnixTime;
pub trait JitterSource {
fn jitter(&mut self, time: UnixTime) -> UnixTime;
}
#[derive(Debug)]
pub struct NullJitter;
impl JitterSource for NullJitter {
#[inline]
fn jitter(&mut self, time: UnixTime) -> UnixTime {
time
}
}
#[cfg(feature = "rand")]
mod random {
use aliri_clock::{DurationSecs, UnixTime};
use rand::{Rng, SeedableRng};
#[derive(Debug)]
pub struct RandomEarlyJitter<R> {
max_jitter: DurationSecs,
rand_source: R,
}
impl RandomEarlyJitter<rand::rngs::StdRng> {
pub fn new(max_jitter: DurationSecs) -> Self {
Self {
max_jitter,
rand_source: rand::rngs::StdRng::from_rng(rand::thread_rng()).unwrap(),
}
}
}
impl<R: Rng> super::JitterSource for RandomEarlyJitter<R> {
fn jitter(&mut self, time: UnixTime) -> UnixTime {
let jitter = self.rand_source.gen_range(0..(self.max_jitter.0));
time - DurationSecs(jitter)
}
}
}
#[cfg(feature = "rand")]
pub use random::RandomEarlyJitter;