colorparser_css/
color.rs

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
use std::fmt;

use crate::{Error, ErrorKind, Result as ColorResult, Solid, gradient::Gradient, parse};

#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum ColorValue {
    Solid(Solid),
    Gradient(Gradient),
}

#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct Color(pub ColorValue);

impl Color {
    /// Create color from CSS color string.
    pub fn from_html<S: AsRef<str>>(s: S) -> ColorResult<Self> {
        Self::try_from(s.as_ref())
    }

    /// Convert a `Color` to a `Gradient`.
    pub fn to_gradient(&self) -> ColorResult<Gradient> {
        match self.0.clone() {
            ColorValue::Gradient(grad) => Ok(grad),
            _ => Err(Error::new(ErrorKind::InvalidFunction, self.to_string())),
        }
    }

    /// Convert a `Color` to a `Solid`.
    pub fn to_solid(&self) -> ColorResult<Solid> {
        match self.0.clone() {
            ColorValue::Solid(solid) => Ok(solid),
            _ => Err(Error::new(ErrorKind::InvalidFunction, self.to_string())),
        }
    }
}

impl TryFrom<Gradient> for Color {
    type Error = Error;

    fn try_from(gradient: Gradient) -> Result<Self, Self::Error> {
        Ok(Color(ColorValue::Gradient(gradient)))
    }
}

impl TryFrom<Solid> for Color {
    type Error = Error;

    fn try_from(solid: Solid) -> Result<Self, Self::Error> {
        Ok(Color(ColorValue::Solid(solid)))
    }
}

impl TryFrom<&str> for Color {
    type Error = Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        parse(s)
    }
}

impl fmt::Display for ColorValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ColorValue::Solid(solid) => write!(f, "{}", solid),
            ColorValue::Gradient(gradient) => write!(f, "{}", gradient),
        }
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Color({})", self.0)
    }
}