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
102
103
104
105
106
107
108
109
use std::ops::*;
use super::pixel::*;
use ::RGB;
use ::RGBA;

impl<T: Add> Add for RGB<T> {
    type Output = RGB<<T as Add>::Output>;

    #[inline(always)]
    fn add(self, other: RGB<T>) -> Self::Output {
        RGB {
            r: self.r + other.r,
            g: self.g + other.g,
            b: self.b + other.b,
        }
    }
}

impl<T: Add> Add<RGBA<T>> for RGBA<T> {
    type Output = RGBA<<T as Add>::Output>;

    #[inline(always)]
    fn add(self, other: RGBA<T>) -> Self::Output {
        RGBA {
            r: self.r + other.r,
            g: self.g + other.g,
            b: self.b + other.b,
            a: self.a + other.a,
        }
    }
}

impl<T: Sub> Sub for RGB<T> {
    type Output = RGB<<T as Sub>::Output>;

    #[inline(always)]
    fn sub(self, other: RGB<T>) -> Self::Output {
        RGB {
            r: self.r - other.r,
            g: self.g - other.g,
            b: self.b - other.b,
        }
    }
}

impl<T: Sub> Sub<RGBA<T>> for RGBA<T> {
    type Output = RGBA<<T as Sub>::Output>;

    #[inline(always)]
    fn sub(self, other: RGBA<T>) -> Self::Output {
        RGBA {
            r: self.r - other.r,
            g: self.g - other.g,
            b: self.b - other.b,
            a: self.a - other.a,
        }
    }
}

impl<T: Clone + Copy + Add> Add<T> for RGB<T>
    where T: Add<Output=T> {
    type Output = RGB<T>;

    #[inline(always)]
    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>;

    #[inline(always)]
    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>;

    #[inline(always)]
    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>;

    #[inline(always)]
    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);
}