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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Module with the definition of Multipoint(M, Z)
//!
//! All three variant of Multipoint Shape (Multipoint, MultipointM, MultipointZ)
//! are specialization of the `GenericMultipoint`
//!
//! The `GenericMultipoint` Shape implements the [MultipointShape](../trait.MultipointShape.html) trait
//! which means that to access the points of a multipoint you will have to use the
//! [points](../trait.MultipointShape.html#method.points) method
use std::fmt;
use std::io::{Read, Write};
use std::mem::size_of;
use std::slice::SliceIndex;

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};

use record::io::*;
use record::traits::{HasXY, MultipointShape};
use record::ConcreteReadableShape;
use record::{BBox, EsriShape};
use record::{HasShapeType, WritableShape};
use record::{Point, PointM, PointZ};
use {Error, ShapeType};

#[cfg(feature = "geo-types")]
use geo_types;

/// Generic struct to create the Multipoint, MultipointM, MultipointZ types
pub struct GenericMultipoint<PointType> {
    /// The 2D bounding box
    pub bbox: BBox,
    pub points: Vec<PointType>,
}

impl<PointType> MultipointShape<PointType> for GenericMultipoint<PointType> {
    fn point<I: SliceIndex<[PointType]>>(
        &self,
        index: I,
    ) -> Option<&<I as SliceIndex<[PointType]>>::Output> {
        self.points.get(index)
    }
    fn points(&self) -> &[PointType] {
        &self.points
    }
}

impl<PointType: HasXY> GenericMultipoint<PointType> {
    /// Creates a new Multipoint shape
    ///
    /// # Examples
    ///
    /// Creating Multipoint
    /// ```
    /// use shapefile::{Multipoint, Point};
    /// let points = vec![
    ///     Point::new(1.0, 1.0),
    ///     Point::new(2.0, 2.0),
    /// ];
    /// let multipoint = Multipoint::new(points);
    /// ```
    ///
    /// Creating a MultipointM
    /// ```
    /// use shapefile::{MultipointM, PointM, NO_DATA};
    /// let points = vec![
    ///     PointM::new(1.0, 1.0, NO_DATA),
    ///     PointM::new(2.0, 2.0, NO_DATA),
    /// ];
    /// let multipointm = MultipointM::new(points);
    /// ```
    ///
    /// Creating a MultipointZ
    /// ```
    /// use shapefile::{MultipointZ, PointZ, NO_DATA};
    /// let points = vec![
    ///     PointZ::new(1.0, 1.0, 1.0, NO_DATA),
    ///     PointZ::new(2.0, 2.0, 2.0, NO_DATA),
    /// ];
    /// let multipointz = MultipointZ::new(points);
    /// ```

    pub fn new(points: Vec<PointType>) -> Self {
        let bbox = BBox::from_points(&points);
        Self { bbox, points }
    }
}

#[cfg(feature = "geo-types")]
impl<PointType> From<GenericMultipoint<PointType>> for geo_types::MultiPoint<f64>
    where geo_types::Point<f64>: From<PointType>
{
    fn from(multi_points: GenericMultipoint<PointType>) -> Self {
        multi_points.points
            .into_iter()
            .map(|p| geo_types::Point::from(p))
            .collect::<Vec<geo_types::Point<f64>>>()
            .into()
    }
}

#[cfg(feature = "geo-types")]
impl<PointType> From<geo_types::MultiPoint<f64>> for GenericMultipoint<PointType>
    where PointType: From<geo_types::Point<f64>> + HasXY{
    fn from(mp: geo_types::MultiPoint<f64>) -> Self {
        let points = mp.into_iter().map(|p| p.into()).collect();
        Self::new(points)
    }
}


/*
 * Multipoint
 */

/// Specialization of the `GenericMultipoint` struct to represent a `Multipoint` shape
/// ( collection of [Point](../point/struct.Point.html))
pub type Multipoint = GenericMultipoint<Point>;

impl Multipoint {
    pub(crate) fn size_of_record(num_points: i32) -> usize {
        let mut size = 0usize;
        size += 4 * size_of::<f64>(); // BBOX
        size += size_of::<i32>(); // num points
        size += size_of::<Point>() * num_points as usize;
        size
    }
}

impl fmt::Display for Multipoint {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Multipoint({} points)", self.points.len())
    }
}

impl HasShapeType for Multipoint {
    fn shapetype() -> ShapeType {
        ShapeType::Multipoint
    }
}

impl ConcreteReadableShape for Multipoint {
    fn read_shape_content<T: Read>(mut source: &mut T, record_size: i32) -> Result<Self, Error> {
        let bbox = BBox::read_from(&mut source)?;
        let num_points = source.read_i32::<LittleEndian>()?;
        if record_size == Self::size_of_record(num_points) as i32 {
            let points = read_xy_in_vec_of::<Point, T>(&mut source, num_points)?;
            Ok(Self { bbox, points })
        } else {
            Err(Error::InvalidShapeRecordSize)
        }
    }
}

impl WritableShape for Multipoint {
    fn size_in_bytes(&self) -> usize {
        let mut size = 0usize;
        size += 4 * size_of::<f64>(); // BBOX
        size += size_of::<i32>(); // num points
        size += 2 * size_of::<f64>() * self.points.len();
        size
    }

    fn write_to<T: Write>(self, mut dest: &mut T) -> Result<(), Error> {
        self.bbox.write_to(&mut dest)?;
        dest.write_i32::<LittleEndian>(self.points.len() as i32)?;
        for point in self.points {
            dest.write_f64::<LittleEndian>(point.x)?;
            dest.write_f64::<LittleEndian>(point.y)?;
        }
        Ok(())
    }
}

impl EsriShape for Multipoint {
    fn bbox(&self) -> BBox {
        self.bbox
    }
}




/*
 * MultipointM
 */

/// Specialization of the `GenericMultipoint` struct to represent a `MultipointM` shape
/// ( collection of [PointM](../point/struct.PointM.html))
pub type MultipointM = GenericMultipoint<PointM>;

impl MultipointM {
    pub(crate) fn size_of_record(num_points: i32, is_m_used: bool) -> usize {
        let mut size = Multipoint::size_of_record(num_points);
        if is_m_used {
            size += 2 * size_of::<f64>(); // M Range
            size += size_of::<f64>() * num_points as usize; // M
        }
        size
    }
}

impl fmt::Display for MultipointM {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "MultipointM({} points)", self.points.len())
    }
}

impl HasShapeType for MultipointM {
    fn shapetype() -> ShapeType {
        ShapeType::MultipointM
    }
}

impl ConcreteReadableShape for MultipointM {
    fn read_shape_content<T: Read>(mut source: &mut T, record_size: i32) -> Result<Self, Error> {
        let bbox = BBox::read_from(&mut source)?;

        let num_points = source.read_i32::<LittleEndian>()?;

        let size_with_m = Self::size_of_record(num_points, true) as i32;
        let size_without_m = Self::size_of_record(num_points, false) as i32;

        if (record_size != size_with_m) & (record_size != size_without_m) {
            Err(Error::InvalidShapeRecordSize)
        } else {
            let m_is_used = size_with_m == record_size;
            let mut points = read_xy_in_vec_of::<PointM, T>(&mut source, num_points)?;

            if m_is_used {
                let _m_range = read_range(&mut source)?;
                read_ms_into(&mut source, &mut points)?;
            }
            Ok(Self { bbox, points })
        }
    }
}

impl WritableShape for MultipointM {
    fn size_in_bytes(&self) -> usize {
        let mut size = 0usize;
        size += 4 * size_of::<f64>();
        size += size_of::<i32>();
        size += 3 * size_of::<f64>() * self.points.len();
        size += 2 * size_of::<f64>();
        size
    }

    fn write_to<T: Write>(self, mut dest: &mut T) -> Result<(), Error> {
        self.bbox.write_to(&mut dest)?;
        dest.write_i32::<LittleEndian>(self.points.len() as i32)?;

        write_points(&mut dest, &self.points)?;

        write_range(&mut dest, self.m_range())?;
        write_ms(&mut dest, &self.points)?;
        Ok(())
    }
}

impl EsriShape for MultipointM {
    fn bbox(&self) -> BBox {
        self.bbox
    }

    fn m_range(&self) -> [f64; 2] {
        calc_m_range(&self.points)
    }
}

/*
 * MultipointZ
 */

/// Specialization of the `GenericMultipoint` struct to represent a `MultipointZ` shape
/// ( collection of [PointZ](../point/struct.PointZ.html))
pub type MultipointZ = GenericMultipoint<PointZ>;

impl fmt::Display for MultipointZ {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "MultipointZ({} points)", self.points.len())
    }
}
impl MultipointZ {
    pub(crate) fn size_of_record(num_points: i32, is_m_used: bool) -> usize {
        let mut size = Multipoint::size_of_record(num_points);
        size += 2 * size_of::<f64>(); // Z Range
        size += size_of::<f64>() * num_points as usize; // Z

        if is_m_used {
            size += 2 * size_of::<f64>(); // M Range
            size += size_of::<f64>() * num_points as usize; // M
        }

        size
    }
}

impl HasShapeType for MultipointZ {
    fn shapetype() -> ShapeType {
        ShapeType::MultipointZ
    }
}

impl ConcreteReadableShape for MultipointZ {
    fn read_shape_content<T: Read>(mut source: &mut T, record_size: i32) -> Result<Self, Error> {
        let bbox = BBox::read_from(&mut source)?;
        let num_points = source.read_i32::<LittleEndian>()?;

        let size_with_m = Self::size_of_record(num_points, true) as i32;
        let size_without_m = Self::size_of_record(num_points, false) as i32;

        if (record_size != size_with_m) & (record_size != size_without_m) {
            Err(Error::InvalidShapeRecordSize)
        } else {
            let m_is_used = size_with_m == record_size;
            let mut points = read_xy_in_vec_of::<PointZ, T>(&mut source, num_points)?;

            let _z_range = read_range(&mut source)?;
            read_zs_into(&mut source, &mut points)?;

            if m_is_used {
                let _m_range = read_range(&mut source)?;
                read_ms_into(&mut source, &mut points)?;
            }

            Ok(Self { bbox, points })
        }
    }
}

impl WritableShape for MultipointZ {
    fn size_in_bytes(&self) -> usize {
        let mut size = 0usize;
        size += 4 * size_of::<f64>();
        size += size_of::<i32>();
        size += 4 * size_of::<f64>() * self.points.len();
        size += 2 * size_of::<f64>();
        size += 2 * size_of::<f64>();
        size
    }

    fn write_to<T: Write>(self, mut dest: &mut T) -> Result<(), Error> {
        self.bbox.write_to(&mut dest)?;
        dest.write_i32::<LittleEndian>(self.points.len() as i32)?;

        write_points(&mut dest, &self.points)?;

        write_range(&mut dest, self.z_range())?;
        write_zs(&mut dest, &self.points)?;

        write_range(&mut dest, self.m_range())?;
        write_ms(&mut dest, &self.points)?;

        Ok(())
    }
}

impl EsriShape for MultipointZ {
    fn bbox(&self) -> BBox {
        self.bbox
    }

    fn z_range(&self) -> [f64; 2] {
        calc_z_range(&self.points)
    }

    fn m_range(&self) -> [f64; 2] {
        calc_m_range(&self.points)
    }
}


#[cfg(test)]
#[cfg(feature = "geo-types")]
mod tests {
    use super::*;
    use ::{geo_types, NO_DATA};

    #[test]
    fn test_multipoint_to_geo_types_multipoint() {
        let points = vec![
            Point::new(1.0, 1.0),
            Point::new(2.0, 2.0),
        ];
        let shapefile_multipoint = Multipoint::new(points);
        let geo_types_multipoint = geo_types::MultiPoint::from(shapefile_multipoint);

        let mut iter = geo_types_multipoint.into_iter();
        let p1 = iter.next().unwrap();
        let p2 = iter.next().unwrap();
        assert_eq!(p1.x(), 1.0);
        assert_eq!(p1.y(), 1.0);

        assert_eq!(p2.x(), 2.0);
        assert_eq!(p2.y(), 2.0);
    }


    #[test]
    fn test_multipoint_m_to_geo_types_multipoint() {
        let points = vec![
            PointM::new(120.0, 56.0, 42.2),
            PointM::new(6.0, 18.7, 462.54),
        ];
        let shapefile_multipoint = MultipointM::new(points);
        let geo_types_multipoint = geo_types::MultiPoint::from(shapefile_multipoint);

        let mut iter = geo_types_multipoint.into_iter();
        let p1 = iter.next().unwrap();
        let p2 = iter.next().unwrap();
        assert_eq!(p1.x(), 120.0);
        assert_eq!(p1.y(), 56.0);

        assert_eq!(p2.x(), 6.0);
        assert_eq!(p2.y(), 18.7);


        let geo_types_multipoint: geo_types::MultiPoint<_> = vec![p1, p2].into();
        let shapefile_multipoint = MultipointM::from(geo_types_multipoint);

        assert_eq!(shapefile_multipoint.points[0].x, 120.0);
        assert_eq!(shapefile_multipoint.points[0].y, 56.0);
        assert_eq!(shapefile_multipoint.points[0].m, NO_DATA);

        assert_eq!(shapefile_multipoint.points[1].x, 6.0);
        assert_eq!(shapefile_multipoint.points[1].y, 18.7);
        assert_eq!(shapefile_multipoint.points[0].m, NO_DATA);
    }

    #[test]
    fn test_multipoint_z_to_geo_types_multipoint() {
        let points = vec![
            PointZ::new(1.0, 1.0,  17.0, 18.0),
            PointZ::new(2.0, 2.0, 15.0, 16.0),
        ];
        let shapefile_multipoint = MultipointZ::new(points);
        let geo_types_multipoint = geo_types::MultiPoint::from(shapefile_multipoint);

        let mut iter = geo_types_multipoint.into_iter();
        let p1 = iter.next().unwrap();
        let p2 = iter.next().unwrap();
        assert_eq!(p1.x(), 1.0);
        assert_eq!(p1.y(), 1.0);

        assert_eq!(p2.x(), 2.0);
        assert_eq!(p2.y(), 2.0);

        let geo_types_multipoint: geo_types::MultiPoint<_> = vec![p1, p2].into();
        let shapefile_multipoint = MultipointZ::from(geo_types_multipoint);

        assert_eq!(shapefile_multipoint.points[0].x, 1.0);
        assert_eq!(shapefile_multipoint.points[0].y, 1.0);
        assert_eq!(shapefile_multipoint.points[0].z, 0.0);
        assert_eq!(shapefile_multipoint.points[0].m, NO_DATA);

        assert_eq!(shapefile_multipoint.points[1].x, 2.0);
        assert_eq!(shapefile_multipoint.points[1].y, 2.0);
        assert_eq!(shapefile_multipoint.points[0].z, 0.0);
        assert_eq!(shapefile_multipoint.points[0].m, NO_DATA);
    }

}