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_duration_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
81 #[test]
82 fn test_randomize_time() {
83 let now = SystemTime::now();
84 let one_hour = humantime::parse_duration("1hr").unwrap();
85 let ten_sec = humantime::parse_duration("10s").unwrap();
86 let mut rng = testing_rng();
87
88 for _ in 0..1000 {
89 let t = randomize_time(&mut rng, now, one_hour);
90 assert!(t >= now - one_hour - ten_sec);
91 assert!(t <= now);
92 }
93
94 let close_to_epoch = humantime::parse_rfc3339("1970-01-01T00:30:00Z").unwrap();
95 for _ in 0..1000 {
96 let t = randomize_time(&mut rng, close_to_epoch, one_hour);
97 assert!(t >= SystemTime::UNIX_EPOCH);
98 assert!(t <= close_to_epoch);
99 let d = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
100 assert_eq!(d.subsec_nanos(), 0);
101 assert_eq!(d.as_secs() % 10, 0);
102 }
103 }
104}