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
use crate::geom::Circle;
use crate::geom::Line;
use crate::geom::Point;
use crate::num::Num;
use crate::num::ToRounded;
use ::std::f32::consts::TAU;
#[derive(Clone, Debug)]
pub struct CircleCircumferenceLinesIterator {
circle: Circle<f32>,
index: usize,
num_lines: usize,
}
impl CircleCircumferenceLinesIterator {
pub fn new<N>(circle: Circle<N>, num_lines: usize) -> Self
where
N: Num + ToRounded<f32>,
{
Self {
circle: circle.to_rounded(),
index: 0,
num_lines,
}
}
}
impl CircleCircumferenceLinesIterator {
fn calculate_edge_point(&self, index: usize) -> Point<f32> {
let angle = self.calculate_angle_index(index);
let edge_point = self.circle.centre() + Point(0.0, self.circle.radius().to_rounded());
edge_point.rotate_around_point(angle, self.circle.centre())
}
fn calculate_angle_index(&self, index: usize) -> f32 {
let angle_index = index as f32 / self.num_lines as f32;
TAU * angle_index
}
}
impl Iterator for CircleCircumferenceLinesIterator {
type Item = Line<f32>;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.num_lines {
return None;
}
let point_from = self.calculate_edge_point(self.index);
let point_to = self.calculate_edge_point(self.index + 1);
let line = Line(point_from, point_to);
self.index += 1;
Some(line)
}
}
#[cfg(test)]
mod iterator {
use super::*;
#[test]
fn it_should_return_num_of_points_requested() {
let iterator = CircleCircumferenceLinesIterator::new(Circle(Point(10.0, 20.0), 5.0), 3);
assert_eq!(iterator.count(), 3);
}
#[test]
fn it_should_return_no_points_if_zero_requested() {
let mut iterator = CircleCircumferenceLinesIterator::new(Circle(Point(10.0, 20.0), 5.0), 0);
assert_eq!(iterator.next(), None);
}
#[test]
fn it_should_return_all_points_of_a_circle() {
let iterator = CircleCircumferenceLinesIterator::new(Circle(Point(10.0, 20.0), 5.0), 8);
let points: Vec<Line<f32>> = iterator.collect();
assert_eq!(
points,
vec![
Line(Point(10.0, 25.0), Point(13.535534, 23.535534),),
Line(Point(13.535534, 23.535534), Point(15.0, 20.0),),
Line(Point(15.0, 20.0), Point(13.535534, 16.464466),),
Line(Point(13.535534, 16.464466), Point(10.0, 15.0),),
Line(Point(10.0, 15.0), Point(6.464466, 16.464466),),
Line(Point(6.464466, 16.464466), Point(5.0, 20.0),),
Line(Point(5.0, 20.0), Point(6.4644666, 23.535534),),
Line(Point(6.4644666, 23.535534), Point(10.0, 25.0),),
]
);
}
}