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")]
#[cfg_attr(docsrs, doc(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")]
#[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
pub use random::RandomEarlyJitter;