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
#[cfg(feature = "serialize")]
#[macro_use]
extern crate serde;

extern crate coord_2d;
use coord_2d::Axis;
pub use coord_2d::Coord;

pub trait StepsTrait: Clone + Eq + private::Sealed {
    fn prev(&mut self) -> Coord;
    fn next(&mut self) -> Coord;
    fn prev_copy(&self) -> (Coord, Self) {
        let mut s = self.clone();
        (s.prev(), s)
    }
    fn next_copy(&self) -> (Coord, Self) {
        let mut s = self.clone();
        (s.next(), s)
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Steps {
    major_x: i8,
    major_y: i8,
    minor_x: i8,
    minor_y: i8,
    accumulator: i64,
    major_delta_abs: u32,
    minor_delta_abs: u32,
}

impl Steps {
    fn new_common<F: Fn(i8, i8, Axis) -> (Coord, Coord)>(delta: Coord, f: F) -> Self {
        let (major_axis, minor_axis) = if delta.x.abs() > delta.y.abs() {
            (Axis::X, Axis::Y)
        } else {
            (Axis::Y, Axis::X)
        };
        let major_sign = if delta.get(major_axis) < 0 { -1 } else { 1 };
        let minor_sign = if delta.get(minor_axis) < 0 { -1 } else { 1 };
        let (major_coord, minor_coord) = f(major_sign, minor_sign, major_axis);
        let (major_delta_abs, minor_delta_abs) = if delta == Coord::new(0, 0) {
            // this prevents traversal from looping forever
            (1, 1)
        } else {
            (
                delta.get(major_axis).abs() as u32,
                delta.get(minor_axis).abs() as u32,
            )
        };
        let accumulator = 0;
        let major_x = major_coord.x as i8;
        let major_y = major_coord.y as i8;
        let minor_x = minor_coord.x as i8;
        let minor_y = minor_coord.y as i8;
        Self {
            major_x,
            major_y,
            minor_x,
            minor_y,
            accumulator,
            major_delta_abs,
            minor_delta_abs,
        }
    }
    pub fn new(delta: Coord) -> Self {
        Self::new_common(delta, |major_sign, minor_sign, major_axis| {
            let major_coord = Coord::new_axis(major_sign as i32, 0, major_axis);
            let minor_coord = Coord::new_axis(major_sign as i32, minor_sign as i32, major_axis);
            (major_coord, minor_coord)
        })
    }
}

impl StepsTrait for Steps {
    fn prev(&mut self) -> Coord {
        self.accumulator -= self.minor_delta_abs as i64;
        if self.accumulator <= (self.major_delta_abs as i64 / 2) - self.major_delta_abs as i64 {
            self.accumulator += self.major_delta_abs as i64;
            Coord::new(-self.minor_x as i32, -self.minor_y as i32)
        } else {
            Coord::new(-self.major_x as i32, -self.major_y as i32)
        }
    }
    fn next(&mut self) -> Coord {
        self.accumulator += self.minor_delta_abs as i64;
        if self.accumulator > self.major_delta_abs as i64 / 2 {
            self.accumulator -= self.major_delta_abs as i64;
            Coord::new(self.minor_x as i32, self.minor_y as i32)
        } else {
            Coord::new(self.major_x as i32, self.major_y as i32)
        }
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StepsCardinal(Steps);

impl StepsCardinal {
    fn new(delta: Coord) -> Self {
        let steps = Steps::new_common(delta, |major_sign, minor_sign, major_axis| {
            let major_coord = Coord::new_axis(major_sign as i32, 0, major_axis);
            let minor_coord = Coord::new_axis(0, minor_sign as i32, major_axis);
            (major_coord, minor_coord)
        });
        StepsCardinal(steps)
    }
}

impl StepsTrait for StepsCardinal {
    fn prev(&mut self) -> Coord {
        self.0.accumulator -= self.0.minor_delta_abs as i64;
        if self.0.accumulator
            <= (self.0.major_delta_abs as i64 / 2)
                - self.0.major_delta_abs as i64
                - self.0.minor_delta_abs as i64
        {
            self.0.accumulator += self.0.major_delta_abs as i64 + self.0.minor_delta_abs as i64;;
            Coord::new(-self.0.minor_x as i32, -self.0.minor_y as i32)
        } else {
            Coord::new(-self.0.major_x as i32, -self.0.major_y as i32)
        }
    }
    fn next(&mut self) -> Coord {
        self.0.accumulator += self.0.minor_delta_abs as i64;
        if self.0.accumulator > self.0.major_delta_abs as i64 / 2 {
            self.0.accumulator -= self.0.major_delta_abs as i64 + self.0.minor_delta_abs as i64;
            Coord::new(self.0.minor_x as i32, self.0.minor_y as i32)
        } else {
            Coord::new(self.0.major_x as i32, self.0.major_y as i32)
        }
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LineSegment {
    pub start: Coord,
    pub end: Coord,
}

impl LineSegment {
    pub fn new(start: Coord, end: Coord) -> Self {
        Self { start, end }
    }
    pub fn traverse(&self) -> Traverse {
        Traverse {
            line_segment: *self,
        }
    }
    pub fn traverse_cardinal(&self) -> TraverseCardinal {
        TraverseCardinal {
            line_segment: *self,
        }
    }
    pub fn delta(&self) -> Coord {
        self.end - self.start
    }
    pub fn iter(&self) -> LineSegmentIter {
        GeneralLineSegmentIter::new(self.traverse())
    }
    pub fn iter_cardinal(&self) -> LineSegmentIterCardinal {
        GeneralLineSegmentIter::new(self.traverse_cardinal())
    }
    pub fn iter_config(&self, config: Config) -> LineSegmentIter {
        GeneralLineSegmentIter::new_config(self.traverse(), config)
    }
    pub fn iter_cardinal_config(&self, config: Config) -> LineSegmentIterCardinal {
        GeneralLineSegmentIter::new_config(self.traverse_cardinal(), config)
    }
    pub fn steps(&self) -> Steps {
        Steps::new(self.delta())
    }
    pub fn steps_cardinal(&self) -> StepsCardinal {
        StepsCardinal::new(self.delta())
    }
    pub fn num_steps(&self) -> usize {
        let delta = self.delta();
        delta.x.abs().max(delta.y.abs()) as usize + 1
    }
    pub fn num_steps_cardinal(&self) -> usize {
        let delta = self.delta();
        delta.x.abs() as usize + delta.y.abs() as usize + 1
    }
    pub fn reverse(&self) -> Self {
        Self {
            start: self.end,
            end: self.start,
        }
    }
    pub fn try_infinite(&self) -> Result<InfiniteLineSegment, ZeroLengthDelta> {
        InfiniteLineSegment::try_new(self.start, self.delta())
    }
    pub fn infinite(&self) -> InfiniteLineSegment {
        self.try_infinite().unwrap()
    }
}

pub trait TraverseTrait: Clone + Eq + private::Sealed {
    type Steps: StepsTrait;
    type Iter: Iterator<Item = Coord>;
    fn num_steps(&self) -> usize;
    fn steps(&self) -> Self::Steps;
    fn iter(&self) -> Self::Iter;
    fn iter_config(&self, config: Config) -> Self::Iter;
    fn line_segment(&self) -> LineSegment;
    fn start(&self) -> Coord {
        self.line_segment().start
    }
    fn end(&self) -> Coord {
        self.line_segment().end
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Traverse {
    pub line_segment: LineSegment,
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TraverseCardinal {
    pub line_segment: LineSegment,
}

impl TraverseTrait for Traverse {
    type Steps = Steps;
    type Iter = LineSegmentIter;
    fn num_steps(&self) -> usize {
        self.line_segment.num_steps()
    }
    fn steps(&self) -> Self::Steps {
        self.line_segment.steps()
    }
    fn iter(&self) -> Self::Iter {
        self.line_segment.iter()
    }
    fn iter_config(&self, config: Config) -> Self::Iter {
        self.line_segment.iter_config(config)
    }
    fn line_segment(&self) -> LineSegment {
        self.line_segment
    }
}

impl TraverseTrait for TraverseCardinal {
    type Steps = StepsCardinal;
    type Iter = LineSegmentIterCardinal;
    fn num_steps(&self) -> usize {
        self.line_segment.num_steps_cardinal()
    }
    fn steps(&self) -> Self::Steps {
        self.line_segment.steps_cardinal()
    }
    fn iter(&self) -> LineSegmentIterCardinal {
        self.line_segment.iter_cardinal()
    }
    fn iter_config(&self, config: Config) -> LineSegmentIterCardinal {
        self.line_segment.iter_cardinal_config(config)
    }
    fn line_segment(&self) -> LineSegment {
        self.line_segment
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Default, Debug, Clone, Copy)]
pub struct Config {
    pub exclude_start: bool,
    pub exclude_end: bool,
}

impl Config {
    pub fn new() -> Self {
        Default::default()
    }
    pub fn include_start(self) -> Self {
        Self {
            exclude_start: false,
            ..self
        }
    }
    pub fn include_end(self) -> Self {
        Self {
            exclude_end: false,
            ..self
        }
    }
    pub fn exclude_start(self) -> Self {
        Self {
            exclude_start: true,
            ..self
        }
    }
    pub fn exclude_end(self) -> Self {
        Self {
            exclude_end: true,
            ..self
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct GeneralLineSegmentIter<S: StepsTrait> {
    steps: S,
    current_coord: Coord,
    remaining: usize,
}

pub type LineSegmentIter = GeneralLineSegmentIter<Steps>;
pub type LineSegmentIterCardinal = GeneralLineSegmentIter<StepsCardinal>;

impl<S: StepsTrait> GeneralLineSegmentIter<S> {
    fn new<T: TraverseTrait<Steps = S>>(traverse: T) -> Self {
        let mut steps = traverse.steps();
        let backwards_step = steps.prev();
        let current_coord = traverse.start() + backwards_step;
        let remaining = traverse.num_steps();
        Self {
            steps,
            current_coord,
            remaining,
        }
    }

    fn new_config<T: TraverseTrait<Steps = S>>(traverse: T, config: Config) -> Self {
        let mut iter = Self::new(traverse);
        if config.exclude_end {
            iter.remaining -= 1;
        }
        if config.exclude_start {
            iter.next();
        }
        iter
    }
}

impl<S: StepsTrait> Iterator for GeneralLineSegmentIter<S> {
    type Item = Coord;
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        let step = self.steps.next();
        self.current_coord += step;
        self.remaining -= 1;
        Some(self.current_coord)
    }
}

impl IntoIterator for LineSegment {
    type Item = Coord;
    type IntoIter = LineSegmentIter;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl IntoIterator for Traverse {
    type Item = Coord;
    type IntoIter = LineSegmentIter;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl IntoIterator for TraverseCardinal {
    type Item = Coord;
    type IntoIter = LineSegmentIterCardinal;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InfiniteLineSegment {
    line_segment: LineSegment,
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy)]
pub struct ZeroLengthDelta;

impl InfiniteLineSegment {
    pub fn try_new(start: Coord, delta: Coord) -> Result<Self, ZeroLengthDelta> {
        if delta == Coord::new(0, 0) {
            Err(ZeroLengthDelta)
        } else {
            Ok(Self {
                line_segment: LineSegment::new(start, start + delta),
            })
        }
    }
    pub fn new(start: Coord, delta: Coord) -> Self {
        Self::try_new(start, delta).unwrap()
    }
    pub fn start(&self) -> Coord {
        self.line_segment.start
    }
    pub fn delta(&self) -> Coord {
        self.line_segment.delta()
    }
    pub fn reverse(&self) -> Self {
        let start = self.start();
        let end = start - self.delta();
        Self {
            line_segment: LineSegment::new(start, end),
        }
    }
    pub fn traverse(&self) -> InfiniteTraverse {
        InfiniteTraverse {
            line_segment: *self,
        }
    }
    pub fn traverse_cardinal(&self) -> InfiniteTraverseCardinal {
        InfiniteTraverseCardinal {
            line_segment: *self,
        }
    }
    pub fn iter(&self) -> InfiniteLineSegmentIter {
        GeneralInfiniteLineSegmentIter::new(self.traverse())
    }
    pub fn iter_config(&self, config: InfiniteConfig) -> InfiniteLineSegmentIter {
        if config.exclude_start {
            GeneralInfiniteLineSegmentIter::new_exclude_start(self.traverse())
        } else {
            self.iter()
        }
    }
    pub fn iter_cardinal(&self) -> InfiniteLineSegmentIterCardinal {
        GeneralInfiniteLineSegmentIter::new(self.traverse_cardinal())
    }
    pub fn iter_cardinal_config(&self, config: InfiniteConfig) -> InfiniteLineSegmentIterCardinal {
        if config.exclude_start {
            GeneralInfiniteLineSegmentIter::new_exclude_start(self.traverse_cardinal())
        } else {
            self.iter_cardinal()
        }
    }
}

pub trait InfiniteTraverseTrait: Clone + Eq + private::Sealed {
    type Steps: StepsTrait;
    type Iter: Iterator<Item = Coord>;
    fn steps(&self) -> Self::Steps;
    fn iter(&self) -> Self::Iter;
    fn iter_config(&self, config: InfiniteConfig) -> Self::Iter;
    fn start(&self) -> Coord;
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InfiniteTraverse {
    line_segment: InfiniteLineSegment,
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InfiniteTraverseCardinal {
    line_segment: InfiniteLineSegment,
}

impl InfiniteTraverseTrait for InfiniteTraverse {
    type Steps = Steps;
    type Iter = InfiniteLineSegmentIter;
    fn steps(&self) -> Self::Steps {
        Steps::new(self.line_segment.delta())
    }
    fn iter(&self) -> Self::Iter {
        self.line_segment.iter()
    }
    fn iter_config(&self, config: InfiniteConfig) -> Self::Iter {
        self.line_segment.iter_config(config)
    }
    fn start(&self) -> Coord {
        self.line_segment.start()
    }
}

impl InfiniteTraverseTrait for InfiniteTraverseCardinal {
    type Steps = StepsCardinal;
    type Iter = InfiniteLineSegmentIterCardinal;
    fn steps(&self) -> Self::Steps {
        StepsCardinal::new(self.line_segment.delta())
    }
    fn iter(&self) -> Self::Iter {
        self.line_segment.iter_cardinal()
    }
    fn iter_config(&self, config: InfiniteConfig) -> Self::Iter {
        self.line_segment.iter_cardinal_config(config)
    }
    fn start(&self) -> Coord {
        self.line_segment.start()
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Default, Debug, Clone, Copy)]
pub struct InfiniteConfig {
    pub exclude_start: bool,
}

impl InfiniteConfig {
    pub fn new() -> Self {
        Default::default()
    }
    pub fn include_start(self) -> Self {
        Self {
            exclude_start: false,
            ..self
        }
    }
    pub fn exclude_start(self) -> Self {
        Self {
            exclude_start: true,
            ..self
        }
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy)]
pub struct GeneralInfiniteLineSegmentIter<S: StepsTrait> {
    steps: S,
    current_coord: Coord,
}

pub type InfiniteLineSegmentIter = GeneralInfiniteLineSegmentIter<Steps>;
pub type InfiniteLineSegmentIterCardinal = GeneralInfiniteLineSegmentIter<StepsCardinal>;

impl<S: StepsTrait> GeneralInfiniteLineSegmentIter<S> {
    fn new<T: InfiniteTraverseTrait<Steps = S>>(traverse: T) -> Self {
        let mut steps = traverse.steps();
        let backwards_step = steps.prev();
        let current_coord = traverse.start() + backwards_step;
        Self {
            steps,
            current_coord,
        }
    }

    fn new_exclude_start<T: InfiniteTraverseTrait<Steps = S>>(traverse: T) -> Self {
        let steps = traverse.steps();
        let current_coord = traverse.start();
        Self {
            steps,
            current_coord,
        }
    }
}

impl<S: StepsTrait> Iterator for GeneralInfiniteLineSegmentIter<S> {
    type Item = Coord;
    fn next(&mut self) -> Option<Self::Item> {
        let (delta, next_steps) = self.steps.next_copy();
        if let Some(next_coord) = self.current_coord.checked_add(delta) {
            self.current_coord = next_coord;
            self.steps = next_steps;
            Some(next_coord)
        } else {
            None
        }
    }
}

impl IntoIterator for InfiniteLineSegment {
    type Item = Coord;
    type IntoIter = InfiniteLineSegmentIter;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl IntoIterator for InfiniteTraverse {
    type Item = Coord;
    type IntoIter = InfiniteLineSegmentIter;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl IntoIterator for InfiniteTraverseCardinal {
    type Item = Coord;
    type IntoIter = InfiniteLineSegmentIterCardinal;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

mod private {
    pub trait Sealed {}

    impl Sealed for super::Steps {}
    impl Sealed for super::StepsCardinal {}
    impl Sealed for super::Traverse {}
    impl Sealed for super::TraverseCardinal {}
    impl Sealed for super::InfiniteTraverse {}
    impl Sealed for super::InfiniteTraverseCardinal {}
}

#[cfg(test)]
mod test {
    extern crate rand;
    use self::rand::rngs::StdRng;
    use self::rand::{Rng, SeedableRng};
    use super::*;

    fn test_properties_gen<T>(traverse: T)
    where
        T: TraverseTrait + ::std::fmt::Debug,
        T::Steps: ::std::fmt::Debug,
    {
        let coords: Vec<_> = traverse.iter().collect();
        assert_eq!(coords.len(), traverse.num_steps());
        assert_eq!(*coords.first().unwrap(), traverse.start());
        assert_eq!(*coords.last().unwrap(), traverse.end());
        let mut steps = traverse.steps();
        for _ in 0..traverse.num_steps() {
            let before = steps.clone();
            steps.next();
            let mut after = steps.clone();
            after.prev();
            assert_eq!(
                before, after,
                "\n{:#?}\n{:#?}\n{:#?}",
                before, after, traverse
            );
        }
        let orig_coords = coords;
        let coords: Vec<_> = traverse
            .iter_config(Config::new().exclude_start().exclude_end())
            .collect();
        assert_eq!(coords.len(), traverse.num_steps().max(2) - 2);
        if let Some(&coord) = coords.first() {
            assert_eq!(coord, orig_coords[1]);
        }
        if let Some(&coord) = coords.last() {
            assert_eq!(coord, orig_coords[orig_coords.len() - 2]);
        }
        let coords: Vec<_> = traverse
            .iter_config(Config::new().exclude_start())
            .collect();
        assert_eq!(coords.len(), traverse.num_steps().max(1) - 1);
        if let Some(&coord) = coords.first() {
            assert_eq!(coord, orig_coords[1]);
        }
        if let Some(&coord) = coords.last() {
            assert_eq!(coord, orig_coords[orig_coords.len() - 1]);
        }
        let coords: Vec<_> = traverse.iter_config(Config::new().exclude_end()).collect();
        assert_eq!(coords.len(), traverse.num_steps().max(1) - 1);
        if let Some(&coord) = coords.first() {
            assert_eq!(coord, orig_coords[0]);
        }
        if let Some(&coord) = coords.last() {
            assert_eq!(coord, orig_coords[orig_coords.len() - 2]);
        }
    }

    fn compare_finite_with_infinite<F: TraverseTrait, I: InfiniteTraverseTrait>(f: F, i: I) {
        f.iter().zip(i.iter()).for_each(|(f, i)| {
            assert_eq!(f, i);
        });
        f.iter_config(Config::new().exclude_start())
            .zip(i.iter_config(InfiniteConfig::new().exclude_start()))
            .for_each(|(f, i)| {
                assert_eq!(f, i);
            });
    }

    fn test_properties(line_segment: LineSegment) {
        test_properties_gen(line_segment.traverse());
        test_properties_gen(line_segment.traverse_cardinal());
        if let Ok(infinite) = line_segment.try_infinite() {
            compare_finite_with_infinite(line_segment.traverse(), infinite.traverse());
            compare_finite_with_infinite(
                line_segment.traverse_cardinal(),
                infinite.traverse_cardinal(),
            );
        }
    }

    fn rand_int<R: Rng>(rng: &mut R) -> i32 {
        const MAX: i32 = 100;
        rng.gen::<i32>() % MAX
    }

    fn rand_coord<R: Rng>(rng: &mut R) -> Coord {
        Coord::new(rand_int(rng), rand_int(rng))
    }

    fn rand_line_segment<R: Rng>(rng: &mut R) -> LineSegment {
        LineSegment::new(rand_coord(rng), rand_coord(rng))
    }

    #[test]
    fn all() {
        test_properties(LineSegment::new(Coord::new(0, 0), Coord::new(0, 0)));
        test_properties(LineSegment::new(Coord::new(0, 0), Coord::new(1, 1)));
        test_properties(LineSegment::new(Coord::new(0, 0), Coord::new(1, 0)));
        test_properties(LineSegment::new(Coord::new(0, 0), Coord::new(2, 1)));
        test_properties(LineSegment::new(Coord::new(1, -1), Coord::new(0, 0)));
        test_properties(LineSegment::new(Coord::new(1, 100), Coord::new(0, 0)));
        test_properties(LineSegment::new(Coord::new(100, 1), Coord::new(0, 0)));
        const NUM_RAND_TESTS: usize = 10000;
        let mut rng = StdRng::seed_from_u64(0);
        for _ in 0..NUM_RAND_TESTS {
            test_properties(rand_line_segment(&mut rng));
        }
    }
}