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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use serde::de::{Deserialize, Deserializer, Error, IgnoredAny, MapAccess, SeqAccess, Unexpected, Visitor};
use std::fmt;
#[derive(Clone, Debug, PartialEq)]
pub enum Geometry {
Point(Position),
MultiPoint(Vec<Position>),
LineString(LineString),
MultiLineString(Vec<LineString>),
Polygon(Polygon),
MultiPolygon(Vec<Polygon>),
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Position(
pub f64,
pub f64,
);
pub type LineString = Vec<Position>;
pub type Polygon = Vec<LinearRing>;
pub type LinearRing = LineString;
impl<'x> Deserialize<'x> for Geometry {
fn deserialize<D: Deserializer<'x>>(d: D) -> Result<Self, D::Error> {
struct GeometryVisitor;
impl<'x> Visitor<'x> for GeometryVisitor {
type Value = Geometry;
fn visit_map<V: MapAccess<'x>>(self, mut v: V) -> Result<Geometry, V::Error> {
enum Coordinates {
F64(f64),
Dim0(Position),
Dim1(Vec<Position>),
Dim2(Vec<Vec<Position>>),
Dim3(Vec<Vec<Vec<Position>>>),
}
impl<'x> Deserialize<'x> for Coordinates {
fn deserialize<D: Deserializer<'x>>(d: D) -> Result<Self, D::Error> {
struct CoordinatesVisitor;
impl<'x> Visitor<'x> for CoordinatesVisitor {
type Value = Coordinates;
fn visit_f64<E>(self, v: f64) -> Result<Coordinates, E> {
Ok(Coordinates::F64(v))
}
fn visit_i64<E>(self, v: i64) -> Result<Coordinates, E> {
Ok(Coordinates::F64(v as _))
}
fn visit_u64<E>(self, v: u64) -> Result<Coordinates, E> {
Ok(Coordinates::F64(v as _))
}
fn visit_seq<V: SeqAccess<'x>>(self, mut v: V) -> Result<Coordinates, V::Error> {
macro_rules! match_val {
(
$C:ident,
$($V:ident => $R:ident,)*
) => {
match v.next_element()? {
Some($C::F64(v1)) => {
let v2 = match v.next_element()? {
Some(val) => val,
None => return Err(V::Error::invalid_length(1, &self)),
};
while v.next_element::<IgnoredAny>()?.is_some() {}
Ok($C::Dim0(Position(v1, v2)))
},
$(Some($C::$V(val)) => {
let mut ret = v.size_hint().map_or_else(Vec::new, Vec::with_capacity);
ret.push(val);
while let Some(val) = v.next_element()? {
ret.push(val);
}
Ok($C::$R(ret))
},)*
Some($C::Dim3(_)) => Err(V::Error::invalid_type(Unexpected::Seq, &self)),
None => Ok($C::Dim1(Vec::new())),
}
};
}
match_val! {
Coordinates,
Dim0 => Dim1,
Dim1 => Dim2,
Dim2 => Dim3,
}
}
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"a floating point number \
or an array of floating point number with a depth of 4 or lower"
)
}
}
d.deserialize_seq(CoordinatesVisitor)
}
}
let mut c = None;
use self::Geometry::*;
macro_rules! end {
() => {{
while v.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
}};
}
while let Some(k) = v.next_key::<String>()? {
match k.as_str() {
"type" => {
let t = v.next_value::<String>()?;
macro_rules! match_type {
($C:ident, $($($V:ident($typ:expr))|* => $D:ident,)*) => {{
const EXPECTED: &'static [&'static str] = &[$($($typ),*),*];
match t.as_str() {
$($($typ => match c {
Some($C::$D(val)) => {
end!();
return Ok($V(val));
},
None => {
while let Some(k) = v.next_key::<String>()? {
if "coordinates" == k.as_str() {
end!();
return Ok($V(v.next_value()?));
} else {
v.next_value::<IgnoredAny>()?;
}
}
return Err(V::Error::missing_field("coordinates"));
},
_ => return Err(V::Error::custom("invalid coordinates type")),
},)*)*
s => return Err(V::Error::unknown_variant(&s, EXPECTED)),
}
}};
}
match_type! {
Coordinates,
Point("Point") => Dim0,
MultiPoint("MultiPoint") | LineString("LineString") => Dim1,
MultiLineString("MultiLineString") | Polygon("Polygon") => Dim2,
MultiPolygon("MultiPolygon") => Dim3,
}
},
"coordinates" => c = Some(v.next_value()?),
_ => { v.next_value::<IgnoredAny>()?; },
}
}
Err(V::Error::missing_field("type"))
}
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "a map with `type` and `coordinate` fields")
}
}
d.deserialize_map(GeometryVisitor)
}
}
#[cfg(test)]
mod tests {
use json;
use super::*;
#[test]
fn deserialize() {
assert_eq!(
Geometry::Point(Position(-75.14310264, 40.05701649)),
json::from_str("{\"coordinates\":[-75.14310264,40.05701649],\"type\":\"Point\"}").unwrap()
);
assert_eq!(
Geometry::Polygon(vec![vec![Position(2.2241006,48.8155414), Position(2.4699099,48.8155414),
Position(2.4699099,48.9021461), Position(2.2241006,48.9021461)]]),
json::from_str("{\"coordinates\":[
[[2.2241006,48.8155414],[2.4699099,48.8155414],[2.4699099,48.9021461],[2.2241006,48.9021461]]
],\"type\":\"Polygon\"}").unwrap()
);
}
}