Skip to main content

rustpython_vm/function/
time.rs

1use crate::{PyObjectRef, PyResult, TryFromObject, VirtualMachine};
2
3/// A Python timeout value that accepts both `float` and `int`.
4///
5/// `TimeoutSeconds` implements `FromArgs` so that a built-in function can accept
6/// timeout parameters given as either `float` or `int`, normalizing them to `f64`.
7#[derive(Debug, Clone, Copy, PartialEq)]
8pub struct TimeoutSeconds {
9    value: f64,
10}
11
12impl TimeoutSeconds {
13    #[must_use]
14    pub const fn new(secs: f64) -> Self {
15        Self { value: secs }
16    }
17
18    #[inline]
19    #[must_use]
20    pub fn to_secs_f64(self) -> f64 {
21        self.value
22    }
23
24    #[must_use]
25    pub const fn py_default(&self) -> super::DefaultRepr {
26        super::DefaultRepr::Float(self.value)
27    }
28}
29
30impl TryFromObject for TimeoutSeconds {
31    fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
32        let value = match super::Either::<f64, i64>::try_from_object(vm, obj)? {
33            super::Either::A(f) => f,
34            super::Either::B(i) => i as f64,
35        };
36        if value.is_nan() {
37            return Err(vm.new_value_error("Invalid value NaN (not a number)"));
38        }
39        Ok(Self { value })
40    }
41}