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
// Copyright (c) 2016-2017 <daggerbot@gmail.com>
// This software is available under the terms of the zlib license.
// See COPYING.md for more information.

use std::ops::Sub;

use numeric::Clamp;

use lum::{Lum, LumAlpha};
use rgb::{Rgb, Rgba};

/// Inverts a color.
pub trait Invert : Sized {
    type Output : Sized;
    fn invert (self) -> Self::Output;
}

impl<'a, T: 'a + Clone + Sized + Invert> Invert for &'a T {
    type Output = T::Output;
    fn invert (self) -> T::Output { self.clone().invert() }
}

impl<T: Clamp + Sub<Output = T>> Invert for Lum<T> {
    type Output = Lum<T>;
    fn invert (self) -> Lum<T> { Lum(T::clamp_max() - self.0) }
}

impl<T: Clamp + Sub<Output = T>> Invert for Option<Lum<T>> {
    type Output = Option<Lum<T>>;
    fn invert (self) -> Option<Lum<T>> { self.map(Lum::invert) }
}

impl<T: Clamp + Sub<Output = T>> Invert for LumAlpha<T> {
    type Output = LumAlpha<T>;
    fn invert (self) -> LumAlpha<T> { LumAlpha(T::clamp_max() - self.0, self.1) }
}

impl<T: Clamp + Sub<Output = T>> Invert for Rgb<T> {
    type Output = Rgb<T>;

    fn invert (self) -> Rgb<T> {
        Rgb(T::clamp_max() - self.0, T::clamp_max() - self.1, T::clamp_max() - self.2)
    }
}

impl<T: Clamp + Sub<Output = T>> Invert for Option<Rgb<T>> {
    type Output = Option<Rgb<T>>;
    fn invert (self) -> Option<Rgb<T>> { self.map(Rgb::invert) }
}

impl<T: Clamp + Sub<Output = T>> Invert for Rgba<T> {
    type Output = Rgba<T>;

    fn invert (self) -> Rgba<T> {
        Rgba(T::clamp_max() - self.0, T::clamp_max() - self.1, T::clamp_max() - self.2, self.3)
    }
}

/// Inverts a color.
pub fn invert<T: Invert> (color: T) -> T::Output { color.invert() }