easy_complex/
convert.rs

1//! Conversion macros
2
3/// This macro performs a conversion from any type that can cast
4/// into a float (either `f32` or `f64`) and transforms it into a
5/// Either `Complex` or `EComplex`
6/// 
7/// If a type `T` is given, it is treated as a `real` only value.
8/// If the type `(T, T)` is given, it maps the struct's fields directly to it
9#[macro_export]
10macro_rules! convert {
11	([ $($other:ty),+ ], $float:ty, $ctype:ident) => {
12		$(
13			impl From<$other> for $ctype<$float> {
14				fn from(other: $other) -> Self {
15					Self::new(other.into(), Default::default())
16				}
17			}
18
19			impl From<($other, $other)> for $ctype<$float> {
20				fn from(other: ($other, $other)) -> Self {
21					Self::new(other.0.into(), other.0.into())
22				}
23			}
24		)+
25	};
26}
27
28macro_rules! dual_convert {
29	($c1:ident, $c2:ident) => (
30		dc_inner!(f32, f32, $c1, $c2);
31		dc_inner!(f32, f64, $c1, $c2);
32		dc_inner!(f64, f64, $c1, $c2);
33
34		dc_inner!(f32, f32, $c2, $c1);
35		dc_inner!(f32, f64, $c2, $c1);
36		dc_inner!(f64, f64, $c2, $c1);
37	);
38}
39
40macro_rules! dc_inner {
41	($t1:ty, $t2:ty, Complex, EComplex) => (
42		impl From<Complex<$t1>> for EComplex<$t2> {
43			fn from(other: Complex<$t1>) -> EComplex<$t2> {
44				EComplex {
45					module: other.module().into(),
46					arg: match other.arg() {
47						Angle::Radian(a) => a.into(),
48						_ => unreachable!(),
49					},
50				}
51			}
52		}
53
54		impl<'a> From<&'a Complex<$t1>> for EComplex<$t2> {
55			fn from(other: &'a Complex<$t1>) -> EComplex<$t2> {
56				EComplex {
57					module: other.module().into(),
58					arg: match other.arg() {
59						Angle::Radian(a) => a.into(),
60						_ => unreachable!(),
61					},
62				}
63			}
64		}
65	);
66
67	($t1:ty, $t2:ty, EComplex, Complex) => (
68		impl From<EComplex<$t1>> for Complex<$t2> {
69			fn from(other: EComplex<$t1>) -> Complex<$t2> {
70				Complex {
71					real: other.real().into(),
72					imag: other.imag().into(),
73				}
74			}
75		}
76
77		impl<'a> From<&'a EComplex<$t1>> for Complex<$t2> {
78			fn from(other: &'a EComplex<$t1>) -> Complex<$t2> {
79				Complex {
80					real: other.real().into(),
81					imag: other.imag().into(),
82				}
83			}
84		}
85	);
86}