Skip to content

Commit b7c41a7

Browse files
committed
Use Duration::{from_secs_f64,as_secs_f64}
1 parent ccb263d commit b7c41a7

File tree

1 file changed

+9
-22
lines changed

1 file changed

+9
-22
lines changed

vm/src/stdlib/time_module.rs

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,11 @@ use crate::vm::VirtualMachine;
2020
#[cfg(unix)]
2121
fn time_sleep(seconds: f64, vm: &VirtualMachine) -> PyResult<()> {
2222
// this is basically std::thread::sleep, but that catches interrupts and we don't want to
23-
let secs = seconds.trunc() as u64;
24-
let nsecs = (seconds.fract() * 1e9) as i64;
23+
let dur = Duration::from_secs_f64(seconds);
2524

2625
let mut ts = libc::timespec {
27-
tv_sec: std::cmp::min(libc::time_t::max_value() as u64, secs) as libc::time_t,
28-
tv_nsec: nsecs,
26+
tv_sec: std::cmp::min(libc::time_t::max_value() as u64, dur.as_secs()) as libc::time_t,
27+
tv_nsec: dur.subsec_nanos() as i64,
2928
};
3029
let res = unsafe { libc::nanosleep(&ts, &mut ts) };
3130
let interrupted = res == -1 && nix::errno::errno() == libc::EINTR;
@@ -39,20 +38,13 @@ fn time_sleep(seconds: f64, vm: &VirtualMachine) -> PyResult<()> {
3938

4039
#[cfg(not(unix))]
4140
fn time_sleep(seconds: f64, _vm: &VirtualMachine) {
42-
let secs: u64 = seconds.trunc() as u64;
43-
let nanos: u32 = (seconds.fract() * 1e9) as u32;
44-
let duration = Duration::new(secs, nanos);
45-
std::thread::sleep(duration);
46-
}
47-
48-
fn duration_to_f64(d: Duration) -> f64 {
49-
(d.as_secs() as f64) + (f64::from(d.subsec_nanos()) / 1e9)
41+
std::thread::sleep(Duration::from_secs_f64(seconds));
5042
}
5143

5244
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
5345
pub fn get_time() -> f64 {
5446
match SystemTime::now().duration_since(UNIX_EPOCH) {
55-
Ok(v) => duration_to_f64(v),
47+
Ok(v) => v.as_secs_f64(),
5648
Err(err) => panic!("Time error: {:?}", err),
5749
}
5850
}
@@ -77,22 +69,17 @@ fn time_time(_vm: &VirtualMachine) -> f64 {
7769
fn time_monotonic(_vm: &VirtualMachine) -> f64 {
7870
// TODO: implement proper monotonic time!
7971
match SystemTime::now().duration_since(UNIX_EPOCH) {
80-
Ok(v) => duration_to_f64(v),
72+
Ok(v) => v.as_secs_f64(),
8173
Err(err) => panic!("Time error: {:?}", err),
8274
}
8375
}
8476

85-
fn pyfloat_to_secs_and_nanos(seconds: f64) -> (i64, u32) {
86-
let secs: i64 = seconds.trunc() as i64;
87-
let nanos: u32 = (seconds.fract() * 1e9) as u32;
88-
(secs, nanos)
89-
}
90-
9177
fn pyobj_to_naive_date_time(value: Either<f64, i64>) -> NaiveDateTime {
9278
match value {
9379
Either::A(float) => {
94-
let (seconds, nanos) = pyfloat_to_secs_and_nanos(float);
95-
NaiveDateTime::from_timestamp(seconds, nanos)
80+
let secs = float.trunc() as i64;
81+
let nsecs = (float.fract() * 1e9) as u32;
82+
NaiveDateTime::from_timestamp(secs, nsecs)
9683
}
9784
Either::B(int) => NaiveDateTime::from_timestamp(int, 0),
9885
}

0 commit comments

Comments
 (0)