forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime_module.rs
More file actions
40 lines (35 loc) · 1.32 KB
/
time_module.rs
File metadata and controls
40 lines (35 loc) · 1.32 KB
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
//! The python `time` module.
use super::super::obj::{objfloat, objtype};
use super::super::pyobject::{
DictProtocol, PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol,
};
use super::super::VirtualMachine;
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
fn time_sleep(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(seconds, Some(vm.ctx.float_type()))]);
let seconds = objfloat::get_value(seconds);
let secs: u64 = seconds.trunc() as u64;
let nanos: u32 = (seconds.fract() * 1e9) as u32;
let duration = Duration::new(secs, nanos);
thread::sleep(duration);
Ok(vm.get_none())
}
fn duration_to_f64(d: Duration) -> f64 {
(d.as_secs() as f64) + ((d.subsec_nanos() as f64) / 1e9)
}
fn time_time(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args);
let x = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(v) => duration_to_f64(v),
Err(err) => panic!("Error: {:?}", err),
};
let value = vm.ctx.new_float(x);
Ok(value)
}
pub fn mk_module(ctx: &PyContext) -> PyObjectRef {
let py_mod = ctx.new_module(&"time".to_string(), ctx.new_scope(None));
py_mod.set_item("sleep", ctx.new_rustfunc(time_sleep));
py_mod.set_item("time", ctx.new_rustfunc(time_time));
py_mod
}