rigetti_pyo3/py_try_from/
complex.rs

1// Copyright 2022 Rigetti Computing
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Display;
16use std::os::raw::c_double;
17
18use num_complex::Complex;
19use num_traits::{Float, FloatConst};
20use pyo3::{exceptions::PyFloatingPointError, types::PyComplex, IntoPy, Py, PyResult, Python};
21
22use crate::py_try_from::{impl_try_from_self_python, PyAny, PyTryFrom};
23
24impl_try_from_self_python!(PyComplex);
25
26impl<F> PyTryFrom<Self> for Complex<F>
27where
28    F: Copy + Float + FloatConst + Into<c_double> + Display,
29{
30    fn py_try_from(_py: Python, item: &Self) -> PyResult<Self> {
31        Ok(*item)
32    }
33}
34
35impl<F> PyTryFrom<Py<PyComplex>> for Complex<F>
36where
37    F: Copy + Float + FloatConst + Into<c_double> + Display,
38{
39    fn py_try_from(py: Python, item: &Py<PyComplex>) -> PyResult<Self> {
40        Self::py_try_from(py, item.as_ref(py))
41    }
42}
43
44impl<F> PyTryFrom<PyComplex> for Complex<F>
45where
46    // `Display` seems like an odd trait to require, but it is used to make a more useful
47    // error message. The types realistically used for this are `f32` and `f64` both of which
48    // impl `Display`, so there's no issue there.
49    F: Copy + Float + FloatConst + Into<c_double> + Display,
50{
51    fn py_try_from(_py: Python, item: &PyComplex) -> PyResult<Self> {
52        let make_error = |val: c_double| {
53            PyFloatingPointError::new_err(format!(
54                "expected {val} to be between {} and {}, inclusive",
55                F::min_value(),
56                F::max_value(),
57            ))
58        };
59        Ok(Self {
60            re: F::from(item.real()).ok_or_else(|| make_error(item.real()))?,
61            im: F::from(item.imag()).ok_or_else(|| make_error(item.imag()))?,
62        })
63    }
64}
65
66impl<F> PyTryFrom<PyAny> for Complex<F>
67where
68    F: Copy + Float + FloatConst + Into<c_double> + Display,
69{
70    fn py_try_from(py: Python, item: &PyAny) -> PyResult<Self> {
71        let dict: &PyComplex = item.downcast()?;
72        Self::py_try_from(py, dict)
73    }
74}