1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use rand::Rng;
use std::time::{Duration, SystemTime};
pub(crate) fn randomize_time<R: Rng>(rng: &mut R, when: SystemTime, max: Duration) -> SystemTime {
let offset = rng.gen_range(Duration::ZERO..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::unwrap_used)]
use super::*;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn test_randomize_time() {
let now = SystemTime::now();
let one_hour = Duration::from_secs(3600);
let ten_sec = Duration::from_secs(10);
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 = SystemTime::UNIX_EPOCH + one_hour / 2;
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);
}
}
}