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
99
100
101
102
103
104
105
use serde_tuple::{Deserialize_tuple, Serialize_tuple};
use std::fmt::{Display, Formatter};
use std::num::{ParseFloatError, ParseIntError};
use std::str::FromStr;
#[derive(Serialize_tuple, Deserialize_tuple, PartialEq, Debug, Default, Copy, Clone)]
pub struct Center {
pub longitude: f64,
pub latitude: f64,
pub zoom: u8,
}
impl Center {
pub fn new(longitude: f64, latitude: f64, zoom: u8) -> Self {
Self {
longitude,
latitude,
zoom,
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ParseCenterError {
BadLen,
ParseCoordError(ParseFloatError),
ParseZoomError(ParseIntError),
}
impl Display for ParseCenterError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ParseCenterError::BadLen => {
f.write_str("Incorrect number of values. Center expects two f64 and one u8 values.")
}
ParseCenterError::ParseCoordError(e) => e.fmt(f),
ParseCenterError::ParseZoomError(e) => e.fmt(f),
}
}
}
impl FromStr for Center {
type Err = ParseCenterError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut vals = s.split(',').map(|s| s.trim());
let mut next_val = || vals.next().ok_or(ParseCenterError::BadLen);
let center = Self {
longitude: next_val()?
.parse()
.map_err(ParseCenterError::ParseCoordError)?,
latitude: next_val()?
.parse()
.map_err(ParseCenterError::ParseCoordError)?,
zoom: next_val()?
.parse()
.map_err(ParseCenterError::ParseZoomError)?,
};
match vals.next() {
Some(_) => Err(ParseCenterError::BadLen),
None => Ok(center),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_err() {
const E_EMPTY: &str = "cannot parse float from empty string";
const E_FORMAT: &str = "invalid digit found in string";
const E_LEN: &str = "Incorrect number of values. Center expects two f64 and one u8 values.";
let err_to_str = |s| Center::from_str(s).unwrap_err().to_string();
assert_eq!(err_to_str(""), E_EMPTY);
assert_eq!(err_to_str("1"), E_LEN);
assert_eq!(err_to_str("1,2"), E_LEN);
assert_eq!(err_to_str("1,2,3,4"), E_LEN);
assert_eq!(err_to_str("1,2,a"), E_FORMAT);
assert_eq!(err_to_str("1,2,1.1"), E_FORMAT);
assert_eq!(err_to_str("1,,0"), E_EMPTY);
}
#[test]
fn test_parse() {
let val = |s| Center::from_str(s).unwrap();
assert_eq!(val("0,0,0"), Center::new(0.0, 0.0, 0));
assert_eq!(val(" 1 ,2.0, 3 "), Center::new(1.0, 2.0, 3));
}
}