-
Notifications
You must be signed in to change notification settings - Fork 26
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
impl serde::Deserialize for Wkt and Geometry (and helper function) #59
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
78ec483
impl serde::Deserialize for Wkt and Geometry
woshilapin 9f1de49
add helper function to deserialize to geo_types::Geometry
woshilapin f5e5d35
expose deserialize helper function at crate level
woshilapin d5a8de3
remove unwrap in deserialize helper function
woshilapin be202f4
make helper function generic over float type
woshilapin fe5e129
expose helper function only when geo-types and serde
woshilapin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,200 @@ | ||
use crate::{Geometry, Wkt, WktFloat}; | ||
use serde::de::{Deserializer, Error, Visitor}; | ||
use std::{ | ||
default::Default, | ||
fmt::{self, Debug}, | ||
marker::PhantomData, | ||
str::FromStr, | ||
}; | ||
|
||
struct WktVisitor<T> { | ||
_marker: PhantomData<T>, | ||
} | ||
|
||
impl<T> Default for WktVisitor<T> { | ||
fn default() -> Self { | ||
WktVisitor { | ||
_marker: PhantomData::default(), | ||
} | ||
} | ||
} | ||
|
||
impl<'de, T> Visitor<'de> for WktVisitor<T> | ||
where | ||
T: FromStr + Default + Debug + WktFloat, | ||
{ | ||
type Value = Wkt<T>; | ||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
write!(formatter, "a valid WKT format") | ||
} | ||
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> | ||
where | ||
E: Error, | ||
{ | ||
Wkt::from_str(s).map_err(|e| serde::de::Error::custom(e)) | ||
} | ||
} | ||
|
||
impl<'de, T> serde::Deserialize<'de> for Wkt<T> | ||
where | ||
T: FromStr + Default + Debug + WktFloat, | ||
{ | ||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> | ||
where | ||
D: Deserializer<'de>, | ||
{ | ||
deserializer.deserialize_str(WktVisitor::default()) | ||
} | ||
} | ||
|
||
struct GeometryVisitor<T> { | ||
_marker: PhantomData<T>, | ||
} | ||
|
||
impl<T> Default for GeometryVisitor<T> { | ||
fn default() -> Self { | ||
GeometryVisitor { | ||
_marker: PhantomData::default(), | ||
} | ||
} | ||
} | ||
|
||
impl<'de, T> Visitor<'de> for GeometryVisitor<T> | ||
where | ||
T: FromStr + Default + WktFloat, | ||
{ | ||
type Value = Geometry<T>; | ||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
write!(formatter, "a valid WKT format") | ||
} | ||
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> | ||
where | ||
E: Error, | ||
{ | ||
let mut wkt = Wkt::from_str(s).map_err(|e| serde::de::Error::custom(e))?; | ||
if wkt.items.len() == 1 { | ||
Ok(wkt.items.remove(0)) | ||
} else { | ||
Err(serde::de::Error::custom( | ||
"WKT should have only 1 Geometry item", | ||
)) | ||
} | ||
} | ||
} | ||
|
||
impl<'de, T> serde::Deserialize<'de> for Geometry<T> | ||
where | ||
T: FromStr + Default + WktFloat, | ||
{ | ||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> | ||
where | ||
D: Deserializer<'de>, | ||
{ | ||
deserializer.deserialize_str(GeometryVisitor::default()) | ||
} | ||
} | ||
|
||
/// This is a helper function to convert directly from WKT format into a geo_types::Geometry. | ||
/// ``` | ||
/// # extern crate wkt; | ||
/// # extern crate geo_types; | ||
/// # extern crate serde_json; | ||
/// use geo_types::Geometry; | ||
/// | ||
/// #[derive(serde::Deserialize)] | ||
/// struct MyType { | ||
/// #[serde(deserialize_with = "wkt::deserialize_geometry")] | ||
/// pub geometry: Geometry<f64>, | ||
/// } | ||
/// | ||
/// let json = r#"{ "geometry": "POINT (3.14 42)" }"#; | ||
/// let my_type: MyType = serde_json::from_str(json).unwrap(); | ||
/// assert!(matches!(my_type.geometry, Geometry::Point(_))); | ||
/// ``` | ||
#[cfg(feature = "geo-types")] | ||
pub fn deserialize_geometry<'de, D, T>(deserializer: D) -> Result<geo_types::Geometry<T>, D::Error> | ||
where | ||
D: Deserializer<'de>, | ||
T: FromStr + Default + WktFloat, | ||
{ | ||
use serde::Deserialize; | ||
Geometry::deserialize(deserializer).and_then(|g: Geometry<T>| { | ||
use std::convert::TryInto; | ||
g.try_into().map_err(|e| D::Error::custom(e)) | ||
}) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::{ | ||
types::{Coord, Point}, | ||
Geometry, | ||
}; | ||
use serde::de::{ | ||
value::{Error, StrDeserializer}, | ||
Deserializer, Error as _, IntoDeserializer, | ||
}; | ||
|
||
mod wkt { | ||
use super::*; | ||
|
||
#[test] | ||
fn deserialize() { | ||
let deserializer: StrDeserializer<'_, Error> = "POINT (10 20.1)".into_deserializer(); | ||
let wkt = deserializer | ||
.deserialize_any(WktVisitor::<f64>::default()) | ||
.unwrap(); | ||
assert!(matches!( | ||
wkt.items[0], | ||
Geometry::Point(Point(Some(Coord { | ||
x: _, // floating-point types cannot be used in patterns | ||
y: _, // floating-point types cannot be used in patterns | ||
z: None, | ||
m: None, | ||
}))) | ||
)); | ||
} | ||
|
||
#[test] | ||
fn deserialize_error() { | ||
let deserializer: StrDeserializer<'_, Error> = "POINT (10 20.1A)".into_deserializer(); | ||
let wkt = deserializer.deserialize_any(WktVisitor::<f64>::default()); | ||
assert_eq!( | ||
wkt.unwrap_err(), | ||
Error::custom("Expected a number for the Y coordinate") | ||
); | ||
} | ||
} | ||
|
||
mod geometry { | ||
use super::*; | ||
|
||
#[test] | ||
fn deserialize() { | ||
let deserializer: StrDeserializer<'_, Error> = "POINT (42 3.14)".into_deserializer(); | ||
let geometry = deserializer | ||
.deserialize_any(GeometryVisitor::<f64>::default()) | ||
.unwrap(); | ||
assert!(matches!( | ||
geometry, | ||
Geometry::Point(Point(Some(Coord { | ||
x: _, // floating-point types cannot be used in patterns | ||
y: _, // floating-point types cannot be used in patterns | ||
z: None, | ||
m: None, | ||
}))) | ||
)); | ||
} | ||
|
||
#[test] | ||
fn deserialize_error() { | ||
let deserializer: StrDeserializer<'_, Error> = "POINT (42 PI3.14)".into_deserializer(); | ||
let geometry = deserializer.deserialize_any(GeometryVisitor::<f64>::default()); | ||
assert_eq!( | ||
geometry.unwrap_err(), | ||
Error::custom("Expected a number for the Y coordinate") | ||
); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
oh right, there is a special dance to do when a doc-test requires a feature flag.
We have a similar example here in
proj
which requires the optionalgeo-types
feature:https://github.com/georust/proj/blob/master/src/lib.rs#L175
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually, forget that. This whole module is only included conditionally with the
serde
feature. I'm not immediately sure what to make of the CI failure. I can look at it further next week.https://github.com/georust/wkt/runs/1891796241