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
use crate::{utils, Data};
use std::io;
const LABEL_PADDING: usize = 2;
#[derive(Debug)]
pub struct Chart {
radius: u16,
aspect_ratio: u16,
legend: bool,
}
impl Default for Chart {
fn default() -> Self {
Self {
radius: 8,
aspect_ratio: 3,
legend: false,
}
}
}
impl Chart {
pub fn new() -> Self {
Default::default()
}
pub fn radius(&mut self, radius: u16) -> &mut Self {
self.radius = radius;
self
}
pub fn aspect_ratio(&mut self, aspect_ratio: u16) -> &mut Self {
assert!(aspect_ratio > 0, "aspect ratio has to be greater than zero");
self.aspect_ratio = aspect_ratio;
self
}
pub fn legend(&mut self, legend: bool) -> &mut Self {
self.legend = legend;
self
}
}
impl Chart {
pub fn draw(&self, data: &[Data]) {
self.draw_into(io::stdout(), data)
.expect("failed to write to stdout")
}
pub fn draw_into(&self, mut f: impl io::Write, data: &[Data]) -> io::Result<()> {
let total: f32 = data.iter().map(|d| d.value).sum();
assert!(!data.is_empty(), "chart data cannot be empty");
assert!(
total > 0.0,
"total of data values has to be greater than zero"
);
let data_angles = utils::data_angles(total, data);
let radius = self.radius as i32;
let aspect_ratio = self.aspect_ratio as i32;
let center_x = utils::calculate_center_x(radius, aspect_ratio);
let circle = (-radius..=radius).map(|y| {
let width = utils::calculate_width(radius, y, aspect_ratio);
let padding_len = (center_x - width) as usize;
let mut output = " ".repeat(padding_len);
(-width..=width).for_each(|x| {
let (x, y) = (x as f32, y as f32);
let angle = x.atan2(y).to_degrees();
let idx = data_angles
.iter()
.position(|a| 360.0 / 2.0 - angle <= *a)
.expect("no data item for given angle, should be impossible");
let item = &data[idx];
match item.color {
None => output.push(item.fill),
Some(c) => output.push_str(&c.paint(item.fill.to_string()).to_string()),
}
});
if self.legend {
output.push_str(&" ".repeat(padding_len + LABEL_PADDING));
let max_label_idx = (data.len() - 1) as i32;
let mut iter = (0..=max_label_idx)
.map(|x| x * 2)
.map(|x| x - max_label_idx);
if let Some(idx) = iter.position(|i| i == y) {
let item = &data[idx];
output.push_str(&item.format_label(total));
}
}
output
});
for line in circle {
writeln!(&mut f, "{}", line)?;
}
Ok(())
}
}