generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadme_benchmarks.rs
182 lines (157 loc) · 5.33 KB
/
readme_benchmarks.rs
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
/// Module that updates the readme me with timing information.
/// The approach taken is similar to how `aoc-readme-stars` handles this.
use std::{fs, io};
use crate::template::timings::Timings;
use crate::template::Day;
static MARKER: &str = "<!--- benchmarking table --->";
#[derive(Debug)]
pub enum Error {
Parser(String),
IO(io::Error),
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::IO(e)
}
}
pub struct TablePosition {
pos_start: usize,
pos_end: usize,
}
#[must_use]
pub fn get_path_for_bin(day: Day) -> String {
format!("./src/bin/{day}.rs")
}
fn locate_table(readme: &str) -> Result<TablePosition, Error> {
let matches: Vec<_> = readme.match_indices(MARKER).collect();
if matches.len() > 2 {
return Err(Error::Parser(
"{}: too many occurences of marker in README.".into(),
));
}
let pos_start = matches
.first()
.map(|m| m.0)
.ok_or_else(|| Error::Parser("Could not find table start position.".into()))?;
let pos_end = matches
.last()
.map(|m| m.0 + m.1.len())
.ok_or_else(|| Error::Parser("Could not find table end position.".into()))?;
Ok(TablePosition { pos_start, pos_end })
}
fn construct_table(prefix: &str, timings: Timings, total_millis: f64) -> String {
let header = format!("{prefix} Benchmarks");
let mut lines: Vec<String> = vec![
MARKER.into(),
header,
String::new(),
"| Day | Part 1 | Part 2 |".into(),
"| :---: | :---: | :---: |".into(),
];
for timing in timings.data {
let path = get_path_for_bin(timing.day);
lines.push(format!(
"| [Day {}]({}) | `{}` | `{}` |",
timing.day.into_inner(),
path,
timing.part_1.unwrap_or_else(|| "-".into()),
timing.part_2.unwrap_or_else(|| "-".into())
));
}
lines.push(String::new());
lines.push(format!("**Total: {total_millis:.2}ms**"));
lines.push(MARKER.into());
lines.join("\n")
}
fn update_content(s: &mut String, timings: Timings, total_millis: f64) -> Result<(), Error> {
let positions = locate_table(s)?;
let table = construct_table("##", timings, total_millis);
s.replace_range(positions.pos_start..positions.pos_end, &table);
Ok(())
}
pub fn update(timings: Timings) -> Result<(), Error> {
let path = "README.md";
let mut readme = String::from_utf8_lossy(&fs::read(path)?).to_string();
let total_millis = timings.total_millis();
update_content(&mut readme, timings, total_millis)?;
fs::write(path, &readme)?;
Ok(())
}
#[cfg(feature = "test_lib")]
mod tests {
use super::{update_content, MARKER};
use crate::{day, template::timings::Timing, template::timings::Timings};
fn get_mock_timings() -> Timings {
Timings {
data: vec![
Timing {
day: day!(1),
part_1: Some("10ms".into()),
part_2: Some("20ms".into()),
total_nanos: 3e+10,
},
Timing {
day: day!(2),
part_1: Some("30ms".into()),
part_2: Some("40ms".into()),
total_nanos: 7e+10,
},
Timing {
day: day!(4),
part_1: Some("40ms".into()),
part_2: Some("50ms".into()),
total_nanos: 9e+10,
},
],
}
}
#[test]
#[should_panic]
fn errors_if_marker_not_present() {
let mut s = "# readme".to_string();
update_content(&mut s, get_mock_timings(), 190.0).unwrap();
}
#[test]
#[should_panic]
fn errors_if_too_many_markers_present() {
let mut s = format!("{} {} {}", MARKER, MARKER, MARKER);
update_content(&mut s, get_mock_timings(), 190.0).unwrap();
}
#[test]
fn updates_empty_benchmarks() {
let mut s = format!("foo\nbar\n{}{}\nbaz", MARKER, MARKER);
update_content(&mut s, get_mock_timings(), 190.0).unwrap();
assert_eq!(s.contains("## Benchmarks"), true);
}
#[test]
fn updates_existing_benchmarks() {
let mut s = format!("foo\nbar\n{}{}\nbaz", MARKER, MARKER);
update_content(&mut s, get_mock_timings(), 190.0).unwrap();
update_content(&mut s, get_mock_timings(), 190.0).unwrap();
assert_eq!(s.matches(MARKER).collect::<Vec<&str>>().len(), 2);
assert_eq!(s.matches("## Benchmarks").collect::<Vec<&str>>().len(), 1);
}
#[test]
fn format_benchmarks() {
let mut s = format!("foo\nbar\n{}\n{}\nbaz", MARKER, MARKER);
update_content(&mut s, get_mock_timings(), 190.0).unwrap();
let expected = [
"foo",
"bar",
"<!--- benchmarking table --->",
"## Benchmarks",
"",
"| Day | Part 1 | Part 2 |",
"| :---: | :---: | :---: |",
"| [Day 1](./src/bin/01.rs) | `10ms` | `20ms` |",
"| [Day 2](./src/bin/02.rs) | `30ms` | `40ms` |",
"| [Day 4](./src/bin/04.rs) | `40ms` | `50ms` |",
"",
"**Total: 190.00ms**",
"<!--- benchmarking table --->",
"baz",
]
.join("\n");
assert_eq!(s, expected);
}
}