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
use properties::parse::{self, UnitRepr, AngleRepr, LengthRepr};
use euclid;

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Angle {
    Degrees(f32),
    Radians(f32),
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Length {
    Percent(f32),
    Point(f32),
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum SharedUnit {
    Length(Length),
    Angle(Angle),
    None,
}

impl From<Length> for String {
    fn from(unit: Length) -> String {
        match unit {
            Length::Percent(value) => format!("{}%", value),
            Length::Point(value) => format!("{}px", value),
        }
    }
}

impl<'a, 'b> From<LengthRepr<'a, 'b>> for SharedUnit {
    fn from(u: LengthRepr) -> SharedUnit {
        let value = u.value.parse::<f32>().unwrap_or(0.0);
        match u.unit {
            "percent" => SharedUnit::Length(Length::Percent(value)),
            "point" => SharedUnit::Length(Length::Point(value)),
            _ => SharedUnit::None,
        }
    }
}

impl From<Angle> for String {
    fn from(unit: Angle) -> String {
        use self::Angle::*;

        match unit {
            Degrees(v) => format!("{}deg", v),
            Radians(v) => format!("{}rad", v),
        }
    }
}

impl From<Angle> for euclid::Angle<f32> {
    fn from(angle: Angle) -> euclid::Angle<f32> {
        match angle {
            Angle::Radians(v) => euclid::Angle::radians(v),
            Angle::Degrees(v) => euclid::Angle::degrees(v),
        }
    }
}

impl<'a, 'b> From<AngleRepr<'a, 'b>> for SharedUnit {
    fn from(u: AngleRepr) -> SharedUnit {
        let value = u.value.parse::<f32>().unwrap_or(0.0);
        match u.angle {
            "radians" => SharedUnit::Angle(Angle::Radians(value)),
            "degrees" => SharedUnit::Angle(Angle::Degrees(value)),
            _ => SharedUnit::None,
        }
    }
}

impl<'a, 'b> From<UnitRepr<'a, 'b>> for SharedUnit {
    fn from(u: UnitRepr) -> SharedUnit {
        match u {
            UnitRepr::Length(length) => length.into(),
            UnitRepr::Angle(angle) => angle.into(),
        }
    }
}

impl<'a> From<&'a str> for SharedUnit {
    fn from(s: &str) -> SharedUnit {
        if let Ok(result) = parse::unit(s.as_bytes()) {
            result.1.into()
        } else {
            SharedUnit::None
        }
    }
}

impl From<String> for SharedUnit {
    fn from(s: String) -> SharedUnit {
        let slice = &*s;
        slice.into()
    }
}