1use std::cell::Cell;
2use std::time::{Duration, Instant as StdInstant};
3
4const NANOSECONDS_PER_BASIC_BLOCK: u128 = 5000;
10
11#[derive(Debug)]
12pub struct Instant {
13 kind: InstantKind,
14}
15
16#[derive(Debug)]
17enum InstantKind {
18 Host(StdInstant),
19 Virtual { nanoseconds: u128 },
20}
21
22impl Instant {
23 pub fn add_lossy(&self, duration: Duration) -> Instant {
25 match self.kind {
26 InstantKind::Host(instant) => {
27 let i = instant
29 .checked_add(duration)
30 .unwrap_or_else(|| instant.checked_add(Duration::from_secs(3600)).unwrap());
31 Instant { kind: InstantKind::Host(i) }
32 }
33 InstantKind::Virtual { nanoseconds } => {
34 let n = nanoseconds.saturating_add(duration.as_nanos());
35 Instant { kind: InstantKind::Virtual { nanoseconds: n } }
36 }
37 }
38 }
39
40 pub fn duration_since(&self, earlier: Instant) -> Duration {
41 match (&self.kind, earlier.kind) {
42 (InstantKind::Host(instant), InstantKind::Host(earlier)) =>
43 instant.duration_since(earlier),
44 (
45 InstantKind::Virtual { nanoseconds },
46 InstantKind::Virtual { nanoseconds: earlier },
47 ) => {
48 let duration = nanoseconds.saturating_sub(earlier);
49 Duration::from_nanos_u128(duration)
50 }
51 _ => panic!("all `Instant` must be of the same kind"),
52 }
53 }
54}
55
56#[derive(Debug)]
58pub struct MonotonicClock {
59 kind: MonotonicClockKind,
60}
61
62#[derive(Debug)]
63enum MonotonicClockKind {
64 Host {
65 epoch: StdInstant,
68 },
69 Virtual {
70 nanoseconds: Cell<u128>,
72 },
73}
74
75impl MonotonicClock {
76 pub fn new(communicate: bool) -> Self {
78 let kind = if communicate {
79 MonotonicClockKind::Host { epoch: StdInstant::now() }
80 } else {
81 MonotonicClockKind::Virtual { nanoseconds: 0.into() }
82 };
83
84 Self { kind }
85 }
86
87 pub fn tick(&self) {
89 match &self.kind {
90 MonotonicClockKind::Host { .. } => {
91 }
93 MonotonicClockKind::Virtual { nanoseconds } => {
94 nanoseconds.update(|x| x + NANOSECONDS_PER_BASIC_BLOCK);
95 }
96 }
97 }
98
99 pub fn sleep(&self, duration: Duration) {
101 match &self.kind {
102 MonotonicClockKind::Host { .. } => std::thread::sleep(duration),
103 MonotonicClockKind::Virtual { nanoseconds } => {
104 let nanos: u128 = duration.as_nanos();
106 nanoseconds.update(|x| {
107 x.checked_add(nanos)
108 .expect("Miri's virtual clock cannot represent an execution this long")
109 });
110 }
111 }
112 }
113
114 pub fn epoch(&self) -> Instant {
116 match &self.kind {
117 MonotonicClockKind::Host { epoch } => Instant { kind: InstantKind::Host(*epoch) },
118 MonotonicClockKind::Virtual { .. } =>
119 Instant { kind: InstantKind::Virtual { nanoseconds: 0 } },
120 }
121 }
122
123 pub fn now(&self) -> Instant {
124 match &self.kind {
125 MonotonicClockKind::Host { .. } =>
126 Instant { kind: InstantKind::Host(StdInstant::now()) },
127 MonotonicClockKind::Virtual { nanoseconds } =>
128 Instant { kind: InstantKind::Virtual { nanoseconds: nanoseconds.get() } },
129 }
130 }
131}