use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Location {
#[serde(
serialize_with = "geojson::ser::serialize_geometry",
deserialize_with = "geojson::de::deserialize_geometry"
)]
inner: geo::Point<f64>,
}
impl Location {
pub fn new(x: f64, y: f64) -> Self {
Self {
inner: geo::Point::new(x, y),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde_with::skip_serializing_none]
struct S {
pub location: Option<Location>,
}
#[test]
fn serialization_roundtrip_some() {
let ground_truth = S {
location: Some(Location::new(3.14, 15.92)),
};
let serialized = serde_json::to_string(&ground_truth).unwrap();
assert_eq!(
serialized,
"{\"location\":{\"inner\":{\"type\":\"Point\",\"coordinates\":[3.14,15.92]}}}"
);
let deserialized: S = serde_json::from_str(&serialized).unwrap();
assert_eq!(deserialized, ground_truth);
}
#[test]
fn serialization_roundtrip_none() {
let ground_truth = S { location: None };
let serialized = serde_json::to_string(&ground_truth).unwrap();
let deserialized: S = serde_json::from_str(&serialized).unwrap();
assert_eq!(deserialized, ground_truth);
}
#[test]
fn deserializing_invalid_data_errors_out() {
for invalid_str in [
"{\"location\":{\"type\":\"Point\",\"coordinates\":[3.14a,15.92]}}",
"{\"location\":{\"inner\":{\"x\":3.14,\"y\":15.92}}}",
] {
assert!(serde_json::from_str::<S>(invalid_str).is_err());
}
}
}