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
use std::ops::*;
use std::iter::FromIterator;
use super::pixel::*;
use super::rgb::RGB;
use super::rgba::RGBA;

impl<T: Clone + Add> Add for RGB<T>
    where RGB<T>: FromIterator<<T as Add>::Output> {
    type Output = RGB<T>;
    fn add(self, other: RGB<T>) -> Self::Output {
        self.iter().zip(other.iter()).map(|(l,r)| l+r).collect()
    }
}

impl<T: Clone + Add> Add<RGBA<T>> for RGBA<T>
    where RGBA<T>: FromIterator<<T as Add>::Output>,
        T: From<<T as Add>::Output> {
    type Output = RGBA<T>;
    fn add(self, other: RGBA<T>) -> Self::Output {
        self.iter().zip(other.iter()).map(|(l,r)| l+r).collect()
    }
}

impl<T: Clone + Sub> Sub for RGB<T>
    where RGB<T>: FromIterator<<T as Sub>::Output> {
    type Output = RGB<T>;
    fn sub(self, other: RGB<T>) -> Self::Output {
        self.iter().zip(other.iter()).map(|(l,r)| l-r).collect()
    }
}

impl<T: Clone + Sub> Sub<RGBA<T>> for RGBA<T>
    where RGBA<T>: FromIterator<<T as Sub>::Output>,
        T: From<<T as Sub>::Output> {
    type Output = RGBA<T>;
    fn sub(self, other: RGBA<T>) -> Self::Output {
        self.iter().zip(other.iter()).map(|(l,r)| l-r).collect()
    }
}

impl<T: Clone + Copy + Add> Add<T> for RGB<T>
    where T: Add<Output=T> {
    type Output = RGB<T>;
    fn add(self, r: T) -> Self::Output {
        self.map(|l|l+r)
    }
}

impl<T: Clone + Copy + Add> Add<T> for RGBA<T>
    where T: Add<Output=T> {
    type Output = RGBA<T>;
    fn add(self, r: T) -> Self::Output {
        self.map(|l|l+r)
    }
}

impl<T: Clone + Copy + Mul> Mul<T> for RGB<T>
    where T: Mul<Output=T> {
    type Output = RGB<T>;
    fn mul(self, r: T) -> Self::Output {
        self.map(|l|l*r)
    }
}

impl<T: Clone + Copy + Mul> Mul<T> for RGBA<T>
    where T: Mul<Output=T> {
    type Output = RGBA<T>;
    fn mul(self, r: T) -> Self::Output {
        self.map(|l|l*r)
    }
}

#[test]
fn test_math() {
    assert_eq!(RGB::new(2,4,6), RGB::new(1,2,3) + RGB{r:1,g:2,b:3});
    assert_eq!(RGB::new(2.,4.,6.), RGB::new(1.,3.,5.) + 1.);
    assert_eq!(RGB::new(0.5,1.5,2.5), RGB::new(1.,3.,5.) * 0.5);

    assert_eq!(RGBA::new(2,4,6,8), RGBA::new(1,2,3,4) + RGBA{r:1,g:2,b:3,a:4});
    assert_eq!(RGBA::new(2i16,4,6,8), RGBA::new(1,3,5,7) + 1);
    assert_eq!(RGBA::new(2,4,6,8), RGBA::new(1,2,3,4) * 2);
}