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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use numpy::{Element, PyArray1};
use pyo3::types::PyDict;
use pyo3::{FromPyObject, PyAny, PyResult};

pub enum Vectorized<'lt, T: Copy + Clone> {
    Slice(&'lt [T]),
    Scalar(T),
}

impl<'lt, T: Copy + Clone> Vectorized<'lt, T> {
    #[inline]
    pub unsafe fn get_unchecked(&self, index: usize) -> T {
        match self {
            Self::Scalar(res) => *res,
            Self::Slice(values) => *values.get_unchecked(index),
        }
    }
}

impl<'lt, T: Copy + Clone + Element + FromPyObject<'lt> + 'lt> Vectorized<'lt, T> {
    #[inline]
    pub fn from_python(from: &'lt PyAny, name: &str, iterations: &mut usize) -> PyResult<Self> {
        let res = if let Ok(val) = from.extract() {
            Vectorized::Scalar(val)
        } else if let Ok(values) = from.extract::<&PyArray1<T>>() {
            // Save because we only keep the slice as a temporary variable
            // The slice can not be mutated from rust and python doesn't run until the immutable view is dropped
            // As such this does not cause UB here
            match unsafe{values.as_slice()}.unwrap() {
                [val] => Vectorized::Scalar(*val),
                values if values.len() == *iterations => Vectorized::Slice(values),
                values if *iterations == 1 => {
                    *iterations = values.len();
                    Vectorized::Slice(values)
                },
                values => return Err(pyo3::exceptions::PyTypeError::new_err(
                    format!(
                        "Arguments must have the same length or be scalars but '{}' has length {} while previous arguments had length {}",
                        name,
                        values.len(),
                        *iterations
                    )
                )),
            }
        } else {
            return Err(pyo3::exceptions::PyTypeError::new_err(format!(
                "eval: Expected scalar {} value or 1d numpy {}-array for argument{}",
                std::any::type_name::<T>(),
                std::any::type_name::<T>(),
                name,
            )));
        };
        Ok(res)
    }

    #[inline]
    pub fn from_dict(
        dict: &'lt Option<PyDict>,
        name: &str,
        loc: &str,
        iterations: &mut usize,
    ) -> PyResult<Self> {
        if let Some(dict) = dict {
            if let Some(val) = dict.get_item(name) {
                return Vectorized::from_python(val, name, iterations);
            }
        }
        Err(pyo3::exceptions::PyTypeError::new_err(format!(
            "eval: Required argument '{}' is missing from {}",
            name, loc
        )))
    }
}

impl<'lt> Vectorized<'lt, f64> {
    #[inline]
    pub fn from_dict_opt(
        dict: &'lt Option<PyDict>,
        name: &str,
        iterations: &mut usize,
    ) -> PyResult<Self> {
        if let Some(dict) = dict {
            if let Some(val) = dict.get_item(name) {
                return Vectorized::from_python(val, name, iterations);
            }
        }
        Ok(Self::Scalar(0.0))
    }
}