animate/path/
angle.rs

1use std::str::FromStr;
2
3use super::{Error, FuzzyEq, Result, Stream, WriteBuffer, WriteOptions};
4
5/// List of all SVG angle units.
6#[derive(Clone, Copy, Debug, PartialEq)]
7#[allow(missing_docs)]
8pub enum AngleUnit {
9    Degrees,
10    Gradians,
11    Radians,
12}
13
14/// Representation of the [`<angle>`] type.
15///
16/// [`<angle>`]: https://www.w3.org/TR/SVG11/types.html#DataTypeAngle
17#[derive(Clone, Copy, Debug, PartialEq)]
18#[allow(missing_docs)]
19pub struct Angle {
20    pub num: f64,
21    pub unit: AngleUnit,
22}
23
24impl Angle {
25    /// Constructs a new angle.
26    #[inline]
27    pub fn new(num: f64, unit: AngleUnit) -> Angle {
28        Angle { num, unit }
29    }
30}
31
32impl FromStr for Angle {
33    type Err = Error;
34
35    #[inline]
36    fn from_str(text: &str) -> Result<Self> {
37        let mut s = Stream::from(text);
38        let l = s.parse_angle()?;
39
40        if !s.at_end() {
41            return Err(Error::UnexpectedData(s.calc_char_pos()));
42        }
43
44        Ok(Angle::new(l.num, l.unit))
45    }
46}
47
48impl WriteBuffer for Angle {
49    fn write_buf_opt(&self, opt: &WriteOptions, buf: &mut Vec<u8>) {
50        self.num.write_buf_opt(opt, buf);
51
52        let t: &[u8] = match self.unit {
53            AngleUnit::Degrees => b"deg",
54            AngleUnit::Gradians => b"grad",
55            AngleUnit::Radians => b"rad",
56        };
57
58        buf.extend_from_slice(t);
59    }
60}
61
62impl ::std::fmt::Display for Angle {
63    #[inline]
64    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
65        write!(f, "{}", self.with_write_opt(&WriteOptions::default()))
66    }
67}
68
69impl FuzzyEq for Angle {
70    fn fuzzy_eq(&self, other: &Self) -> bool {
71        if self.unit != other.unit {
72            return false;
73        }
74
75        self.num.fuzzy_eq(&other.num)
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use std::str::FromStr;
83
84    macro_rules! test_p {
85        ($name:ident, $text:expr, $result:expr) => {
86            #[test]
87            fn $name() {
88                assert_eq!(Angle::from_str($text).unwrap(), $result);
89            }
90        };
91    }
92
93    test_p!(parse_1, "1", Angle::new(1.0, AngleUnit::Degrees));
94    test_p!(parse_2, "1deg", Angle::new(1.0, AngleUnit::Degrees));
95    test_p!(parse_3, "1grad", Angle::new(1.0, AngleUnit::Gradians));
96    test_p!(parse_4, "1rad", Angle::new(1.0, AngleUnit::Radians));
97
98    #[test]
99    fn err_1() {
100        let mut s = Stream::from("1q");
101        assert_eq!(
102            s.parse_angle().unwrap(),
103            Angle::new(1.0, AngleUnit::Degrees)
104        );
105        assert_eq!(
106            s.parse_angle().unwrap_err().to_string(),
107            "invalid number at position 2"
108        );
109    }
110
111    #[test]
112    fn err_2() {
113        assert_eq!(
114            Angle::from_str("1degq").unwrap_err().to_string(),
115            "unexpected data at position 5"
116        );
117    }
118
119    macro_rules! test_w {
120        ($name:ident, $len:expr, $unit:expr, $result:expr) => {
121            #[test]
122            fn $name() {
123                let l = Angle::new($len, $unit);
124                assert_eq!(l.to_string(), $result);
125            }
126        };
127    }
128
129    test_w!(write_1, 1.0, AngleUnit::Degrees, "1deg");
130    test_w!(write_2, 1.0, AngleUnit::Gradians, "1grad");
131    test_w!(write_3, 1.0, AngleUnit::Radians, "1rad");
132}