concision_utils/traits/
complex.rs

1/*
2   Appellation: num <traits>
3   Contrib: FL03 <jo3mccain@icloud.com>
4*/
5#![cfg(feature = "complex")]
6use num::Num;
7use num::complex::Complex;
8pub trait AsComplex<T> {
9    type Complex<A>;
10
11    fn as_complex(&self, real: bool) -> Self::Complex<T>;
12
13    fn as_re(&self) -> Self::Complex<T> {
14        self.as_complex(true)
15    }
16
17    fn as_im(&self) -> Self::Complex<T> {
18        self.as_complex(false)
19    }
20}
21/// Trait for converting a type into a complex number.
22pub trait IntoComplex<T> {
23    type Complex<A>;
24
25    fn into_complex(self, real: bool) -> Self::Complex<T>
26    where
27        Self: Sized;
28
29    fn into_re(self) -> Self::Complex<T>
30    where
31        Self: Sized,
32    {
33        self.into_complex(true)
34    }
35
36    fn into_im(self) -> Self::Complex<T>
37    where
38        Self: Sized,
39    {
40        self.into_complex(false)
41    }
42}
43
44/*
45 ********* Implementations *********
46*/
47
48impl<T> AsComplex<T> for T
49where
50    T: Clone + Num,
51{
52    type Complex<A> = Complex<A>;
53
54    fn as_complex(&self, real: bool) -> Complex<T> {
55        match real {
56            true => Complex::new(self.clone(), Self::zero()),
57            false => Complex::new(Self::zero(), self.clone()),
58        }
59    }
60}
61
62impl<T> IntoComplex<T> for T
63where
64    T: Num,
65{
66    type Complex<A> = Complex<A>;
67
68    fn into_complex(self, real: bool) -> Self::Complex<T>
69    where
70        Self: Sized,
71    {
72        match real {
73            true => Complex::new(self, T::zero()),
74            false => Complex::new(T::zero(), self),
75        }
76    }
77}