planar_geo 0.4.0

A Rust library for 2D geometry: geometric objects, algorithms and visualization
Documentation
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
/*!
A module containing the [`Segment`] enum and various helper structs.

The [`Segment`] enum contains the segment variants available in this crate, such
as the [`ArcSegment`] or the [`LineSegment`]. A segment is a directed line
connecting a start to an end point. All types in this crate are two-dimensional
(planar), meaning that start and end points consist of two values (`[f64; 2]`),
where the first element is interpreted as the `x` value and the second element
is interpreted as the `y` value in the underlying cartesian coordinate system.

Multiple connected segments form a
[`Polysegment`](crate::polysegment::Polysegment), which in turn is
used to define [`Contour`](crate::contour::Contour)s and by extension
[`Shape`](crate::shape::Shape)s, the [`Composite`](crate::composite::Composite)
types of this crate. However, segments can also used on their own to e.g.
calculate properties or finding intersections. They implement the [`Primitive`]
trait, which provides various methods shared with other primitive geometric
types such as [`Line`](crate::line::Line)s and points (`[f64; 2]`).
*/

use bounding_box::{BoundingBox, ToBoundingBox};
pub mod arc_segment;
pub mod line_segment;
pub use arc_segment::*;
pub use line_segment::*;

#[cfg(feature = "serde")]
use serde::Serialize;

#[cfg(feature = "serde")]
use deserialize_untagged_verbose_error::DeserializeUntaggedVerboseError;

use crate::{
    primitive::{Primitive, PrimitiveIntersections},
    {CentroidData, Transformation},
};

/**
A directed connection between a start and an end point, which can take different
paths depending on the variant. All methods of [`Segment`] delegate to the
corresponding function of the underlying variant.

*/
#[doc = ""]
#[cfg_attr(feature = "doc-images", doc = "![Segments example][example_segments]")]
#[cfg_attr(
    feature = "doc-images",
    embed_doc_image::embed_doc_image("example_segments", "docs/img/example_segments.svg")
)]
#[cfg_attr(
    not(feature = "doc-images"),
    doc = "**Doc images not enabled**. Compile docs with
    `cargo doc --features 'doc-images'` and Rust version >= 1.54."
)]
/**

See the [module-level](crate::segment) docstring for more.

# Serialization and deserialization

When the `serde` feature is enabled, segments can be serialized and deserialized
using the [`serde`] crate. The enum is treated as untagged, meaning that the
serialized representation of a segment is identical to that of the segment
variant it contains ([`LineSegment`] or [`ArcSegment`]). See [`serde`]s
documentation for more.
 */
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, DeserializeUntaggedVerboseError))]
#[cfg_attr(feature = "serde", serde(untagged))]
pub enum Segment {
    /// A straight line segment between a start and an end point. See the
    /// docstring of [`LineSegment`].
    LineSegment(LineSegment),
    /// An arc segment between a start and an end point. See the docstring of
    /// [`ArcSegment`].
    ArcSegment(ArcSegment),
}

impl Segment {
    /**
    Returns the start point of the underlying segment variant.
     */
    pub fn start(&self) -> [f64; 2] {
        match self {
            Segment::LineSegment(line_segment) => line_segment.start(),
            Segment::ArcSegment(arc_segment) => arc_segment.start(),
        }
    }

    /**
    Returns the end / stop point of the underlying segment variant.
     */
    pub fn end(&self) -> [f64; 2] {
        match self {
            Segment::LineSegment(line_segment) => line_segment.stop(),
            Segment::ArcSegment(arc_segment) => arc_segment.stop(),
        }
    }

    /**
    Returns the end / stop point of the underlying segment variant. This is an
    alias for [`Segment::end`].
     */
    pub fn stop(&self) -> [f64; 2] {
        return self.end();
    }

    /**
    Returns the number of points of the underlying variant.
     */
    pub fn number_points(&self) -> usize {
        match self {
            Segment::LineSegment(line_segment) => line_segment.number_points(),
            Segment::ArcSegment(arc_segment) => arc_segment.number_points(),
        }
    }

    /**
    Returns the length of the underlying line / arc segment.

    # Examples

    ```
    use std::f64::consts::PI;
    use planar_geo::prelude::*;

    let ls = LineSegment::new([0.0, 0.0], [0.0, 2.0], 0.0, 0).unwrap();
    assert_eq!(ls.length(), 2.0);
    let s = Segment::from(ls);
    assert_eq!(s.length(), 2.0);

    let arc = ArcSegment::from_center_radius_start_offset_angle(
            [0.0, 0.0],
            2.0,
            0.0,
            PI,
            DEFAULT_EPSILON,
            DEFAULT_MAX_ULPS,
        )
        .unwrap();
    approx::assert_abs_diff_eq!(arc.length(), 2.0 * PI);
    let s = Segment::from(arc);
    approx::assert_abs_diff_eq!(s.length(), 2.0 * PI);
    ```
     */
    pub fn length(&self) -> f64 {
        match self {
            Segment::LineSegment(line_segment) => line_segment.length(),
            Segment::ArcSegment(arc_segment) => arc_segment.length(),
        }
    }

    /**
    Reverses the underlying segment, i.e. switching the segment direction.
     */
    pub fn reverse(&mut self) {
        match self {
            Segment::LineSegment(line_segment) => line_segment.reverse(),
            Segment::ArcSegment(arc_segment) => arc_segment.reverse(),
        }
    }

    /**
    Returns a point on the segment defined by its normalized position on it.

    For example, `normalized = 0` returns the start point, `normalized = 1`
    returns the end point and `normalized = 0.5` returns the middle point of the
    segment. The input `normalized` is clamped to [0, 1].

    # Examples

    ```
    use planar_geo::prelude::*;
    let ls = LineSegment::new([0.0, 0.0], [0.0, 2.0], 0.0, 0).unwrap();
    let s = Segment::from(ls);

    assert_eq!(s.segment_point(0.0), s.start());
    assert_eq!(s.segment_point(-10.0), s.start());

    assert_eq!(s.segment_point(1.0), s.stop());
    assert_eq!(s.segment_point(10.0), s.stop());

    assert_eq!(s.segment_point(0.5), [0.0, 1.0]);
    ```
    */
    pub fn segment_point(&self, normalized: f64) -> [f64; 2] {
        match self {
            Segment::LineSegment(line_segment) => line_segment.segment_point(normalized),
            Segment::ArcSegment(arc_segment) => arc_segment.segment_point(normalized),
        }
    }

    /**
    Returns the points of a polygon polysegment which approximates `self`.

    The number  of points is defined by the [`SegmentPolygonizer`] (see its
    docstring). The points are regularily distributed over the segment, which
    means that two subsequent points always have the same euclidian distance
    from each other.

    # Examples

    ```
    use std::f64::consts::FRAC_PI_2;
    use planar_geo::prelude::*;

    // Approximate an arc segment from 0 to 90 degrees by four straight
    // segments (five points). The returned points are regularily distributed
    // over the arc.
    let arc = ArcSegment::from_center_radius_start_offset_angle(
            [0.0, 0.0],
            1.0,
            0.0,
            FRAC_PI_2,
            DEFAULT_EPSILON,
            DEFAULT_MAX_ULPS,
        )
        .unwrap();
    let s = Segment::from(arc);
    let mut iter = s.polygonize(SegmentPolygonizer::InnerSegments(4));

    assert_eq!(iter.next(), Some(s.segment_point(0.0)));
    assert_eq!(iter.next(), Some(s.segment_point(0.25)));
    assert_eq!(iter.next(), Some(s.segment_point(0.5)));
    assert_eq!(iter.next(), Some(s.segment_point(0.75)));
    assert_eq!(iter.next(), Some(s.segment_point(1.0)));
    assert!(iter.next().is_none());
    ```
     */
    pub fn polygonize<'a>(&'a self, polygonizer: SegmentPolygonizer) -> PolygonPointsIterator<'a> {
        match self {
            Segment::LineSegment(line_segment) => line_segment.polygonize(polygonizer),
            Segment::ArcSegment(arc_segment) => arc_segment.polygonize(polygonizer),
        }
    }

    /**
    Returns the centroid (center of mass) of the segment.

    # Examples

    ```
    use std::f64::consts::PI;
    use planar_geo::prelude::*;

    let arc = ArcSegment::from_center_radius_start_offset_angle(
            [0.0, 0.0],
            2.0,
            0.0,
            PI,
            DEFAULT_EPSILON,
            DEFAULT_MAX_ULPS,
        )
        .unwrap();
    let s = Segment::from(arc);
    approx::assert_abs_diff_eq!(s.centroid(), [0.0, 0.8488263631567751]);
    ```
     */
    pub fn centroid(&self) -> [f64; 2] {
        return CentroidData::from(self).into();
    }

    /**
    Switches start and end / stop points of `self`.

    # Examples

    ```
    use planar_geo::prelude::*;

    let mut s: Segment = LineSegment::new([0.0, 0.0], [2.0, 0.0], 0.0, 0).unwrap().into();
    assert_eq!(s.start(), [0.0, 0.0]);
    assert_eq!(s.stop(), [2.0, 0.0]);

    s.invert();
    assert_eq!(s.start(), [2.0, 0.0]);
    assert_eq!(s.stop(), [0.0, 0.0]);

    s.invert();
    assert_eq!(s.start(), [0.0, 0.0]);
    assert_eq!(s.stop(), [2.0, 0.0]);
    ```
     */
    pub fn invert(&mut self) {
        match self {
            Segment::LineSegment(s) => s.invert(),
            Segment::ArcSegment(s) => s.invert(),
        }
    }

    /**
    Returns whether `self` and `other` are touching.

    Two segments are touching if they are intersecting but not dividing each
    other. Depending on the type of `self`, this function forwards to
    [`LineSegment::touches_segment`] or [`ArcSegment::touches_segment`], see
    their respective docstrings for further explanation and examples.
     */
    pub fn touches_segment<'a, T: Into<SegmentRef<'a>>>(
        &self,
        other: T,
        epsilon: f64,
        max_ulps: u32,
    ) -> bool {
        match self {
            Segment::LineSegment(line_segment) => {
                line_segment.touches_segment(other, epsilon, max_ulps)
            }
            Segment::ArcSegment(arc_segment) => {
                arc_segment.touches_segment(other, epsilon, max_ulps)
            }
        }
    }
}

impl Transformation for Segment {
    fn translate(&mut self, shift: [f64; 2]) {
        match self {
            Segment::LineSegment(obj) => obj.translate(shift),
            Segment::ArcSegment(obj) => obj.translate(shift),
        }
    }

    fn rotate(&mut self, center: [f64; 2], angle: f64) {
        match self {
            Segment::LineSegment(obj) => obj.rotate(center, angle),
            Segment::ArcSegment(obj) => obj.rotate(center, angle),
        }
    }

    fn scale(&mut self, factor: f64) {
        match self {
            Segment::LineSegment(obj) => obj.scale(factor),
            Segment::ArcSegment(obj) => obj.scale(factor),
        }
    }

    fn line_reflection(&mut self, start: [f64; 2], stop: [f64; 2]) -> () {
        match self {
            Segment::LineSegment(obj) => obj.line_reflection(start, stop),
            Segment::ArcSegment(obj) => obj.line_reflection(start, stop),
        }
    }
}

impl crate::primitive::private::Sealed for Segment {}

impl Primitive for Segment {
    fn covers_point(&self, point: [f64; 2], epsilon: f64, max_ulps: u32) -> bool {
        match self {
            Segment::LineSegment(s) => s.covers_point(point, epsilon, max_ulps),
            Segment::ArcSegment(s) => s.covers_point(point, epsilon, max_ulps),
        }
    }

    fn covers_arc_segment(&self, arc_segment: &ArcSegment, epsilon: f64, max_ulps: u32) -> bool {
        match self {
            Segment::LineSegment(_) => return false,
            Segment::ArcSegment(this) => {
                return this.covers_arc_segment(arc_segment, epsilon, max_ulps);
            }
        }
    }

    fn covers_line_segment(&self, line_segment: &LineSegment, epsilon: f64, max_ulps: u32) -> bool {
        match self {
            Segment::LineSegment(this) => {
                return this.covers_line_segment(line_segment, epsilon, max_ulps);
            }
            Segment::ArcSegment(_) => return false,
        }
    }

    fn covers_line(&self, _line: &crate::line::Line, _epsilon: f64, _max_ulps: u32) -> bool {
        return false;
    }

    fn intersections_line(
        &self,
        line: &crate::line::Line,
        epsilon: f64,
        max_ulps: u32,
    ) -> PrimitiveIntersections {
        match self {
            Segment::LineSegment(s) => s.intersections_line(line, epsilon, max_ulps),
            Segment::ArcSegment(s) => s.intersections_line(line, epsilon, max_ulps),
        }
    }

    fn intersections_line_segment(
        &self,
        line_segment: &LineSegment,
        epsilon: f64,
        max_ulps: u32,
    ) -> PrimitiveIntersections {
        match self {
            Segment::LineSegment(s) => {
                s.intersections_line_segment(line_segment, epsilon, max_ulps)
            }
            Segment::ArcSegment(s) => s.intersections_line_segment(line_segment, epsilon, max_ulps),
        }
    }

    fn intersections_arc_segment(
        &self,
        arc_segment: &ArcSegment,
        epsilon: f64,
        max_ulps: u32,
    ) -> PrimitiveIntersections {
        match self {
            Segment::LineSegment(s) => s.intersections_arc_segment(arc_segment, epsilon, max_ulps),
            Segment::ArcSegment(s) => s.intersections_arc_segment(arc_segment, epsilon, max_ulps),
        }
    }

    fn intersections_primitive<T: Primitive>(
        &self,
        other: &T,
        epsilon: f64,
        max_ulps: u32,
    ) -> PrimitiveIntersections {
        other.intersections_segment(self, epsilon, max_ulps)
    }
}

impl ToBoundingBox for Segment {
    fn bounding_box(&self) -> BoundingBox {
        match self {
            Segment::LineSegment(s) => s.bounding_box(),
            Segment::ArcSegment(s) => s.bounding_box(),
        }
    }
}

impl From<&Segment> for CentroidData {
    fn from(value: &Segment) -> Self {
        match value {
            Segment::LineSegment(line_segment) => line_segment.into(),
            Segment::ArcSegment(arc_segment) => arc_segment.into(),
        }
    }
}

impl From<LineSegment> for Segment {
    fn from(value: LineSegment) -> Self {
        return Self::LineSegment(value);
    }
}

impl From<ArcSegment> for Segment {
    fn from(value: ArcSegment) -> Self {
        return Self::ArcSegment(value);
    }
}

/**
This enum defines how many points should be in the polygonized representation
of a segment (created by [`Segment::polygonize`]). Depending on the selected
variant and its parametrization, a different number of points is created:
```
use std::f64::consts::PI;
use planar_geo::prelude::*;

let arc = ArcSegment::from_center_radius_start_offset_angle(
    [0.0, 0.0],
    1.0,
    1.25 * PI,
    0.75 * PI,
    DEFAULT_EPSILON,
    DEFAULT_MAX_ULPS,
)
.unwrap();
let s = Segment::from(arc);

// One segment (red line in the image below this code snippet)
let iter = s.polygonize(SegmentPolygonizer::MaximumSegmentLength(10.0));
assert_eq!(iter.count(), 2);

// Two segments (green line in the image below this code snippet)
let iter = s.polygonize(SegmentPolygonizer::MaximumAngle(0.5 * PI));
assert_eq!(iter.count(), 3);

// Three segments (blue line in the image below this code snippet)
let iter = s.polygonize(SegmentPolygonizer::InnerSegments(3));
assert_eq!(iter.count(), 4);
```
*/
#[doc = ""]
#[cfg_attr(feature = "doc-images", doc = "![Polygonized arc][polygonized_arc]")]
#[cfg_attr(
    feature = "doc-images",
    embed_doc_image::embed_doc_image("polygonized_arc", "docs/img/polygonized_arc.svg")
)]
#[cfg_attr(
    not(feature = "doc-images"),
    doc = "**Doc images not enabled**. Compile docs with
    `cargo doc --features 'doc-images'` and Rust version >= 1.54."
)]
#[derive(Debug, Clone, Copy)]
pub enum SegmentPolygonizer {
    /**
    Inner of line segments of the polygon polysegments given explicitly
    -> Inner of points is equal to this plus one (end point of the last
    segment). If the number of line segments is specified to be 0, only the
    start point of the input is returned.
     */
    InnerSegments(usize),
    /**
    The given number is the upper limit for the allowed length of the line
    segments. The algorithm then calculates the fewest number of line segments
    possible where this constraint is fulfilled and returns the respective
    points. If the given value is zero or negative, only the start point is
    returned.
     */
    MaximumSegmentLength(f64),
    /**
    If applied to an [`ArcSegment`], this constraint limits the maximum angle
    which can be convered by a single line segment. The algorithm then
    calculates the fewest number of line segments possible where this constraint
    is fulfilled and returns the respective points. If the given value is
    zero or negative, only the start point is returned.
    If applied to a [`LineSegment`], only the start point is returned.
     */
    MaximumAngle(f64),
}

impl Default for SegmentPolygonizer {
    fn default() -> Self {
        return SegmentPolygonizer::InnerSegments(1);
    }
}

/**
The "borrowed" version of [`Segment`] which has the same variants as its
brother, but with references instead of owned instances of the underlying
segment types.

The main purpose of this type is to enable the usage of references for any
segment type ([`LineSegment`], [`ArcSegment`] or [`Segment`]) in function
interfaces. See for example the
[`Polygonizer::segment_polygonizer`](crate::composite::Polygonizer::segment_polygonizer)
method.
 */
#[derive(Clone, Debug)]
pub enum SegmentRef<'a> {
    /// A reference to a [`LineSegment`].
    LineSegment(&'a LineSegment),
    /// A reference to an [`ArcSegment`].
    ArcSegment(&'a ArcSegment),
}

impl<'a> From<&'a Segment> for SegmentRef<'a> {
    fn from(value: &'a Segment) -> Self {
        match value {
            Segment::LineSegment(v) => v.into(),
            Segment::ArcSegment(v) => v.into(),
        }
    }
}

impl<'a> From<&'a LineSegment> for SegmentRef<'a> {
    fn from(value: &'a LineSegment) -> Self {
        return Self::LineSegment(value);
    }
}

impl<'a> From<&'a ArcSegment> for SegmentRef<'a> {
    fn from(value: &'a ArcSegment) -> Self {
        return Self::ArcSegment(value);
    }
}

impl<'a> ToBoundingBox for SegmentRef<'a> {
    fn bounding_box(&self) -> BoundingBox {
        match self {
            SegmentRef::LineSegment(s) => s.bounding_box(),
            SegmentRef::ArcSegment(s) => s.bounding_box(),
        }
    }
}

impl<'a> SegmentRef<'a> {
    /**
    Returns the start point of the underlying segment variant.
     */
    pub fn start(&self) -> [f64; 2] {
        match self {
            SegmentRef::LineSegment(line_segment) => line_segment.start(),
            SegmentRef::ArcSegment(arc_segment) => arc_segment.start(),
        }
    }

    /**
    Returns the end / stop point of the underlying segment variant.
     */
    pub fn end(&self) -> [f64; 2] {
        match self {
            SegmentRef::LineSegment(line_segment) => line_segment.stop(),
            SegmentRef::ArcSegment(arc_segment) => arc_segment.stop(),
        }
    }

    /**
    Returns the end / stop point of the underlying segment variant. This is an
    alias for [`Segment::end`].
     */
    pub fn stop(&self) -> [f64; 2] {
        return self.end();
    }

    /**
    Returns the number of points of the underlying variant.
     */
    pub fn number_points(&self) -> usize {
        match self {
            SegmentRef::LineSegment(line_segment) => line_segment.number_points(),
            SegmentRef::ArcSegment(arc_segment) => arc_segment.number_points(),
        }
    }

    /**
    Returns the length of the underlying line / arc segment.

    See [`Segment::length`] for further explanation and examples.
     */
    pub fn length(&self) -> f64 {
        match self {
            SegmentRef::LineSegment(line_segment) => line_segment.length(),
            SegmentRef::ArcSegment(arc_segment) => arc_segment.length(),
        }
    }

    /**
    Returns a point on the segment defined by its normalized position on it.

    See [`Segment::segment_point`] for further explanation and examples.
    */
    pub fn segment_point(&self, normalized: f64) -> [f64; 2] {
        match self {
            SegmentRef::LineSegment(line_segment) => line_segment.segment_point(normalized),
            SegmentRef::ArcSegment(arc_segment) => arc_segment.segment_point(normalized),
        }
    }

    /**
    Returns the points of a polygon polysegment which approximates `self`.

    See [`Segment::polygonize`] for further explanation and examples.
     */
    pub fn polygonize(&self, polygonizer: SegmentPolygonizer) -> PolygonPointsIterator<'a> {
        match self {
            SegmentRef::LineSegment(line_segment) => line_segment.polygonize(polygonizer),
            SegmentRef::ArcSegment(arc_segment) => arc_segment.polygonize(polygonizer),
        }
    }

    /**
    Returns the centroid (center of mass) of the segment.

    See [`Segment::centroid`] for further explanation and examples.
     */
    pub fn centroid(&self) -> [f64; 2] {
        return CentroidData::from(self).into();
    }

    /**
    Returns whether `self` and `other` are touching.

    Two segments are touching if they are intersecting but not dividing each
    other. Depending on the type of `self`, this function forwards to
    [`LineSegment::touches_segment`] or [`ArcSegment::touches_segment`], see
    their respective docstrings for further explanation and examples.
     */
    pub fn touches_segment<'b, T: Into<SegmentRef<'b>>>(
        &self,
        other: T,
        epsilon: f64,
        max_ulps: u32,
    ) -> bool {
        match self {
            SegmentRef::LineSegment(line_segment) => {
                line_segment.touches_segment(other, epsilon, max_ulps)
            }
            SegmentRef::ArcSegment(arc_segment) => {
                arc_segment.touches_segment(other, epsilon, max_ulps)
            }
        }
    }
}

impl From<SegmentRef<'_>> for CentroidData {
    fn from(value: SegmentRef<'_>) -> Self {
        match value {
            SegmentRef::LineSegment(line_segment) => line_segment.into(),
            SegmentRef::ArcSegment(arc_segment) => arc_segment.into(),
        }
    }
}

impl From<&SegmentRef<'_>> for CentroidData {
    fn from(value: &SegmentRef) -> Self {
        match value {
            SegmentRef::LineSegment(line_segment) => (*line_segment).into(),
            SegmentRef::ArcSegment(arc_segment) => (*arc_segment).into(),
        }
    }
}

impl<'a> crate::primitive::private::Sealed for SegmentRef<'a> {}

impl<'a> Primitive for SegmentRef<'a> {
    fn covers_point(&self, point: [f64; 2], epsilon: f64, max_ulps: u32) -> bool {
        match self {
            SegmentRef::LineSegment(s) => s.covers_point(point, epsilon, max_ulps),
            SegmentRef::ArcSegment(s) => s.covers_point(point, epsilon, max_ulps),
        }
    }

    fn covers_arc_segment(&self, arc_segment: &ArcSegment, epsilon: f64, max_ulps: u32) -> bool {
        match self {
            SegmentRef::LineSegment(_) => return false,
            SegmentRef::ArcSegment(this) => {
                return this.covers_arc_segment(arc_segment, epsilon, max_ulps);
            }
        }
    }

    fn covers_line_segment(&self, line_segment: &LineSegment, epsilon: f64, max_ulps: u32) -> bool {
        match self {
            SegmentRef::LineSegment(this) => {
                return this.covers_line_segment(line_segment, epsilon, max_ulps);
            }
            SegmentRef::ArcSegment(_) => return false,
        }
    }

    fn covers_line(&self, _line: &crate::line::Line, _epsilon: f64, _max_ulps: u32) -> bool {
        return false;
    }

    fn intersections_line(
        &self,
        line: &crate::line::Line,
        epsilon: f64,
        max_ulps: u32,
    ) -> PrimitiveIntersections {
        match self {
            SegmentRef::LineSegment(s) => s.intersections_line(line, epsilon, max_ulps),
            SegmentRef::ArcSegment(s) => s.intersections_line(line, epsilon, max_ulps),
        }
    }

    fn intersections_line_segment(
        &self,
        line_segment: &LineSegment,
        epsilon: f64,
        max_ulps: u32,
    ) -> PrimitiveIntersections {
        match self {
            SegmentRef::LineSegment(s) => {
                s.intersections_line_segment(line_segment, epsilon, max_ulps)
            }
            SegmentRef::ArcSegment(s) => {
                s.intersections_line_segment(line_segment, epsilon, max_ulps)
            }
        }
    }

    fn intersections_arc_segment(
        &self,
        arc_segment: &ArcSegment,
        epsilon: f64,
        max_ulps: u32,
    ) -> PrimitiveIntersections {
        match self {
            SegmentRef::LineSegment(s) => {
                s.intersections_arc_segment(arc_segment, epsilon, max_ulps)
            }
            SegmentRef::ArcSegment(s) => {
                s.intersections_arc_segment(arc_segment, epsilon, max_ulps)
            }
        }
    }

    fn intersections_primitive<T: Primitive>(
        &self,
        other: &T,
        epsilon: f64,
        max_ulps: u32,
    ) -> PrimitiveIntersections {
        other.intersections_segment(self.clone(), epsilon, max_ulps)
    }
}

/**
An iterator created by calling [`Segment::polygonize`]. See the docstring of
[`SegmentPolygonizer`] for more.
 */
#[derive(Clone, Debug)]
pub struct PolygonPointsIterator<'a> {
    index: usize,
    num_segs: usize,
    segment: SegmentRef<'a>,
}

impl<'a> PolygonPointsIterator<'a> {
    pub(super) fn start_at_second_point(&mut self) {
        self.index = 1;
    }
    pub(super) fn skip_last_vertex(&mut self) {
        if self.num_segs > 0 {
            self.num_segs -= 1;
        }
    }
}

impl<'a> Iterator for PolygonPointsIterator<'a> {
    type Item = [f64; 2];

    fn next(&mut self) -> Option<Self::Item> {
        if self.index == self.num_segs + 1 {
            return None;
        }
        let point = match self.segment {
            SegmentRef::LineSegment(segment) => {
                let x = segment.start()[0]
                    + self.index as f64 / self.num_segs as f64
                        * (segment.stop()[0] - segment.start()[0]);
                let y = segment.start()[1]
                    + self.index as f64 / self.num_segs as f64
                        * (segment.stop()[1] - segment.start()[1]);
                [x, y]
            }
            SegmentRef::ArcSegment(segment) => {
                let angle = segment.start_angle()
                    + self.index as f64 / self.num_segs as f64 * segment.offset_angle();
                let mut center = segment.center();
                center.translate([
                    segment.radius() * angle.cos(),
                    segment.radius() * angle.sin(),
                ]);
                center
            }
        };

        self.index += 1;

        return Some(point);
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let length = self.num_segs + 1;
        (length, Some(length))
    }
}