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
//! Module with the definition of Polyline, PolylineM, PolylineZ

use std::fmt;
use std::io::{Read, Write};
use std::mem::size_of;

use record::io::*;
use record::traits::{GrowablePoint, ShrinkablePoint};
use record::ConcreteReadableShape;
use record::GenericBBox;
use record::{EsriShape, HasShapeType, WritableShape};
use record::{Point, PointM, PointZ};
use {Error, ShapeType};

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

/// Generic struct to create Polyline; PolylineM, PolylineZ
///
/// Polylines can have multiple parts.
///
/// Polylines parts must have 2 at least 2 points
///
/// To create a polyline with only one part use [`new`],
/// to create a polyline with multiple parts use [`with_parts`]
///
/// # geo-types
///
/// shapefile's Polyline can be converted to geo_types's `MultiLineString<f64>`
///
/// geo-types's `Line`, `LineString`, `MultiLineString` can be converted to shapefile's Polyline
/// ```
/// # #[cfg(feature = "geo-types")]
/// # fn main() -> Result<(), shapefile::Error>{
/// let mut polylines = shapefile::read_shapes_as::<_, shapefile::Polyline>("tests/data/line.shp")?;
/// let geo_polyline: geo_types::MultiLineString<f64> = polylines.pop().unwrap().into();
/// let polyline = shapefile::Polyline::from(geo_polyline);
/// # Ok(())
/// # }
/// # #[cfg(not(feature = "geo-types"))]
/// # fn main() {}
/// ```
///
/// [`new`]: #method.new
/// [`with_parts`]: #method.with_parts
#[derive(Debug, Clone, PartialEq)]
pub struct GenericPolyline<PointType> {
    pub(crate) bbox: GenericBBox<PointType>,
    pub(crate) parts: Vec<Vec<PointType>>,
}

/// Creating a Polyline
impl<PointType: ShrinkablePoint + GrowablePoint + Copy> GenericPolyline<PointType> {
    /// # Examples
    ///
    /// Polyline with single part
    /// ```
    /// use shapefile::{Point, Polyline};
    /// let points = vec![
    ///     Point::new(1.0, 1.0),
    ///     Point::new(2.0, 2.0),
    /// ];
    /// let poly = Polyline::new(points);
    /// ```
    ///
    /// # panic
    ///
    /// This will panic if the vec has less than 2 points
    pub fn new(points: Vec<PointType>) -> Self {
        assert!(
            points.len() >= 2,
            "Polylines parts must have at least 2 points"
        );
        Self {
            bbox: GenericBBox::<PointType>::from_points(&points),
            parts: vec![points],
        }
    }

    /// # Examples
    ///
    /// Polyline with multiple parts
    /// ```
    /// use shapefile::{Point, Polyline};
    /// let first_part = vec![
    ///     Point::new(1.0, 1.0),
    ///     Point::new(2.0, 2.0),
    /// ];
    ///
    /// let second_part = vec![
    ///     Point::new(3.0, 1.0),
    ///     Point::new(5.0, 6.0),
    /// ];
    ///
    /// let third_part = vec![
    ///     Point::new(17.0, 15.0),
    ///     Point::new(18.0, 19.0),
    ///     Point::new(20.0, 19.0),
    /// ];
    /// let poly = Polyline::with_parts(vec![first_part, second_part, third_part]);
    /// ```
    ///
    /// # panic
    ///
    /// This will panic if any of the parts are less than 2 points
    pub fn with_parts(parts: Vec<Vec<PointType>>) -> Self {
        assert!(
            parts.iter().all(|p| p.len() >= 2),
            "Polylines parts must have at least 2 points"
        );
        Self {
            bbox: GenericBBox::<PointType>::from_parts(&parts),
            parts,
        }
    }
}

impl<PointType> GenericPolyline<PointType> {
    /// Returns the bounding box associated to the polyline
    #[inline]
    pub fn bbox(&self) -> &GenericBBox<PointType> {
        &self.bbox
    }

    /// Returns a reference to all the parts
    #[inline]
    pub fn parts(&self) -> &Vec<Vec<PointType>> {
        &self.parts
    }

    /// Returns a reference to a part
    #[inline]
    pub fn part(&self, index: usize) -> Option<&Vec<PointType>> {
        self.parts.get(index)
    }

    /// Consumes the polyline and returns the parts
    #[inline]
    pub fn into_inner(self) -> Vec<Vec<PointType>> {
        self.parts
    }

    /// Returns the number of points contained in all the parts
    #[inline]
    pub fn total_point_count(&self) -> usize {
        self.parts.iter().map(|part| part.len()).sum()
    }
}

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

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

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

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

impl ConcreteReadableShape for Polyline {
    fn read_shape_content<T: Read>(source: &mut T, record_size: i32) -> Result<Self, Error> {
        let rdr = MultiPartShapeReader::<Point, T>::new(source)?;
        if record_size != Self::size_of_record(rdr.num_points, rdr.num_parts) as i32 {
            Err(Error::InvalidShapeRecordSize)
        } else {
            rdr.read_xy().map_err(Error::IoError).and_then(|rdr| {
                Ok(Self {
                    bbox: rdr.bbox,
                    parts: rdr.parts,
                })
            })
        }
    }
}

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

    fn write_to<T: Write>(&self, dest: &mut T) -> Result<(), Error> {
        let parts_iter = self.parts.iter().map(|part| part.as_slice());
        let writer = MultiPartShapeWriter::new(&self.bbox, parts_iter, dest);
        writer.write_point_shape()?;
        Ok(())
    }
}

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

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

/*
 * PolylineM
 */

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

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

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

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

impl ConcreteReadableShape for PolylineM {
    fn read_shape_content<T: Read>(source: &mut T, record_size: i32) -> Result<Self, Error> {
        let rdr = MultiPartShapeReader::<PointM, T>::new(source)?;

        let record_size_with_m = Self::size_of_record(rdr.num_points, rdr.num_parts, true) as i32;
        let record_size_without_m =
            Self::size_of_record(rdr.num_points, rdr.num_parts, false) as i32;

        if (record_size != record_size_with_m) && (record_size != record_size_without_m) {
            Err(Error::InvalidShapeRecordSize)
        } else {
            rdr.read_xy()
                .and_then(|rdr| rdr.read_ms_if(record_size == record_size_with_m))
                .map_err(Error::IoError)
                .and_then(|rdr| {
                    Ok(Self {
                        bbox: rdr.bbox,
                        parts: rdr.parts,
                    })
                })
        }
    }
}

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

    fn write_to<T: Write>(&self, dest: &mut T) -> Result<(), Error> {
        let parts_iter = self.parts.iter().map(|part| part.as_slice());
        let writer = MultiPartShapeWriter::new(&self.bbox, parts_iter, dest);
        writer.write_point_m_shape()?;
        Ok(())
    }
}

impl EsriShape for PolylineM {
    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()
    }
}

/*
 * PolylineZ
 */

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

impl PolylineZ {
    pub(crate) fn size_of_record(num_points: i32, num_parts: i32, is_m_used: bool) -> usize {
        let mut size = Polyline::size_of_record(num_points, num_parts);
        size += 2 * size_of::<f64>(); // ZRange
        size += num_points as usize * size_of::<f64>(); // Z
        if is_m_used {
            size += 2 * size_of::<f64>(); // MRange
            size += num_points as usize * size_of::<f64>(); // M
        }
        size
    }
}

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

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

impl ConcreteReadableShape for PolylineZ {
    fn read_shape_content<T: Read>(source: &mut T, record_size: i32) -> Result<Self, Error> {
        let rdr = MultiPartShapeReader::<PointZ, T>::new(source)?;

        let record_size_with_m = Self::size_of_record(rdr.num_points, rdr.num_parts, true) as i32;
        let record_size_without_m =
            Self::size_of_record(rdr.num_points, rdr.num_parts, false) as i32;

        if (record_size != record_size_with_m) && (record_size != record_size_without_m) {
            Err(Error::InvalidShapeRecordSize)
        } else {
            rdr.read_xy()
                .and_then(|rdr| rdr.read_zs())
                .and_then(|rdr| rdr.read_ms_if(record_size == record_size_with_m))
                .map_err(Error::IoError)
                .and_then(|rdr| {
                    Ok(Self {
                        bbox: rdr.bbox,
                        parts: rdr.parts,
                    })
                })
        }
    }
}

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

    fn write_to<T: Write>(&self, dest: &mut T) -> Result<(), Error> {
        let parts_iter = self.parts.iter().map(|part| part.as_slice());
        let writer = MultiPartShapeWriter::new(&self.bbox, parts_iter, dest);
        writer.write_point_z_shape()?;
        Ok(())
    }
}

impl EsriShape for PolylineZ {
    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(feature = "geo-types")]
impl<PointType> From<GenericPolyline<PointType>> for geo_types::MultiLineString<f64>
where
    PointType: Copy,
    geo_types::Coordinate<f64>: From<PointType>,
{
    fn from(polyline: GenericPolyline<PointType>) -> Self {
        use std::iter::FromIterator;
        let mut lines = Vec::<geo_types::LineString<f64>>::with_capacity(polyline.parts().len());

        for points in polyline.parts {
            let line: Vec<geo_types::Coordinate<f64>> = points
                .into_iter()
                .map(geo_types::Coordinate::<f64>::from)
                .collect();
            lines.push(line.into());
        }
        geo_types::MultiLineString::<f64>::from_iter(lines.into_iter())
    }
}

#[cfg(feature = "geo-types")]
impl<PointType> From<geo_types::Line<f64>> for GenericPolyline<PointType>
where
    PointType: From<geo_types::Point<f64>> + ShrinkablePoint + GrowablePoint + Copy,
{
    fn from(line: geo_types::Line<f64>) -> Self {
        let (p1, p2) = line.points();
        Self::new(vec![PointType::from(p1), PointType::from(p2)])
    }
}

#[cfg(feature = "geo-types")]
impl<PointType> From<geo_types::LineString<f64>> for GenericPolyline<PointType>
where
    PointType: From<geo_types::Coordinate<f64>> + ShrinkablePoint + GrowablePoint + Copy,
{
    fn from(line: geo_types::LineString<f64>) -> Self {
        let points: Vec<PointType> = line.into_iter().map(PointType::from).collect();
        Self::new(points)
    }
}

#[cfg(feature = "geo-types")]
impl<PointType> From<geo_types::MultiLineString<f64>> for GenericPolyline<PointType>
where
    PointType: From<geo_types::Coordinate<f64>> + ShrinkablePoint + GrowablePoint + Copy,
{
    fn from(mls: geo_types::MultiLineString<f64>) -> Self {
        let mut parts = Vec::<Vec<PointType>>::with_capacity(mls.0.len());
        for linestring in mls.0.into_iter() {
            parts.push(linestring.into_iter().map(PointType::from).collect());
        }
        Self::with_parts(parts)
    }
}

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

    #[test]
    #[should_panic(expected = "Polylines parts must have at least 2 points")]
    fn test_polyline_new_less_than_2_points() {
        let _polyline = Polyline::new(vec![Point::new(1.0, 1.0)]);
    }

    #[test]
    #[should_panic(expected = "Polylines parts must have at least 2 points")]
    fn test_polyline_with_parts_less_than_2_points() {
        let _polyline = Polyline::with_parts(vec![
            vec![Point::new(1.0, 1.0), Point::new(2.0, 2.0)],
            vec![Point::new(1.0, 1.0)],
        ]);
    }
}

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

    #[test]
    fn test_polyline_into_multiline_string() {
        let polyline_m = PolylineM::with_parts(vec![
            vec![
                PointM::new(1.0, 5.0, 0.0),
                PointM::new(5.0, 5.0, NO_DATA),
                PointM::new(5.0, 1.0, 3.0),
            ],
            vec![PointM::new(1.0, 5.0, 0.0), PointM::new(1.0, 1.0, 0.0)],
        ]);

        let multiline_string: MultiLineString<f64> = polyline_m.into();

        let expected_multiline = geo_types::MultiLineString(vec![
            LineString::<f64>(vec![
                Coordinate { x: 1.0, y: 5.0 },
                Coordinate { x: 5.0, y: 5.0 },
                Coordinate { x: 5.0, y: 1.0 },
            ]),
            LineString::<f64>(vec![
                Coordinate { x: 1.0, y: 5.0 },
                Coordinate { x: 1.0, y: 1.0 },
            ]),
        ]);
        assert_eq!(multiline_string, expected_multiline);
    }

    #[test]
    fn test_line_into_polyline() {
        let line = geo_types::Line::new(
            Coordinate { x: 2.0, y: 3.0 },
            Coordinate { x: 6.0, y: -6.0 },
        );
        let polyline: PolylineZ = line.into();

        assert_eq!(
            polyline.parts,
            vec![vec![
                PointZ::new(2.0, 3.0, 0.0, NO_DATA),
                PointZ::new(6.0, -6.0, 0.0, NO_DATA)
            ]]
        );
    }

    #[test]
    fn test_linestring_into_polyline() {
        let linestring = LineString::from(vec![
            Coordinate { x: 1.0, y: 5.0 },
            Coordinate { x: 5.0, y: 5.0 },
            Coordinate { x: 5.0, y: 1.0 },
        ]);

        let polyline: Polyline = linestring.into();
        assert_eq!(
            polyline.parts,
            vec![vec![
                Point::new(1.0, 5.0),
                Point::new(5.0, 5.0),
                Point::new(5.0, 1.0),
            ]]
        )
    }

    #[test]
    fn test_multi_line_string_into_polyline() {
        let multiline_string = geo_types::MultiLineString(vec![
            LineString::<f64>(vec![
                Coordinate { x: 1.0, y: 5.0 },
                Coordinate { x: 5.0, y: 5.0 },
                Coordinate { x: 5.0, y: 1.0 },
            ]),
            LineString::<f64>(vec![
                Coordinate { x: 1.0, y: 5.0 },
                Coordinate { x: 1.0, y: 1.0 },
            ]),
        ]);

        let expected_polyline_z = PolylineZ::with_parts(vec![
            vec![
                PointZ::new(1.0, 5.0, 0.0, NO_DATA),
                PointZ::new(5.0, 5.0, 0.0, NO_DATA),
                PointZ::new(5.0, 1.0, 0.0, NO_DATA),
            ],
            vec![
                PointZ::new(1.0, 5.0, 0.0, NO_DATA),
                PointZ::new(1.0, 1.0, 0.0, NO_DATA),
            ],
        ]);

        let polyline_z: PolylineZ = multiline_string.into();
        assert_eq!(polyline_z, expected_polyline_z);
    }
}