1use rand::Rng;
4use std::time::{Duration, SystemTime};
5use tor_basic_utils::RngExt as _;
6
7pub(crate) fn randomize_time<R: Rng>(rng: &mut R, when: SystemTime, max: Duration) -> SystemTime {
16 let offset = rng.gen_range_infallible(..=max);
17 let random = when
18 .checked_sub(offset)
19 .unwrap_or(SystemTime::UNIX_EPOCH)
20 .max(SystemTime::UNIX_EPOCH);
21 round_time(random, 10)
23}
24
25fn round_time(when: SystemTime, d: u32) -> SystemTime {
37 let (early, elapsed) = if when < SystemTime::UNIX_EPOCH {
38 (
39 true,
40 SystemTime::UNIX_EPOCH
41 .duration_since(when)
42 .expect("logic_error"),
43 )
44 } else {
45 (
46 false,
47 when.duration_since(SystemTime::UNIX_EPOCH)
48 .expect("logic error"),
49 )
50 };
51
52 let secs_elapsed = elapsed.as_secs();
53 let secs_rounded = secs_elapsed - (secs_elapsed % u64::from(d));
54 let dur_rounded = Duration::from_secs(secs_rounded);
55
56 if early {
57 SystemTime::UNIX_EPOCH - dur_rounded
58 } else {
59 SystemTime::UNIX_EPOCH + dur_rounded
60 }
61}
62
63#[cfg(test)]
64mod test {
65 #![allow(clippy::bool_assert_comparison)]
67 #![allow(clippy::clone_on_copy)]
68 #![allow(clippy::dbg_macro)]
69 #![allow(clippy::mixed_attributes_style)]
70 #![allow(clippy::print_stderr)]
71 #![allow(clippy::print_stdout)]
72 #![allow(clippy::single_char_pattern)]
73 #![allow(clippy::unwrap_used)]
74 #![allow(clippy::unchecked_time_subtraction)]
75 #![allow(clippy::useless_vec)]
76 #![allow(clippy::needless_pass_by_value)]
77 use super::*;
79 use tor_basic_utils::test_rng::testing_rng;
80 use web_time_compat::SystemTimeExt;
81
82 #[test]
83 fn test_randomize_time() {
84 let now = SystemTime::get();
85 let one_hour = humantime::parse_duration("1hr").unwrap();
86 let ten_sec = humantime::parse_duration("10s").unwrap();
87 let mut rng = testing_rng();
88
89 for _ in 0..1000 {
90 let t = randomize_time(&mut rng, now, one_hour);
91 assert!(t >= now - one_hour - ten_sec);
92 assert!(t <= now);
93 }
94
95 let close_to_epoch = humantime::parse_rfc3339("1970-01-01T00:30:00Z").unwrap();
96 for _ in 0..1000 {
97 let t = randomize_time(&mut rng, close_to_epoch, one_hour);
98 assert!(t >= SystemTime::UNIX_EPOCH);
99 assert!(t <= close_to_epoch);
100 let d = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
101 assert_eq!(d.subsec_nanos(), 0);
102 assert_eq!(d.as_secs() % 10, 0);
103 }
104 }
105}