Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

deserialize point #62

Merged
merged 3 commits into from
Feb 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion src/deserialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ where
}
}

/// This is a helper function to convert directly from WKT format into a geo_types::Geometry.
/// Deserializes directly from WKT format into a geo_types::Geometry.
/// ```
/// # extern crate wkt;
/// # extern crate geo_types;
Expand Down Expand Up @@ -124,6 +124,52 @@ where
})
}

/// Deserializes directly from WKT format into a `Option<geo_types::Point>`.
///
/// # Examples
///
///
/// ```
/// # extern crate wkt;
/// # extern crate geo_types;
/// # extern crate serde_json;
/// use geo_types::Point;
///
/// #[derive(serde::Deserialize)]
/// struct MyType {
/// #[serde(deserialize_with = "wkt::deserialize_point")]
/// pub geometry: Option<Point<f64>>,
/// }
///
/// let json = r#"{ "geometry": "POINT (3.14 42)" }"#;
/// let my_type: MyType = serde_json::from_str(json).unwrap();
/// assert!(matches!(my_type.geometry, Some(Point(_))));
///
/// let json = r#"{ "geometry": "POINT EMPTY" }"#;
/// let my_type: MyType = serde_json::from_str(json).unwrap();
/// assert!(matches!(my_type.geometry, None));
/// ```
#[cfg(feature = "geo-types")]
pub fn deserialize_point<'de, D, T>(deserializer: D) -> Result<Option<geo_types::Point<T>>, D::Error>
where
D: Deserializer<'de>,
T: FromStr + Default + WktFloat,
{
use serde::Deserialize;
Wkt::deserialize(deserializer).and_then(|wkt: Wkt<T>| {
use std::convert::TryFrom;
geo_types::Point::try_from(wkt).map(|p| Some(p))
.or_else(|e| {
if let crate::conversion::Error::PointConversionError = e {
// map a WKT: 'POINT EMPTY' to an `Option<geo_types::Point>::None`
return Ok(None);
}

Err(D::Error::custom(e))
})
})
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ extern crate serde;
#[cfg(feature = "serde")]
pub mod deserialize;
#[cfg(all(feature = "serde", feature = "geo-types"))]
pub use deserialize::deserialize_geometry;
pub use deserialize::{deserialize_geometry, deserialize_point};

pub trait WktFloat: num_traits::Float + std::fmt::Debug {}
impl<T> WktFloat for T where T: num_traits::Float + std::fmt::Debug {}
Expand Down