use rand::Rng;
use std::time::{Duration, SystemTime};
use tor_basic_utils::RngExt as _;
pub(crate) fn randomize_time<R: Rng>(rng: &mut R, when: SystemTime, max: Duration) -> SystemTime {
let offset = rng.gen_range_infallible(..=max);
let random = when
.checked_sub(offset)
.unwrap_or(SystemTime::UNIX_EPOCH)
.max(SystemTime::UNIX_EPOCH);
round_time(random, 10)
}
fn round_time(when: SystemTime, d: u32) -> SystemTime {
let (early, elapsed) = if when < SystemTime::UNIX_EPOCH {
(
true,
SystemTime::UNIX_EPOCH
.duration_since(when)
.expect("logic_error"),
)
} else {
(
false,
when.duration_since(SystemTime::UNIX_EPOCH)
.expect("logic error"),
)
};
let secs_elapsed = elapsed.as_secs();
let secs_rounded = secs_elapsed - (secs_elapsed % u64::from(d));
let dur_rounded = Duration::from_secs(secs_rounded);
if early {
SystemTime::UNIX_EPOCH - dur_rounded
} else {
SystemTime::UNIX_EPOCH + dur_rounded
}
}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_time_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
use super::*;
use tor_basic_utils::test_rng::testing_rng;
use web_time_compat::SystemTimeExt;
#[test]
fn test_randomize_time() {
let now = SystemTime::get();
let one_hour = humantime::parse_duration("1hr").unwrap();
let ten_sec = humantime::parse_duration("10s").unwrap();
let mut rng = testing_rng();
for _ in 0..1000 {
let t = randomize_time(&mut rng, now, one_hour);
assert!(t >= now - one_hour - ten_sec);
assert!(t <= now);
}
let close_to_epoch = humantime::parse_rfc3339("1970-01-01T00:30:00Z").unwrap();
for _ in 0..1000 {
let t = randomize_time(&mut rng, close_to_epoch, one_hour);
assert!(t >= SystemTime::UNIX_EPOCH);
assert!(t <= close_to_epoch);
let d = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
assert_eq!(d.subsec_nanos(), 0);
assert_eq!(d.as_secs() % 10, 0);
}
}
}