concision_traits/
complex.rs

1/*
2   Appellation: num <traits>
3   Contrib: FL03 <jo3mccain@icloud.com>
4*/
5
6/// [`AsComplex`] defines an interface for converting a reference of some numerical type into a
7/// complex number.
8pub trait AsComplex<T> {
9    type Complex<A>;
10    /// converts the current state into a complex number as either the real or imaginary part,
11    /// depending on the `real` flag
12    fn as_complex(&self, real: bool) -> Self::Complex<T>;
13    /// convert a reference of the current state into the real part of a complex number
14    fn as_re(&self) -> Self::Complex<T> {
15        self.as_complex(true)
16    }
17    /// convert a reference of the current state into the imaginary part of a complex number
18    fn as_im(&self) -> Self::Complex<T> {
19        self.as_complex(false)
20    }
21}
22/// Trait for converting a type into a complex number.
23pub trait IntoComplex<T> {
24    type Complex<A>;
25    /// converts the current state into a complex number used either as the real or imaginary
26    /// part, depending on the `real` flag
27    fn into_complex(self, real: bool) -> Self::Complex<T>
28    where
29        Self: Sized;
30    /// uses the current state as the real value of a complex number
31    fn into_re(self) -> Self::Complex<T>
32    where
33        Self: Sized,
34    {
35        self.into_complex(true)
36    }
37    /// uses the current state as the imaginary value of a complex number
38    fn into_im(self) -> Self::Complex<T>
39    where
40        Self: Sized,
41    {
42        self.into_complex(false)
43    }
44}
45
46/*
47 ********* Implementations *********
48*/
49#[cfg(feature = "complex")]
50mod impl_complex {
51    use super::{AsComplex, IntoComplex};
52
53    use num_complex::Complex;
54    use num_traits::Zero;
55
56    impl<T> AsComplex<T> for T
57    where
58        T: Clone + IntoComplex<T>,
59    {
60        type Complex<A> = <T as IntoComplex<T>>::Complex<A>;
61
62        fn as_complex(&self, real: bool) -> Self::Complex<T> {
63            self.clone().into_complex(real)
64        }
65    }
66
67    impl<T> IntoComplex<T> for T
68    where
69        T: Zero,
70    {
71        type Complex<A> = Complex<A>;
72
73        fn into_complex(self, real: bool) -> Self::Complex<T>
74        where
75            Self: Sized,
76        {
77            if real {
78                Complex::new(self, T::zero())
79            } else {
80                Complex::new(T::zero(), self)
81            }
82        }
83    }
84}