@@ -6,7 +6,7 @@ use std::time::{Duration, Instant as StdInstant};
6
6
/// This number is pretty random, but it has been shown to approximately cause
7
7
/// some sample programs to run within an order of magnitude of real time on desktop CPUs.
8
8
/// (See `tests/pass/shims/time-with-isolation*.rs`.)
9
- const NANOSECONDS_PER_BASIC_BLOCK : u64 = 5000 ;
9
+ const NANOSECONDS_PER_BASIC_BLOCK : u128 = 5000 ;
10
10
11
11
#[ derive( Debug ) ]
12
12
pub struct Instant {
@@ -16,7 +16,7 @@ pub struct Instant {
16
16
#[ derive( Debug ) ]
17
17
enum InstantKind {
18
18
Host ( StdInstant ) ,
19
- Virtual { nanoseconds : u64 } ,
19
+ Virtual { nanoseconds : u128 } ,
20
20
}
21
21
22
22
impl Instant {
@@ -25,9 +25,8 @@ impl Instant {
25
25
InstantKind :: Host ( instant) =>
26
26
instant. checked_add ( duration) . map ( |i| Instant { kind : InstantKind :: Host ( i) } ) ,
27
27
InstantKind :: Virtual { nanoseconds } =>
28
- u128 :: from ( nanoseconds)
28
+ nanoseconds
29
29
. checked_add ( duration. as_nanos ( ) )
30
- . and_then ( |n| u64:: try_from ( n) . ok ( ) )
31
30
. map ( |nanoseconds| Instant { kind : InstantKind :: Virtual { nanoseconds } } ) ,
32
31
}
33
32
}
@@ -39,7 +38,19 @@ impl Instant {
39
38
(
40
39
InstantKind :: Virtual { nanoseconds } ,
41
40
InstantKind :: Virtual { nanoseconds : earlier } ,
42
- ) => Duration :: from_nanos ( nanoseconds. saturating_sub ( earlier) ) ,
41
+ ) => {
42
+ // Trade some nanosecond precision to prevent as much overflow as possible.
43
+ let duration = match u64:: try_from (
44
+ // Manually convert from nanosecond to millisecond.
45
+ // If it exceeded u64::MAX millisecond, we will just use u64::MAX millisecond,
46
+ // Duration can't take in more than u64::MAX millisecond.
47
+ nanoseconds. saturating_sub ( earlier) . saturating_div ( 1_000_000 ) ,
48
+ ) {
49
+ Ok ( millisecond) => Duration :: from_millis ( millisecond) ,
50
+ _ => Duration :: from_millis ( u64:: MAX ) ,
51
+ } ;
52
+ Duration :: new ( duration. as_secs ( ) , duration. subsec_nanos ( ) )
53
+ }
43
54
_ => panic ! ( "all `Instant` must be of the same kind" ) ,
44
55
}
45
56
}
@@ -59,7 +70,7 @@ enum ClockKind {
59
70
} ,
60
71
Virtual {
61
72
/// The "current virtual time".
62
- nanoseconds : Cell < u64 > ,
73
+ nanoseconds : Cell < u128 > ,
63
74
} ,
64
75
}
65
76
@@ -93,7 +104,7 @@ impl Clock {
93
104
ClockKind :: Host { .. } => std:: thread:: sleep ( duration) ,
94
105
ClockKind :: Virtual { nanoseconds } => {
95
106
// Just pretend that we have slept for some time.
96
- let nanos: u64 = duration. as_nanos ( ) . try_into ( ) . unwrap ( ) ;
107
+ let nanos: u128 = duration. as_nanos ( ) . try_into ( ) . unwrap ( ) ;
97
108
nanoseconds. update ( |x| x + nanos) ;
98
109
}
99
110
}
0 commit comments