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

Add TryFrom impls for JsonObject and JsonValue #120

Merged
merged 2 commits into from
Nov 16, 2019
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
58 changes: 56 additions & 2 deletions src/feature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::json::{Deserialize, Deserializer, JsonObject, Serialize, Serializer};
use std::convert::TryFrom;

use crate::json::{Deserialize, Deserializer, JsonObject, JsonValue, Serialize, Serializer};
use crate::serde_json::json;
use crate::{util, Error, Feature};

Expand Down Expand Up @@ -51,7 +53,19 @@ impl<'a> From<&'a Feature> for JsonObject {
}

impl Feature {
pub fn from_json_object(mut object: JsonObject) -> Result<Self, Error> {
pub fn from_json_object(object: JsonObject) -> Result<Self, Error> {
Self::try_from(object)
}

pub fn from_json_value(value: JsonValue) -> Result<Self, Error> {
Self::try_from(value)
}
}

impl TryFrom<JsonObject> for Feature {
type Error = Error;

fn try_from(mut object: JsonObject) -> Result<Self, Error> {
match &*util::expect_type(&mut object)? {
"Feature" => Ok(Feature {
geometry: util::get_geometry(&mut object)?,
Expand All @@ -65,6 +79,18 @@ impl Feature {
}
}

impl TryFrom<JsonValue> for Feature {
type Error = Error;

fn try_from(value: JsonValue) -> Result<Self, Error> {
if let JsonValue::Object(obj) = value {
Self::try_from(obj)
} else {
Err(Error::GeoJsonExpectedObject)
}
}
}

impl Serialize for Feature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down Expand Up @@ -160,6 +186,34 @@ mod tests {
assert_eq!(decoded_feature, feature);
}

#[test]
fn try_from_value() {
use serde_json::json;
use std::convert::TryInto;

let json_value = json!({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [102.0, 0.5]
},
"properties": null,
});
assert!(json_value.is_object());

let feature: Feature = json_value.try_into().unwrap();
assert_eq!(
feature,
Feature {
bbox: None,
geometry: Some(Geometry::new(Value::Point(vec![102.0, 0.5]))),
id: None,
properties: None,
foreign_members: None,
}
)
}

#[test]
fn test_display_feature() {
let f = feature().to_string();
Expand Down
30 changes: 28 additions & 2 deletions src/feature_collection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::json::{Deserialize, Deserializer, JsonObject, Serialize, Serializer};
use std::convert::TryFrom;

use crate::json::{Deserialize, Deserializer, JsonObject, JsonValue, Serialize, Serializer};
use crate::serde_json::json;
use crate::{util, Bbox, Error, Feature};

Expand Down Expand Up @@ -81,7 +83,19 @@ impl<'a> From<&'a FeatureCollection> for JsonObject {
}

impl FeatureCollection {
pub fn from_json_object(mut object: JsonObject) -> Result<Self, Error> {
pub fn from_json_object(object: JsonObject) -> Result<Self, Error> {
Self::try_from(object)
}

pub fn from_json_value(value: JsonValue) -> Result<Self, Error> {
Self::try_from(value)
}
}

impl TryFrom<JsonObject> for FeatureCollection {
type Error = Error;

fn try_from(mut object: JsonObject) -> Result<Self, Error> {
match util::expect_type(&mut object)? {
ref type_ if type_ == "FeatureCollection" => Ok(FeatureCollection {
bbox: util::get_bbox(&mut object)?,
Expand All @@ -96,6 +110,18 @@ impl FeatureCollection {
}
}

impl TryFrom<JsonValue> for FeatureCollection {
type Error = Error;

fn try_from(value: JsonValue) -> Result<Self, Error> {
if let JsonValue::Object(obj) = value {
Self::try_from(obj)
} else {
Err(Error::GeoJsonExpectedObject)
}
}
}

impl Serialize for FeatureCollection {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
55 changes: 34 additions & 21 deletions src/geojson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use crate::json::{self, Deserialize, Deserializer, JsonObject, JsonValue, Serialize, Serializer};
use crate::serde;
use crate::{Error, Feature, FeatureCollection, Geometry};
use std::convert::TryFrom;
use std::fmt;
use std::str::FromStr;

Expand Down Expand Up @@ -58,30 +59,14 @@ impl From<FeatureCollection> for GeoJson {

impl GeoJson {
pub fn from_json_object(object: JsonObject) -> Result<Self, Error> {
let type_ = match object.get("type") {
Some(json::JsonValue::String(t)) => Type::from_str(t),
_ => return Err(Error::ExpectedProperty("type".to_owned())),
};
let type_ = type_.ok_or(Error::GeoJsonUnknownType)?;
match type_ {
Type::Point
| Type::MultiPoint
| Type::LineString
| Type::MultiLineString
| Type::Polygon
| Type::MultiPolygon
| Type::GeometryCollection => Geometry::from_json_object(object).map(GeoJson::Geometry),
Type::Feature => Feature::from_json_object(object).map(GeoJson::Feature),
Type::FeatureCollection => {
FeatureCollection::from_json_object(object).map(GeoJson::FeatureCollection)
}
}
Self::try_from(object)
}

/// Converts a JSON Value into a GeoJson object.
///
/// # Example
/// ```
/// use std::convert::TryInto;
/// use geojson::{Feature, GeoJson, Geometry, Value};
/// use serde_json::json;
///
Expand All @@ -96,7 +81,7 @@ impl GeoJson {
///
/// assert!(json_value.is_object());
///
/// let geojson = GeoJson::from_json_value(json_value).unwrap();
/// let geojson: GeoJson = json_value.try_into().unwrap();
///
/// assert_eq!(
/// geojson,
Expand All @@ -110,8 +95,35 @@ impl GeoJson {
/// );
/// ```
pub fn from_json_value(value: JsonValue) -> Result<Self, Error> {
Self::try_from(value)
}
}

impl TryFrom<JsonObject> for GeoJson {
type Error = Error;

fn try_from(object: JsonObject) -> Result<Self, Self::Error> {
let type_ = match object.get("type") {
Some(json::JsonValue::String(t)) => Type::from_str(t),
_ => return Err(Error::ExpectedProperty("type".to_owned())),
};
let type_ = type_.ok_or(Error::GeoJsonUnknownType)?;
match type_ {
Type::Feature => Feature::try_from(object).map(GeoJson::Feature),
Type::FeatureCollection => {
FeatureCollection::try_from(object).map(GeoJson::FeatureCollection)
}
_ => Geometry::try_from(object).map(GeoJson::Geometry),
}
}
}

impl TryFrom<JsonValue> for GeoJson {
type Error = Error;

fn try_from(value: JsonValue) -> Result<Self, Self::Error> {
if let JsonValue::Object(obj) = value {
Self::from_json_object(obj)
Self::try_from(obj)
} else {
Err(Error::GeoJsonExpectedObject)
}
Expand Down Expand Up @@ -232,6 +244,7 @@ impl fmt::Display for FeatureCollection {
mod tests {
use crate::{Feature, GeoJson, Geometry, Value};
use serde_json::json;
use std::convert::TryInto;

#[test]
fn test_geojson_from_value() {
Expand All @@ -246,7 +259,7 @@ mod tests {

assert!(json_value.is_object());

let geojson = GeoJson::from_json_value(json_value).unwrap();
let geojson: GeoJson = json_value.try_into().unwrap();

assert_eq!(
geojson,
Expand Down
52 changes: 51 additions & 1 deletion src/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::convert::TryFrom;

use crate::json::{Deserialize, Deserializer, JsonObject, JsonValue, Serialize, Serializer};
use crate::serde;
use crate::{util, Bbox, Error, LineStringType, PointType, PolygonType};
Expand Down Expand Up @@ -212,7 +214,19 @@ impl<'a> From<&'a Geometry> for JsonObject {
}

impl Geometry {
pub fn from_json_object(mut object: JsonObject) -> Result<Self, Error> {
pub fn from_json_object(object: JsonObject) -> Result<Self, Error> {
Self::try_from(object)
}

pub fn from_json_value(value: JsonValue) -> Result<Self, Error> {
Self::try_from(value)
}
}

impl TryFrom<JsonObject> for Geometry {
type Error = Error;

fn try_from(mut object: JsonObject) -> Result<Self, Self::Error> {
let value = match &*util::expect_type(&mut object)? {
"Point" => Value::Point(util::get_coords_one_pos(&mut object)?),
"MultiPoint" => Value::MultiPoint(util::get_coords_1d_pos(&mut object)?),
Expand All @@ -233,6 +247,18 @@ impl Geometry {
}
}

impl TryFrom<JsonValue> for Geometry {
type Error = Error;

fn try_from(value: JsonValue) -> Result<Self, Self::Error> {
if let JsonValue::Object(obj) = value {
Self::try_from(obj)
} else {
Err(Error::GeoJsonExpectedObject)
}
}
}

impl Serialize for Geometry {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down Expand Up @@ -290,6 +316,30 @@ mod tests {
assert_eq!(decoded_geometry, geometry);
}

#[test]
fn test_geometry_from_value() {
use serde_json::json;
use std::convert::TryInto;

let json_value = json!({
"type": "Point",
"coordinates": [
0.0, 0.1
],
});
assert!(json_value.is_object());

let geometry: Geometry = json_value.try_into().unwrap();
assert_eq!(
geometry,
Geometry {
value: Value::Point(vec![0.0, 0.1]),
bbox: None,
foreign_members: None,
}
)
}

#[test]
fn test_geometry_display() {
let v = Value::LineString(vec![vec![0.0, 0.1], vec![0.1, 0.2], vec![0.2, 0.3]]);
Expand Down