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    pub const fn new(secs: f64) -> Self {
14        Self { value: secs }
15    }
16
17    #[inline]
18    pub fn to_secs_f64(self) -> f64 {
19        self.value
20    }
21}
22
23impl TryFromObject for TimeoutSeconds {
24    fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
25        let value = match super::Either::<f64, i64>::try_from_object(vm, obj)? {
26            super::Either::A(f) => f,
27            super::Either::B(i) => i as f64,
28        };
29        if value.is_nan() {
30            return Err(vm.new_value_error("Invalid value NaN (not a number)".to_owned()));
31        }
32        Ok(Self { value })
33    }
34}