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
use serde::de::{self, Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use types::{Appearance, PropertyValue};
use properties::parse::filter_parse;

impl_union_into_appearance!(Filters);

pub type Filters = Vec<Filter>;

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Filter {
    Brightness(f32),
    Grayscale(f32),
    HueRotate(f32),
    Saturate(f32),
    Contrast(f32),
    Invert(f32),
    Sepia(f32),
    Blur(f32),
    None,
}

impl Serialize for Filter {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(String::from(*self).as_str())
    }
}

impl<'de> Deserialize<'de> for Filter {
    fn deserialize<D>(deserializer: D) -> Result<Filter, D::Error>
    where
        D: Deserializer<'de>,
    {
        String::deserialize(deserializer).map_err(de::Error::custom).and_then(|filter| Ok(Filter::from(filter)))
    }
}

impl From<String> for Filter {
    fn from(source: String) -> Filter {
        filter_parse(source.as_bytes()).and_then(|parsed| Ok(Filter::from(parsed.1))).unwrap_or(Filter::None)
    }
}

impl From<Filter> for String {
    fn from(source: Filter) -> String {
        use self::Filter::*;
        match source {
            Brightness(v) => format!("brightness({})", v as u32),
            Grayscale(v) => format!("grayscale({})", v as u32),
            HueRotate(v) => format!("hueRotate({})", v as u32),
            Saturate(v) => format!("saturate({})", v as u32),
            Contrast(v) => format!("contrast({})", v as u32),
            Invert(v) => format!("invert({})", v as u32),
            Sepia(v) => format!("sepia({})", v as u32),
            Blur(v) => format!("blur({})", v as u32),
            None => "none".to_string(),
        }
    }
}