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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! Module with the definition of Multipoint, MultipointM and MultipointZ
//!
//! All three variant of Multipoint Shape (Multipoint, MultipointM, MultipointZ)
//! are specialization of the `GenericMultipoint`
//!
use std::fmt;
use std::io::{Read, Write};
use std::mem::size_of;
use std::ops::Index;
use std::slice::SliceIndex;

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

use record::io::*;
use record::traits::{GrowablePoint, ShrinkablePoint};
use record::EsriShape;
use record::{ConcreteReadableShape, GenericBBox};
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
///
/// Multipoints are a collection of... multiple points,
/// they can be created from [`Vec`] of points using the [`From`] trait
/// or using the [`new`] method.
///
/// `Multipoint` shapes only offers non-mutable access to the points data,
/// to be able to mutate it you have to move the points data out of the struct.
///
/// ```
/// use shapefile::{Multipoint, Point};
/// let multipoint = Multipoint::from(vec![
///     Point::new(1.0, 1.0),
///     Point::new(2.0, 2.0),
/// ]);
///
/// assert_eq!(multipoint[0], Point::new(1.0, 1.0));
///
/// let points: Vec<Point> = multipoint.into();
/// assert_eq!(points.len(), 2);
/// ```
///
/// # geo-types
///
/// Multipoints are convertible to the geo-types's Multipoint<f64>
///
/// ```
/// # #[cfg(feature = "geo-types")]
/// # fn main() -> Result<(), shapefile::Error> {
/// let mut multipoints = shapefile::read_shapes_as::<_, shapefile::Multipoint>("tests/data/multipoint.shp")?;
/// let geo_multipoint: geo_types::MultiPoint<f64> = multipoints.pop().unwrap().into();
/// let multipoint = shapefile::Multipoint::from(geo_multipoint);
/// # Ok(())
/// # }
/// # #[cfg(not(feature = "geo-types"))]
/// # fn main() {}
/// ```
///
/// [`new`]: #method.new
#[derive(Debug, Clone, PartialEq)]
pub struct GenericMultipoint<PointType> {
    pub(crate) bbox: GenericBBox<PointType>,
    pub(crate) points: Vec<PointType>,
}

impl<PointType: ShrinkablePoint + GrowablePoint + Copy> 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 = GenericBBox::<PointType>::from_points(&points);
        Self { bbox, points }
    }
}

impl<PointType> GenericMultipoint<PointType> {
    /// Returns the bbox
    ///
    /// # Example
    ///
    /// ```
    /// use shapefile::{MultipointZ, PointZ, NO_DATA};
    /// let multipointz = MultipointZ::new(vec![
    ///     PointZ::new(1.0, 4.0, 1.2, 4.2),
    ///     PointZ::new(2.0, 6.0, 4.0, 13.37),
    /// ]);
    ///
    /// let bbox = multipointz.bbox();
    /// assert_eq!(bbox.min.x, 1.0);
    /// assert_eq!(bbox.max.x, 2.0);
    /// assert_eq!(bbox.m_range(), [4.2, 13.37])
    /// ```
    #[inline]
    pub fn bbox(&self) -> &GenericBBox<PointType> {
        &self.bbox
    }

    /// Returns a non-mutable slice of point
    #[inline]
    pub fn points(&self) -> &[PointType] {
        &self.points
    }

    /// Returns a reference to a point
    ///
    /// # Example
    ///
    /// ```
    /// use shapefile::{MultipointZ, PointZ};
    /// let multipointz = MultipointZ::new(vec![
    ///     PointZ::new(1.0, 4.0, 1.2, 4.2),
    ///     PointZ::new(2.0, 6.0, 4.0, 13.37),
    /// ]);
    ///
    /// assert_eq!(multipointz.point(0), Some(&PointZ::new(1.0, 4.0, 1.2, 4.2)));
    /// assert_eq!(multipointz.point(2), None);
    /// ```
    #[inline]
    pub fn point(&self, index: usize) -> Option<&PointType> {
        self.points.get(index)
    }

    /// Consumes the shape, returning the points
    #[inline]
    pub fn into_inner(self) -> Vec<PointType> {
        self.points
    }
}

impl<PointType> From<Vec<PointType>> for GenericMultipoint<PointType>
where
    PointType: ShrinkablePoint + GrowablePoint + Copy,
{
    fn from(points: Vec<PointType>) -> Self {
        Self::new(points)
    }
}

impl<PointType, I: SliceIndex<[PointType]>> Index<I> for GenericMultipoint<PointType> {
    type Output = I::Output;

    #[inline]
    fn index(&self, index: I) -> &Self::Output {
        Index::index(&self.points, index)
    }
}

// We do this because we can't use generics:
// error[E0210]: type parameter `PointType` must be used as the type parameter for some local type
// (e.g., `MyStruct<PointType>`)
macro_rules! impl_from_multipoint_to_vec_for_point_type {
    ($PointType:ty) => {
        impl From<GenericMultipoint<$PointType>> for Vec<$PointType> {
            fn from(multipoints: GenericMultipoint<$PointType>) -> Self {
                multipoints.points
            }
        }
    };
}

impl_from_multipoint_to_vec_for_point_type!(Point);
impl_from_multipoint_to_vec_for_point_type!(PointM);
impl_from_multipoint_to_vec_for_point_type!(PointZ);

#[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(geo_types::Point::from)
            .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>> + ShrinkablePoint + GrowablePoint + Copy,
{
    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 mut bbox = GenericBBox::<Point>::default();
        bbox_read_xy_from(&mut bbox, 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, dest: &mut T) -> Result<(), Error> {
        bbox_write_xy_to(&self.bbox, dest)?;
        dest.write_i32::<LittleEndian>(self.points.len() as i32)?;
        for point in self.points.iter() {
            dest.write_f64::<LittleEndian>(point.x)?;
            dest.write_f64::<LittleEndian>(point.y)?;
        }
        Ok(())
    }
}

impl EsriShape for Multipoint {
    fn x_range(&self) -> [f64; 2] {
        self.bbox.x_range()
    }

    fn y_range(&self) -> [f64; 2] {
        self.bbox.y_range()
    }
}

/*
 * 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 mut bbox = GenericBBox::<PointM>::default();
        bbox_read_xy_from(&mut bbox, 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 {
                bbox_read_m_range_from(&mut bbox, 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> {
        bbox_write_xy_to(&self.bbox, dest)?;
        dest.write_i32::<LittleEndian>(self.points.len() as i32)?;

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

        bbox_write_m_range_to(&self.bbox, dest)?;
        write_ms(&mut dest, &self.points)?;
        Ok(())
    }
}

impl EsriShape for MultipointM {
    fn x_range(&self) -> [f64; 2] {
        self.bbox.x_range()
    }

    fn y_range(&self) -> [f64; 2] {
        self.bbox.y_range()
    }

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

/*
 * 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 mut bbox = GenericBBox::<PointZ>::default();
        bbox_read_xy_from(&mut bbox, 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)?;

            bbox_read_z_range_from(&mut bbox, source)?;
            read_zs_into(&mut source, &mut points)?;

            if m_is_used {
                bbox_read_m_range_from(&mut bbox, 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> {
        bbox_write_xy_to(&self.bbox, dest)?;
        dest.write_i32::<LittleEndian>(self.points.len() as i32)?;

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

        bbox_write_z_range_to(&self.bbox, dest)?;
        write_zs(&mut dest, &self.points)?;

        bbox_write_m_range_to(&self.bbox, dest)?;
        write_ms(&mut dest, &self.points)?;

        Ok(())
    }
}

impl EsriShape for MultipointZ {
    fn x_range(&self) -> [f64; 2] {
        self.bbox.x_range()
    }

    fn y_range(&self) -> [f64; 2] {
        self.bbox.y_range()
    }

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

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

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

    #[test]
    fn test_multipoint_to_geo_types_multipoint() {
        let shapefile_points = vec![Point::new(1.0, 1.0), Point::new(2.0, 2.0)];
        let geo_types_coords = shapefile_points
            .iter()
            .copied()
            .map(Coordinate::<f64>::from)
            .collect::<Vec<Coordinate<f64>>>();

        let expected_shapefile_multipoint = Multipoint::new(shapefile_points);
        let expected_geo_types_multipoint = geo_types::MultiPoint::from(geo_types_coords);

        let geo_types_multipoint: geo_types::MultiPoint<f64> =
            expected_shapefile_multipoint.clone().into();
        let shapefile_multipoint: Multipoint = expected_geo_types_multipoint.clone().into();

        assert_eq!(geo_types_multipoint, expected_geo_types_multipoint);
        assert_eq!(shapefile_multipoint, expected_shapefile_multipoint);
    }

    #[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);
    }
}

#[cfg(test)]
mod tests {
    use {MultipointZ, PointZ};

    #[test]
    fn test_multipoint_index() {
        let points = vec![
            PointZ::new(1.0, 1.0, 17.0, 18.0),
            PointZ::new(2.0, 2.0, 15.0, 16.0),
        ];
        let multipoint = MultipointZ::new(points.clone());

        assert_eq!(multipoint[0], points[0]);
        assert_eq!(multipoint[1], points[1]);

        assert_eq!(multipoint[..1], points[..1]);
    }
}