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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use crate::de::deserialize_feature_collection;
use crate::{Feature, Result};

use serde::de::DeserializeOwned;

use std::io::Read;

/// Enumerates individual Features from a GeoJSON FeatureCollection
pub struct FeatureReader<R> {
    reader: R,
}

impl<R: Read> FeatureReader<R> {
    /// Create a FeatureReader from the given `reader`.
    pub fn from_reader(reader: R) -> Self {
        Self { reader }
    }

    /// Iterate over the individual [`Feature`s](Feature) of a FeatureCollection.
    ///
    /// If instead you'd like to deserialize directly to your own struct, see [`FeatureReader::deserialize`].
    ///
    /// # Examples
    ///
    /// ```
    /// let feature_collection_string = r#"{
    ///      "type": "FeatureCollection",
    ///      "features": [
    ///          {
    ///            "type": "Feature",
    ///            "geometry": { "type": "Point", "coordinates": [125.6, 10.1] },
    ///            "properties": {
    ///              "name": "Dinagat Islands",
    ///              "age": 123
    ///            }
    ///          },
    ///          {
    ///            "type": "Feature",
    ///            "geometry": { "type": "Point", "coordinates": [2.3, 4.5] },
    ///            "properties": {
    ///              "name": "Neverland",
    ///              "age": 456
    ///            }
    ///          }
    ///      ]
    /// }"#
    /// .as_bytes();
    /// let io_reader = std::io::BufReader::new(feature_collection_string);
    ///
    /// use geojson::FeatureReader;
    /// let feature_reader = FeatureReader::from_reader(io_reader);
    /// for feature in feature_reader.features() {
    ///     let feature = feature.expect("valid geojson feature");
    ///
    ///     let name = feature.property("name").unwrap().as_str().unwrap();
    ///     let age = feature.property("age").unwrap().as_u64().unwrap();
    ///
    ///     if name == "Dinagat Islands" {
    ///         assert_eq!(123, age);
    ///     } else if name == "Neverland" {
    ///         assert_eq!(456, age);
    ///     } else {
    ///         panic!("unexpected name: {}", name);
    ///     }
    /// }
    /// ```
    pub fn features(self) -> impl Iterator<Item = Result<Feature>> {
        #[allow(deprecated)]
        crate::FeatureIterator::new(self.reader)
    }

    /// Deserialize the features of FeatureCollection into your own custom
    /// struct using the [`serde`](../../serde) crate.
    ///
    /// # Examples
    ///
    /// Your struct must implement or derive [`serde::Deserialize`].
    ///
    /// If you have enabled the `geo-types` feature, which is enabled by default, you can
    /// deserialize directly to a useful geometry type.
    ///
    /// ```rust,ignore
    /// use geojson::{FeatureReader, de::deserialize_geometry};
    ///
    /// #[derive(serde::Deserialize)]
    /// struct MyStruct {
    ///     #[serde(deserialize_with = "deserialize_geometry")]
    ///     geometry: geo_types::Point<f64>,
    ///     name: String,
    ///     age: u64,
    /// }
    /// ```
    ///
    /// Then you can deserialize the FeatureCollection directly to your type.
    #[cfg_attr(feature = "geo-types", doc = "```")]
    #[cfg_attr(not(feature = "geo-types"), doc = "```ignore")]
    /// let feature_collection_string = r#"{
    ///     "type": "FeatureCollection",
    ///     "features": [
    ///         {
    ///            "type": "Feature",
    ///            "geometry": { "type": "Point", "coordinates": [125.6, 10.1] },
    ///            "properties": {
    ///              "name": "Dinagat Islands",
    ///              "age": 123
    ///            }
    ///         },
    ///         {
    ///            "type": "Feature",
    ///            "geometry": { "type": "Point", "coordinates": [2.3, 4.5] },
    ///            "properties": {
    ///              "name": "Neverland",
    ///              "age": 456
    ///            }
    ///          }
    ///    ]
    /// }"#.as_bytes();
    /// let io_reader = std::io::BufReader::new(feature_collection_string);
    /// #
    /// # use geojson::{FeatureReader, de::deserialize_geometry};
    /// #
    /// # #[derive(serde::Deserialize)]
    /// # struct MyStruct {
    /// #     #[serde(deserialize_with = "deserialize_geometry")]
    /// #     geometry: geo_types::Point<f64>,
    /// #     name: String,
    /// #     age: u64,
    /// # }
    ///
    /// let feature_reader = FeatureReader::from_reader(io_reader);
    /// for feature in feature_reader.deserialize::<MyStruct>().unwrap() {
    ///     let my_struct = feature.expect("valid geojson feature");
    ///
    ///     if my_struct.name == "Dinagat Islands" {
    ///         assert_eq!(123, my_struct.age);
    ///     } else if my_struct.name == "Neverland" {
    ///         assert_eq!(456, my_struct.age);
    ///     } else {
    ///         panic!("unexpected name: {}", my_struct.name);
    ///     }
    /// }
    /// ```
    ///
    /// If you're not using [`geo-types`](geo_types), you can deserialize to a `geojson::Geometry` instead.
    /// ```rust,ignore
    /// use serde::Deserialize;
    /// #[derive(Deserialize)]
    /// struct MyStruct {
    ///     geometry: geojson::Geometry,
    ///     name: String,
    ///     age: u64,
    /// }
    /// ```
    pub fn deserialize<D: DeserializeOwned>(self) -> Result<impl Iterator<Item = Result<D>>> {
        deserialize_feature_collection(self.reader)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use serde::Deserialize;
    use serde_json::json;

    #[derive(Deserialize)]
    struct MyRecord {
        geometry: crate::Geometry,
        name: String,
        age: u64,
    }

    fn feature_collection_string() -> String {
        json!({
            "type": "FeatureCollection",
            "features": [
                {
                  "type": "Feature",
                  "geometry": {
                    "type": "Point",
                    "coordinates": [125.6, 10.1]
                  },
                  "properties": {
                    "name": "Dinagat Islands",
                    "age": 123
                  }
                },
                {
                  "type": "Feature",
                  "geometry": {
                    "type": "Point",
                    "coordinates": [2.3, 4.5]
                  },
                  "properties": {
                    "name": "Neverland",
                    "age": 456
                  }
                }
            ]
        })
        .to_string()
    }

    #[test]
    #[cfg(feature = "geo-types")]
    fn deserialize_into_type() {
        let feature_collection_string = feature_collection_string();
        let mut bytes_reader = feature_collection_string.as_bytes();
        let feature_reader = FeatureReader::from_reader(&mut bytes_reader);

        let records: Vec<MyRecord> = feature_reader
            .deserialize()
            .expect("a valid feature collection")
            .map(|result| result.expect("a valid feature"))
            .collect();

        assert_eq!(records.len(), 2);

        assert_eq!(
            records[0].geometry,
            (&geo_types::point!(x: 125.6, y: 10.1)).into()
        );
        assert_eq!(records[0].name, "Dinagat Islands");
        assert_eq!(records[0].age, 123);

        assert_eq!(
            records[1].geometry,
            (&geo_types::point!(x: 2.3, y: 4.5)).into()
        );
        assert_eq!(records[1].name, "Neverland");
        assert_eq!(records[1].age, 456);
    }
}