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 let seconds = u64::try_from(duration / 1_000_000_000).unwrap_or(u64::MAX);
54 let nanosecond = u32::try_from(duration.wrapping_rem(1_000_000_000)).unwrap();
56 Duration::new(seconds, nanosecond)
57 }
58 _ => panic!("all `Instant` must be of the same kind"),
59 }
60 }
61}
62
63#[derive(Debug)]
65pub struct Clock {
66 kind: ClockKind,
67}
68
69#[derive(Debug)]
70enum ClockKind {
71 Host {
72 epoch: StdInstant,
75 },
76 Virtual {
77 nanoseconds: Cell<u128>,
79 },
80}
81
82impl Clock {
83 pub fn new(communicate: bool) -> Self {
85 let kind = if communicate {
86 ClockKind::Host { epoch: StdInstant::now() }
87 } else {
88 ClockKind::Virtual { nanoseconds: 0.into() }
89 };
90
91 Self { kind }
92 }
93
94 pub fn tick(&self) {
96 match &self.kind {
97 ClockKind::Host { .. } => {
98 }
100 ClockKind::Virtual { nanoseconds } => {
101 nanoseconds.update(|x| x + NANOSECONDS_PER_BASIC_BLOCK);
102 }
103 }
104 }
105
106 pub fn sleep(&self, duration: Duration) {
108 match &self.kind {
109 ClockKind::Host { .. } => std::thread::sleep(duration),
110 ClockKind::Virtual { nanoseconds } => {
111 let nanos: u128 = duration.as_nanos();
113 nanoseconds.update(|x| {
114 x.checked_add(nanos)
115 .expect("Miri's virtual clock cannot represent an execution this long")
116 });
117 }
118 }
119 }
120
121 pub fn epoch(&self) -> Instant {
123 match &self.kind {
124 ClockKind::Host { epoch } => Instant { kind: InstantKind::Host(*epoch) },
125 ClockKind::Virtual { .. } => Instant { kind: InstantKind::Virtual { nanoseconds: 0 } },
126 }
127 }
128
129 pub fn now(&self) -> Instant {
130 match &self.kind {
131 ClockKind::Host { .. } => Instant { kind: InstantKind::Host(StdInstant::now()) },
132 ClockKind::Virtual { nanoseconds } =>
133 Instant { kind: InstantKind::Virtual { nanoseconds: nanoseconds.get() } },
134 }
135 }
136}