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
90
91
92
93
94
95
96
97
98
99
100
101
use core::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};
pub type Scaler = f32;

#[derive(Debug, Clone, Copy)]
pub struct Complex {
    pub r: Scaler,
    pub i: Scaler,
}

impl Complex {
    pub fn new(r: Scaler, i: Scaler) -> Self {
        Self { r, i }
    }
}

impl Mul for Complex {
    type Output = Complex;
    fn mul(self, rhs: Complex) -> Self::Output {
        Complex {
            r: self.r * rhs.r - self.i * rhs.i,
            i: self.r * rhs.i + self.i * rhs.r,
        }
    }
}

impl Add for Complex {
    type Output = Complex;
    fn add(self, rhs: Self) -> Self::Output {
        Complex {
            r: self.r + rhs.r,
            i: self.i + rhs.i,
        }
    }
}

impl Sub for Complex {
    type Output = Complex;
    fn sub(self, rhs: Self) -> Self::Output {
        Complex {
            r: self.r - rhs.r,
            i: self.i - rhs.i,
        }
    }
}

impl MulAssign<Scaler> for Complex {
    fn mul_assign(&mut self, rhs: Scaler) {
        self.r *= rhs;
        self.i *= rhs;
    }
}

impl AddAssign<Complex> for Complex {
    fn add_assign(&mut self, rhs: Complex) {
        self.r += rhs.r;
        self.i += rhs.i;
    }
}
impl SubAssign<Complex> for Complex {
    fn sub_assign(&mut self, rhs: Complex) {
        self.r -= rhs.r;
        self.i -= rhs.i;
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;

    #[test]
    fn complex_arithmatic() {
        let mut complex = Complex::new(2.0, 3.0);

        // complex addition
        complex += Complex::new(1., 2.);
        assert_eq!(complex.r, 3.0);
        assert_eq!(complex.i, 5.0);
        complex = complex + Complex::new(1., 2.);
        assert_eq!(complex.r, 4.0);
        assert_eq!(complex.i, 7.0);

        // complex subtraction
        complex -= Complex::new(9.0, 15.0);
        assert_eq!(complex.r, -5.0);
        assert_eq!(complex.i, -8.0);
        complex = complex - Complex::new(9.0, 15.0);
        assert_eq!(complex.r, -14.0);
        assert_eq!(complex.i, -23.0);

        // complex multiplication
        complex = complex * Complex::new(2.0, 4.0);
        assert_eq!(complex.r, 64.0);
        assert_eq!(complex.i, -102.0);

        // scalar multiplication
        complex *= 2.0;
        assert_eq!(complex.r, 128.0);
        assert_eq!(complex.i, -204.0);
    }
}