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
use crate::error::Error;
use crate::{ConstGeometry, Geom, Geometry as GGeometry};
use geo_types::Geometry;
use wkt;
use std::convert::TryFrom;
macro_rules! impl_try_into {
($ty_name:ident $(,$lt:lifetime)?) => (
impl<'a, 'b$(,$lt)?> TryFrom<&'b $ty_name<'a$(,$lt)?>> for Geometry<f64> {
type Error = Error;
fn try_from(other: &'b $ty_name<'a$(,$lt)?>) -> Result<Geometry<f64>, Self::Error> {
let wkt_str = other.to_wkt()?;
let wkt_obj = wkt::Wkt::from_str(&wkt_str)
.map_err(|e| Error::ConversionError(format!("impossible to read wkt: {}", e)))?;
let o: wkt::Geometry<f64> = wkt_obj
.items
.into_iter()
.next()
.ok_or(Error::ConversionError("invalid wkt".into()))?;
o.try_into()
.map_err(|e| Error::ConversionError(format!("impossible to built from wkt: {}", e)))
}
}
impl<'a$(,$lt)?> TryFrom<$ty_name<'a$(,$lt)?>> for Geometry<f64> {
type Error = Error;
fn try_from(other: $ty_name<'a$(,$lt)?>) -> Result<Geometry<f64>, Self::Error> {
Geometry::try_from(&other)
}
}
);
}
impl_try_into!(GGeometry);
impl_try_into!(ConstGeometry, 'c);
#[cfg(test)]
mod test {
use crate::Geometry as GGeometry;
use geo_types::{Coordinate, Geometry, LineString, MultiPolygon, Polygon};
use std::convert::TryInto;
fn coords(tuples: Vec<(f64, f64)>) -> Vec<Coordinate<f64>> {
tuples.into_iter().map(Coordinate::from).collect()
}
#[test]
fn geom_to_geo_polygon() {
let poly = "MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))";
let poly = GGeometry::new_from_wkt(poly).unwrap();
let geo_polygon: Geometry<f64> = (&poly).try_into().unwrap();
let exterior = LineString(coords(vec![
(0., 0.),
(0., 1.),
(1., 1.),
(1., 0.),
(0., 0.),
]));
let expected_poly = MultiPolygon(vec![Polygon::new(exterior, vec![])]);
let expected: Geometry<_> = expected_poly.into();
assert_eq!(expected, geo_polygon);
assert_eq!(expected, poly.try_into().unwrap());
}
}