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