1use crate::Stream;
2
3/// A pull-based [`<list-of-points>`] parser.
4///
5/// Use it for the `points` attribute of the `polygon` and `polyline` elements.
6///
7/// # Errors
8///
9/// - Stops on a first invalid character. Follows the same rules as paths parser.
10///
11/// # Notes
12///
13/// - If data contains an odd number of coordinates - the last one will be ignored.
14/// As SVG spec states.
15/// - It doesn't validate that there are more than two coordinate pairs,
16/// which is required by the SVG spec.
17///
18/// # Examples
19///
20/// ```
21/// use svgtypes::PointsParser;
22///
23/// let mut p = PointsParser::from("10 20 30 40");
24/// assert_eq!(p.next(), Some((10.0, 20.0)));
25/// assert_eq!(p.next(), Some((30.0, 40.0)));
26/// assert_eq!(p.next(), None);
27/// ```
28///
29/// [`<list-of-points>`]: https://www.w3.org/TR/SVG11/shapes.html#PointsBNF
30#[derive(Clone, Copy, PartialEq, Eq, Debug)]
31pub struct PointsParser<'a>(Stream<'a>);
32
33impl<'a> From<&'a str> for PointsParser<'a> {
34 #[inline]
35 fn from(v: &'a str) -> Self {
36 PointsParser(Stream::from(v))
37 }
38}
39
40impl<'a> Iterator for PointsParser<'a> {
41 type Item = (f64, f64);
42
43 fn next(&mut self) -> Option<Self::Item> {
44 if self.0.at_end() {
45 None
46 } else {
47 let x: f64 = match self.0.parse_list_number() {
48 Ok(x: f64) => x,
49 Err(_) => return None,
50 };
51
52 let y: f64 = match self.0.parse_list_number() {
53 Ok(y: f64) => y,
54 Err(_) => return None,
55 };
56
57 Some((x, y))
58 }
59 }
60}
61
62#[rustfmt::skip]
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn parse_1() {
69 let mut parser = PointsParser::from("10 20 30 40");
70 assert_eq!(parser.next().unwrap(), (10.0, 20.0));
71 assert_eq!(parser.next().unwrap(), (30.0, 40.0));
72 assert!(parser.next().is_none());
73 }
74
75 #[test]
76 fn parse_2() {
77 let mut parser = PointsParser::from("10 20 30 40 50");
78 assert_eq!(parser.next().unwrap(), (10.0, 20.0));
79 assert_eq!(parser.next().unwrap(), (30.0, 40.0));
80 assert!(parser.next().is_none());
81 }
82}
83