Initial commit

This commit is contained in:
RussellChamp authored and GitHub committed 2025-12-04 16:22:10 -05:00
commit cfeb0828fd
35 files changed
+2865

No files matched your search

View File
Whitespace-only changes.
+3
View File
@@ -0,0 +1,3 @@
pub mod template;
// Use this file to add helper functions and additional modules.
+144
View File
@@ -0,0 +1,144 @@
use advent_of_code::template::commands::{all, download, read, scaffold, solve, time};
use args::{AppArguments, parse};
#[cfg(feature = "today")]
use advent_of_code::template::Day;
#[cfg(feature = "today")]
use std::process;
mod args {
use advent_of_code::template::Day;
use std::process;
pub enum AppArguments {
Download {
day: Day,
},
Read {
day: Day,
},
Scaffold {
day: Day,
download: bool,
overwrite: bool,
},
Solve {
day: Day,
release: bool,
dhat: bool,
submit: Option<u8>,
},
All {
release: bool,
},
Time {
all: bool,
day: Option<Day>,
store: bool,
},
#[cfg(feature = "today")]
Today,
}
pub fn parse() -> Result<AppArguments, Box<dyn std::error::Error>> {
let mut args = pico_args::Arguments::from_env();
let app_args = match args.subcommand()?.as_deref() {
Some("all") => AppArguments::All {
release: args.contains("--release"),
},
Some("time") => {
let all = args.contains("--all");
let store = args.contains("--store");
AppArguments::Time {
all,
day: args.opt_free_from_str()?,
store,
}
}
Some("download") => AppArguments::Download {
day: args.free_from_str()?,
},
Some("read") => AppArguments::Read {
day: args.free_from_str()?,
},
Some("scaffold") => AppArguments::Scaffold {
day: args.free_from_str()?,
download: args.contains("--download"),
overwrite: args.contains("--overwrite"),
},
Some("solve") => AppArguments::Solve {
day: args.free_from_str()?,
release: args.contains("--release"),
submit: args.opt_value_from_str("--submit")?,
dhat: args.contains("--dhat"),
},
#[cfg(feature = "today")]
Some("today") => AppArguments::Today,
Some(x) => {
eprintln!("Unknown command: {x}");
process::exit(1);
}
None => {
eprintln!("No command specified.");
process::exit(1);
}
};
let remaining = args.finish();
if !remaining.is_empty() {
eprintln!("Warning: unknown argument(s): {remaining:?}.");
}
Ok(app_args)
}
}
fn main() {
match parse() {
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
Ok(args) => match args {
AppArguments::All { release } => all::handle(release),
AppArguments::Time { day, all, store } => time::handle(day, all, store),
AppArguments::Download { day } => download::handle(day),
AppArguments::Read { day } => read::handle(day),
AppArguments::Scaffold {
day,
download,
overwrite,
} => {
scaffold::handle(day, overwrite);
if download {
download::handle(day);
}
}
AppArguments::Solve {
day,
release,
dhat,
submit,
} => solve::handle(day, release, dhat, submit),
#[cfg(feature = "today")]
AppArguments::Today => {
match Day::today() {
Some(day) => {
scaffold::handle(day, false);
download::handle(day);
read::handle(day)
}
None => {
eprintln!(
"`today` command can only be run between the 1st and \
the 25th of december. Please use `scaffold` with a specific day."
);
process::exit(1)
}
};
}
},
};
}
+26
View File
@@ -0,0 +1,26 @@
advent_of_code::solution!(%DAY_NUMBER%);
pub fn part_one(input: &str) -> Option<u64> {
None
}
pub fn part_two(input: &str) -> Option<u64> {
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, None);
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, None);
}
}
+125
View File
@@ -0,0 +1,125 @@
/// Wrapper module around the "aoc-cli" command-line.
use std::{
fmt::Display,
process::{Command, Output, Stdio},
};
use crate::template::Day;
#[derive(Debug)]
pub enum AocCommandError {
CommandNotFound,
CommandNotCallable,
BadExitStatus(Output),
}
impl Display for AocCommandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AocCommandError::CommandNotFound => write!(f, "aoc-cli is not present in environment."),
AocCommandError::CommandNotCallable => write!(f, "aoc-cli could not be called."),
AocCommandError::BadExitStatus(_) => {
write!(f, "aoc-cli exited with a non-zero status.")
}
}
}
}
pub fn check() -> Result<(), AocCommandError> {
Command::new("aoc")
.arg("-V")
.output()
.map_err(|_| AocCommandError::CommandNotFound)?;
Ok(())
}
pub fn read(day: Day) -> Result<Output, AocCommandError> {
let puzzle_path = get_puzzle_path(day);
let args = build_args(
"read",
&[
"--description-only".into(),
"--puzzle-file".into(),
puzzle_path,
],
day,
);
call_aoc_cli(&args)
}
pub fn download(day: Day) -> Result<Output, AocCommandError> {
let input_path = get_input_path(day);
let puzzle_path = get_puzzle_path(day);
let args = build_args(
"download",
&[
"--overwrite".into(),
"--input-file".into(),
input_path.to_string(),
"--puzzle-file".into(),
puzzle_path.to_string(),
],
day,
);
let output = call_aoc_cli(&args)?;
println!("---");
println!("🎄 Successfully wrote input to \"{}\".", &input_path);
println!("🎄 Successfully wrote puzzle to \"{}\".", &puzzle_path);
Ok(output)
}
pub fn submit(day: Day, part: u8, result: &str) -> Result<Output, AocCommandError> {
// workaround: the argument order is inverted for submit.
let mut args = build_args("submit", &[], day);
args.push(part.to_string());
args.push(result.to_string());
call_aoc_cli(&args)
}
fn get_input_path(day: Day) -> String {
format!("data/inputs/{day}.txt")
}
fn get_puzzle_path(day: Day) -> String {
format!("data/puzzles/{day}.md")
}
fn get_year() -> Option<u16> {
match std::env::var("AOC_YEAR") {
Ok(x) => x.parse().ok().or(None),
Err(_) => None,
}
}
fn build_args(command: &str, args: &[String], day: Day) -> Vec<String> {
let mut cmd_args = args.to_vec();
if let Some(year) = get_year() {
cmd_args.push("--year".into());
cmd_args.push(year.to_string());
}
cmd_args.append(&mut vec!["--day".into(), day.to_string(), command.into()]);
cmd_args
}
fn call_aoc_cli(args: &[String]) -> Result<Output, AocCommandError> {
// println!("Calling >aoc with: {}", args.join(" "));
let output = Command::new("aoc")
.args(args)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()
.map_err(|_| AocCommandError::CommandNotCallable)?;
if output.status.success() {
Ok(output)
} else {
Err(AocCommandError::BadExitStatus(output))
}
}
+5
View File
@@ -0,0 +1,5 @@
use crate::template::{all_days, run_multi::run_multi};
pub fn handle(is_release: bool) {
run_multi(&all_days().collect(), is_release, false);
}
+16
View File
@@ -0,0 +1,16 @@
use crate::template::{Day, aoc_cli};
use std::process;
pub fn handle(day: Day) {
if aoc_cli::check().is_err() {
eprintln!(
"command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it."
);
process::exit(1);
}
if let Err(e) = aoc_cli::download(day) {
eprintln!("failed to call aoc-cli: {e}");
process::exit(1);
};
}
+6
View File
@@ -0,0 +1,6 @@
pub mod all;
pub mod download;
pub mod read;
pub mod scaffold;
pub mod solve;
pub mod time;
+17
View File
@@ -0,0 +1,17 @@
use std::process;
use crate::template::{Day, aoc_cli};
pub fn handle(day: Day) {
if aoc_cli::check().is_err() {
eprintln!(
"command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it."
);
process::exit(1);
}
if let Err(e) = aoc_cli::read(day) {
eprintln!("failed to call aoc-cli: {e}");
process::exit(1);
};
}
+79
View File
@@ -0,0 +1,79 @@
use std::{
fs::{File, OpenOptions},
io::Write,
process,
};
use crate::template::Day;
const MODULE_TEMPLATE: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/template.txt"));
fn safe_create_file(path: &str, overwrite: bool) -> Result<File, std::io::Error> {
let mut file = OpenOptions::new();
if overwrite {
file.create(true);
} else {
file.create_new(true);
}
file.truncate(true).write(true).open(path)
}
fn create_file(path: &str) -> Result<File, std::io::Error> {
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path)
}
pub fn handle(day: Day, overwrite: bool) {
let input_path = format!("data/inputs/{day}.txt");
let example_path = format!("data/examples/{day}.txt");
let module_path = format!("src/bin/{day}.rs");
let mut file = match safe_create_file(&module_path, overwrite) {
Ok(file) => file,
Err(e) => {
eprintln!("Failed to create module file: {e}");
process::exit(1);
}
};
match file.write_all(
MODULE_TEMPLATE
.replace("%DAY_NUMBER%", &day.into_inner().to_string())
.as_bytes(),
) {
Ok(()) => {
println!("Created module file \"{}\"", &module_path);
}
Err(e) => {
eprintln!("Failed to write module contents: {e}");
process::exit(1);
}
}
match create_file(&input_path) {
Ok(_) => {
println!("Created empty input file \"{}\"", &input_path);
}
Err(e) => {
eprintln!("Failed to create input file: {e}");
process::exit(1);
}
}
match create_file(&example_path) {
Ok(_) => {
println!("Created empty example file \"{}\"", &example_path);
}
Err(e) => {
eprintln!("Failed to create example file: {e}");
process::exit(1);
}
}
println!("---");
println!("🎄 Type `cargo solve {day}` to run your solution.");
}
+34
View File
@@ -0,0 +1,34 @@
use std::process::{Command, Stdio};
use crate::template::Day;
pub fn handle(day: Day, release: bool, dhat: bool, submit_part: Option<u8>) {
let mut cmd_args = vec!["run".to_string(), "--bin".to_string(), day.to_string()];
if dhat {
cmd_args.extend([
"--profile".to_string(),
"dhat".to_string(),
"--features".to_string(),
"dhat-heap".to_string(),
]);
} else if release {
cmd_args.push("--release".to_string());
}
cmd_args.push("--".to_string());
if let Some(submit_part) = submit_part {
cmd_args.push("--submit".to_string());
cmd_args.push(submit_part.to_string());
}
let mut cmd = Command::new("cargo")
.args(&cmd_args)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.spawn()
.unwrap();
cmd.wait().unwrap();
}
+40
View File
@@ -0,0 +1,40 @@
use std::collections::HashSet;
use crate::template::run_multi::run_multi;
use crate::template::timings::Timings;
use crate::template::{Day, all_days, readme_benchmarks};
pub fn handle(day: Option<Day>, run_all: bool, store: bool) {
let stored_timings = Timings::read_from_file();
let days_to_run = day.map_or_else(
|| {
if run_all {
all_days().collect()
} else {
// when the `--all` flag is not set, filter out days that are fully benched.
all_days()
.filter(|day| !stored_timings.is_day_complete(*day))
.collect()
}
},
|day| HashSet::from([day]),
);
let timings = run_multi(&days_to_run, true, true).unwrap();
if store {
let merged_timings = stored_timings.merge(&timings);
merged_timings.store_file().unwrap();
println!();
match readme_benchmarks::update(merged_timings) {
Ok(()) => {
println!("Stored updated benchmarks.");
}
Err(_) => {
eprintln!("Failed to store updated benchmarks.");
}
}
}
}
+181
View File
@@ -0,0 +1,181 @@
use std::error::Error;
use std::fmt::Display;
use std::str::FromStr;
#[cfg(feature = "today")]
use chrono::{Datelike, FixedOffset, Utc};
#[cfg(feature = "today")]
const SERVER_UTC_OFFSET: i32 = -5;
/// A valid day number of advent (i.e. an integer in range 1 to 25).
///
/// # Display
/// This value displays as a two digit number.
///
/// ```
/// # use advent_of_code::Day;
/// let day = Day::new(8).unwrap();
/// assert_eq!(day.to_string(), "08")
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Day(u8);
impl Day {
/// Creates a [`Day`] from the provided value if it's in the valid range,
/// returns [`None`] otherwise.
pub const fn new(day: u8) -> Option<Self> {
if day == 0 || day > 25 {
return None;
}
Some(Self(day))
}
/// Converts the [`Day`] into an [`u8`].
pub fn into_inner(self) -> u8 {
self.0
}
}
#[cfg(feature = "today")]
impl Day {
/// Returns the current day if it's between the 1st and the 25th of december, `None` otherwise.
pub fn today() -> Option<Self> {
let offset = FixedOffset::east_opt(SERVER_UTC_OFFSET * 3600)?;
let today = Utc::now().with_timezone(&offset);
if today.month() == 12 && today.day() <= 25 {
Self::new(u8::try_from(today.day()).ok()?)
} else {
None
}
}
}
impl Display for Day {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:02}", self.0)
}
}
impl PartialEq<u8> for Day {
fn eq(&self, other: &u8) -> bool {
self.0.eq(other)
}
}
impl PartialOrd<u8> for Day {
fn partial_cmp(&self, other: &u8) -> Option<std::cmp::Ordering> {
self.0.partial_cmp(other)
}
}
/* -------------------------------------------------------------------------- */
impl FromStr for Day {
type Err = DayFromStrError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let day = s.parse().map_err(|_| DayFromStrError)?;
Self::new(day).ok_or(DayFromStrError)
}
}
/// An error which can be returned when parsing a [`Day`].
#[derive(Debug)]
pub struct DayFromStrError;
impl Error for DayFromStrError {}
impl Display for DayFromStrError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("expecting a day number between 1 and 25")
}
}
/* -------------------------------------------------------------------------- */
/// An iterator that yields every day of advent from the 1st to the 25th.
pub fn all_days() -> AllDays {
AllDays::new()
}
/// An iterator that yields every day of advent from the 1st to the 25th.
pub struct AllDays {
current: u8,
}
impl AllDays {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self { current: 1 }
}
}
impl Iterator for AllDays {
type Item = Day;
fn next(&mut self) -> Option<Self::Item> {
if self.current > 25 {
return None;
}
// NOTE: the iterator starts at 1 and we have verified that the value is not above 25.
let day = Day(self.current);
self.current += 1;
Some(day)
}
}
/* -------------------------------------------------------------------------- */
/// Creates a [`Day`] value in a const context.
#[macro_export]
macro_rules! day {
($day:expr) => {
const {
$crate::template::Day::new($day)
.expect("invalid day number, expecting a value between 1 and 25")
}
};
}
/* -------------------------------------------------------------------------- */
#[cfg(feature = "test_lib")]
mod tests {
use super::{Day, all_days};
#[test]
fn all_days_iterator() {
let mut iter = all_days();
assert_eq!(iter.next(), Some(Day(1)));
assert_eq!(iter.next(), Some(Day(2)));
assert_eq!(iter.next(), Some(Day(3)));
assert_eq!(iter.next(), Some(Day(4)));
assert_eq!(iter.next(), Some(Day(5)));
assert_eq!(iter.next(), Some(Day(6)));
assert_eq!(iter.next(), Some(Day(7)));
assert_eq!(iter.next(), Some(Day(8)));
assert_eq!(iter.next(), Some(Day(9)));
assert_eq!(iter.next(), Some(Day(10)));
assert_eq!(iter.next(), Some(Day(11)));
assert_eq!(iter.next(), Some(Day(12)));
assert_eq!(iter.next(), Some(Day(13)));
assert_eq!(iter.next(), Some(Day(14)));
assert_eq!(iter.next(), Some(Day(15)));
assert_eq!(iter.next(), Some(Day(16)));
assert_eq!(iter.next(), Some(Day(17)));
assert_eq!(iter.next(), Some(Day(18)));
assert_eq!(iter.next(), Some(Day(19)));
assert_eq!(iter.next(), Some(Day(20)));
assert_eq!(iter.next(), Some(Day(21)));
assert_eq!(iter.next(), Some(Day(22)));
assert_eq!(iter.next(), Some(Day(23)));
assert_eq!(iter.next(), Some(Day(24)));
assert_eq!(iter.next(), Some(Day(25)));
assert_eq!(iter.next(), None);
}
}
/* -------------------------------------------------------------------------- */
+68
View File
@@ -0,0 +1,68 @@
use std::{env, fs};
pub mod aoc_cli;
pub mod commands;
pub mod runner;
pub use day::*;
mod day;
mod readme_benchmarks;
mod run_multi;
mod timings;
pub const ANSI_ITALIC: &str = "\x1b[3m";
pub const ANSI_BOLD: &str = "\x1b[1m";
pub const ANSI_RESET: &str = "\x1b[0m";
/// Helper function that reads a text file to a string.
#[must_use]
pub fn read_file(folder: &str, day: Day) -> String {
let cwd = env::current_dir().unwrap();
let filepath = cwd.join("data").join(folder).join(format!("{day}.txt"));
let f = fs::read_to_string(filepath);
f.expect("could not open input file")
}
/// Helper function that reads a text file to string, appending a part suffix. E.g. like `01-2.txt`.
#[must_use]
pub fn read_file_part(folder: &str, day: Day, part: u8) -> String {
let cwd = env::current_dir().unwrap();
let filepath = cwd
.join("data")
.join(folder)
.join(format!("{day}-{part}.txt"));
let f = fs::read_to_string(filepath);
f.expect("could not open input file")
}
/// Creates the constant `DAY` and sets up the input and runner for each part.
///
/// The optional, second parameter (1 or 2) allows you to only run a single part of the solution.
#[macro_export]
macro_rules! solution {
($day:expr) => {
$crate::solution!(@impl $day, [part_one, 1] [part_two, 2]);
};
($day:expr, 1) => {
$crate::solution!(@impl $day, [part_one, 1]);
};
($day:expr, 2) => {
$crate::solution!(@impl $day, [part_two, 2]);
};
(@impl $day:expr, $( [$func:expr, $part:expr] )*) => {
/// The current day.
const DAY: $crate::template::Day = $crate::day!($day);
#[cfg(feature = "dhat-heap")]
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
fn main() {
use $crate::template::runner::*;
let input = $crate::template::read_file("inputs", DAY);
$( run_part($func, &input, DAY, $part); )*
}
};
}
+183
View File
@@ -0,0 +1,183 @@
/// 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::Day;
use crate::template::timings::Timings;
static MARKER: &str = "<!--- benchmarking table --->";
#[allow(dead_code)]
#[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::{MARKER, update_content};
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);
}
}
+257
View File
@@ -0,0 +1,257 @@
use std::{collections::HashSet, io};
use crate::template::{ANSI_BOLD, ANSI_ITALIC, ANSI_RESET, Day};
use super::{
all_days,
timings::{Timing, Timings},
};
pub fn run_multi(days_to_run: &HashSet<Day>, is_release: bool, is_timed: bool) -> Option<Timings> {
let mut timings: Vec<Timing> = Vec::with_capacity(days_to_run.len());
let mut need_space = false;
// NOTE: use non-duplicate, sorted day values.
all_days()
.filter(|day| days_to_run.contains(day))
.for_each(|day| {
if need_space {
println!();
}
need_space = true;
println!("{ANSI_BOLD}Day {day}{ANSI_RESET}");
println!("------");
let output = child_commands::run_solution(day, is_timed, is_release).unwrap();
if output.is_empty() {
println!("Not solved.");
} else {
let val = child_commands::parse_exec_time(&output, day);
timings.push(val);
}
});
if is_timed {
let timings = Timings { data: timings };
let total_millis = timings.total_millis();
println!(
"\n{ANSI_BOLD}Total (Run):{ANSI_RESET} {ANSI_ITALIC}{total_millis:.2}ms{ANSI_RESET}"
);
Some(timings)
} else {
None
}
}
#[allow(dead_code)]
#[derive(Debug)]
pub enum Error {
BrokenPipe,
IO(io::Error),
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::IO(e)
}
}
#[must_use]
pub fn get_path_for_bin(day: Day) -> String {
format!("./src/bin/{day}.rs")
}
/// All solutions live in isolated binaries.
/// This module encapsulates interaction with these binaries, both invoking them as well as parsing the timing output.
pub mod child_commands {
use super::{Error, get_path_for_bin};
use crate::template::Day;
use std::{
io::{BufRead, BufReader},
path::Path,
process::{Command, Stdio},
thread,
};
/// Run the solution bin for a given day
pub fn run_solution(day: Day, is_timed: bool, is_release: bool) -> Result<Vec<String>, Error> {
// skip command invocation for days that have not been scaffolded yet.
if !Path::new(&get_path_for_bin(day)).exists() {
return Ok(vec![]);
}
let day_padded = day.to_string();
let mut args = vec!["run", "--quiet", "--bin", &day_padded];
if is_release {
args.push("--release");
}
if is_timed {
// mirror `--time` flag to child invocations.
args.push("--");
args.push("--time");
}
// spawn child command with piped stdout/stderr.
// forward output to stdout/stderr while grabbing stdout lines.
let mut cmd = Command::new("cargo")
.args(&args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let stdout = BufReader::new(cmd.stdout.take().ok_or(super::Error::BrokenPipe)?);
let stderr = BufReader::new(cmd.stderr.take().ok_or(super::Error::BrokenPipe)?);
let mut output = vec![];
let thread = thread::spawn(move || {
stderr.lines().for_each(|line| {
eprintln!("{}", line.unwrap());
});
});
for line in stdout.lines() {
let line = line.unwrap();
println!("{line}");
output.push(line);
}
thread.join().unwrap();
cmd.wait()?;
Ok(output)
}
pub fn parse_exec_time(output: &[String], day: Day) -> super::Timing {
let mut timings = super::Timing {
day,
part_1: None,
part_2: None,
total_nanos: 0_f64,
};
output
.iter()
.filter_map(|l| {
if !l.contains(" samples)") {
return None;
}
let Some((timing_str, nanos)) = parse_time(l) else {
eprintln!("Could not parse timings from line: {l}");
return None;
};
let part = l.split(':').next()?;
Some((part, timing_str, nanos))
})
.for_each(|(part, timing_str, nanos)| {
if part.contains("Part 1") {
timings.part_1 = Some(timing_str.into());
} else if part.contains("Part 2") {
timings.part_2 = Some(timing_str.into());
}
timings.total_nanos += nanos;
});
timings
}
fn parse_to_float(s: &str, postfix: &str) -> Option<f64> {
s.split(postfix).next()?.parse().ok()
}
fn parse_time(line: &str) -> Option<(&str, f64)> {
// for possible time formats, see: https://github.com/rust-lang/rust/blob/1.64.0/library/core/src/time.rs#L1176-L1200
let str_timing = line
.split(" samples)")
.next()?
.split('(')
.next_back()?
.split('@')
.next()?
.trim();
let parsed_timing = match str_timing {
s if s.contains("ns") => s.split("ns").next()?.parse::<f64>().ok(),
s if s.contains("µs") => parse_to_float(s, "µs").map(|x| x * 1000_f64),
s if s.contains("ms") => parse_to_float(s, "ms").map(|x| x * 1_000_000_f64),
s => parse_to_float(s, "s").map(|x| x * 1_000_000_000_f64),
}?;
Some((str_timing, parsed_timing))
}
/// copied from: https://github.com/rust-lang/rust/blob/1.64.0/library/std/src/macros.rs#L328-L333
#[cfg(feature = "test_lib")]
macro_rules! assert_approx_eq {
($a:expr, $b:expr) => {{
let (a, b) = (&$a, &$b);
assert!(
(*a - *b).abs() < 1.0e-6,
"{} is not approximately equal to {}",
*a,
*b
);
}};
}
#[cfg(feature = "test_lib")]
mod tests {
use super::parse_exec_time;
use crate::day;
#[test]
fn parses_execution_times() {
let res = parse_exec_time(
&[
"Part 1: 0 (74.13ns @ 100000 samples)".into(),
"Part 2: 10 (74.13ms @ 99999 samples)".into(),
"".into(),
],
day!(1),
);
assert_approx_eq!(res.total_nanos, 74130074.13_f64);
assert_eq!(res.part_1.unwrap(), "74.13ns");
assert_eq!(res.part_2.unwrap(), "74.13ms");
}
#[test]
fn parses_with_patterns_in_input() {
let res = parse_exec_time(
&[
"Part 1: @ @ @ ( ) ms (2s @ 5 samples)".into(),
"Part 2: 10s (100ms @ 1 samples)".into(),
"".into(),
],
day!(1),
);
assert_approx_eq!(res.total_nanos, 2100000000_f64);
assert_eq!(res.part_1.unwrap(), "2s");
assert_eq!(res.part_2.unwrap(), "100ms");
}
#[test]
fn parses_missing_parts() {
let res = parse_exec_time(
&[
"Part 1: ✖ ".into(),
"Part 2: ✖ ".into(),
"".into(),
],
day!(1),
);
assert_approx_eq!(res.total_nanos, 0_f64);
assert_eq!(res.part_1.is_none(), true);
assert_eq!(res.part_2.is_none(), true);
}
}
}
+167
View File
@@ -0,0 +1,167 @@
/// Encapsulates code that interacts with solution functions.
use std::fmt::Display;
use std::hint::black_box;
use std::io::{Write, stdout};
use std::process::Output;
use std::time::{Duration, Instant};
use std::{cmp, env, process};
use crate::template::ANSI_BOLD;
use crate::template::{ANSI_ITALIC, ANSI_RESET, Day, aoc_cli};
pub fn run_part<I: Copy, T: Display>(func: impl Fn(I) -> Option<T>, input: I, day: Day, part: u8) {
let part_str = format!("Part {part}");
let (result, duration, samples) =
run_timed(func, input, |result| print_result(result, &part_str, ""));
print_result(&result, &part_str, &format_duration(&duration, samples));
if let Some(result) = result {
submit_result(result, day, part);
}
}
/// Run a solution part. The behavior differs depending on whether we are running a release or debug build:
/// 1. in debug, the function is executed once.
/// 2. in release, the function is benched (approx. 1 second of execution time or 10 samples, whatever take longer.)
fn run_timed<I: Copy, T>(
func: impl Fn(I) -> T,
input: I,
hook: impl Fn(&T),
) -> (T, Duration, u128) {
let timer = Instant::now();
let result = {
#[cfg(feature = "dhat-heap")]
let _profiler = dhat::Profiler::new_heap();
func(input)
};
let base_time = timer.elapsed();
hook(&result);
let run = if std::env::args().any(|x| x == "--time") {
bench(func, input, &base_time)
} else {
(base_time, 1)
};
(result, run.0, run.1)
}
fn bench<I: Copy, T>(func: impl Fn(I) -> T, input: I, base_time: &Duration) -> (Duration, u128) {
let mut stdout = stdout();
print!(" > {ANSI_ITALIC}benching{ANSI_RESET}");
let _ = stdout.flush();
let bench_iterations =
(Duration::from_secs(1).as_nanos() / cmp::max(base_time.as_nanos(), 10)).clamp(10, 10000);
let mut timers: Vec<Duration> = vec![];
for _ in 0..bench_iterations {
let timer = Instant::now();
black_box(func(black_box(input)));
timers.push(timer.elapsed());
}
(
#[allow(clippy::cast_possible_truncation)]
Duration::from_nanos(average_duration(&timers) as u64),
bench_iterations,
)
}
fn average_duration(numbers: &[Duration]) -> u128 {
numbers
.iter()
.map(std::time::Duration::as_nanos)
.sum::<u128>()
/ numbers.len() as u128
}
fn format_duration(duration: &Duration, samples: u128) -> String {
if samples == 1 {
format!(" ({duration:.1?})")
} else {
format!(" ({duration:.1?} @ {samples} samples)")
}
}
fn print_result<T: Display>(result: &Option<T>, part: &str, duration_str: &str) {
let is_intermediate_result = duration_str.is_empty();
match result {
Some(result) => {
if result.to_string().contains('\n') {
let str = format!("{part}: ▼ {duration_str}");
if is_intermediate_result {
print!("{str}");
} else {
print!("\r");
println!("{str}");
println!("{result}");
}
} else {
let str = format!("{part}: {ANSI_BOLD}{result}{ANSI_RESET}{duration_str}");
if is_intermediate_result {
print!("{str}");
} else {
print!("\r");
println!("{str}");
}
}
}
None => {
if is_intermediate_result {
print!("{part}: ✖");
} else {
print!("\r");
println!("{part}: ✖ ");
}
}
}
}
/// Parse the arguments passed to `solve` and try to submit one part of the solution if:
/// 1. we are in `--release` mode.
/// 2. aoc-cli is installed.
fn submit_result<T: Display>(
result: T,
day: Day,
part: u8,
) -> Option<Result<Output, aoc_cli::AocCommandError>> {
let args: Vec<String> = env::args().collect();
if !args.contains(&"--submit".into()) {
return None;
}
if args.len() < 3 {
eprintln!("Unexpected command-line input. Format: cargo solve 1 --submit 1");
process::exit(1);
}
let part_index = args.iter().position(|x| x == "--submit").unwrap() + 1;
let Ok(part_submit) = args[part_index].parse::<u8>() else {
eprintln!("Unexpected command-line input. Format: cargo solve 1 --submit 1");
process::exit(1);
};
if part_submit != part {
return None;
}
if aoc_cli::check().is_err() {
eprintln!(
"command \"aoc\" not found or not callable. Try running \"cargo install aoc-cli\" to install it."
);
process::exit(1);
}
println!("Submitting result via aoc-cli...");
Some(aoc_cli::submit(day, part, &result.to_string()))
}
+384
View File
@@ -0,0 +1,384 @@
use std::{collections::HashMap, fs, io::Error, str::FromStr};
use tinyjson::JsonValue;
use crate::template::Day;
static TIMINGS_FILE_PATH: &str = "./data/timings.json";
/// Represents benchmark times for a single day.
#[derive(Clone, Debug)]
pub struct Timing {
pub day: Day,
pub part_1: Option<String>,
pub part_2: Option<String>,
pub total_nanos: f64,
}
/// Represents benchmark times for a set of days.
/// Can be serialized from / to JSON.
#[derive(Clone, Debug, Default)]
pub struct Timings {
pub data: Vec<Timing>,
}
impl Timings {
/// Dehydrate timings to a JSON file.
pub fn store_file(&self) -> Result<(), Error> {
let json = JsonValue::from(self.clone());
let mut file = fs::File::create(TIMINGS_FILE_PATH)?;
json.format_to(&mut file)
}
/// Rehydrate timings from a JSON file. If not present, returns empty timings.
pub fn read_from_file() -> Self {
fs::read_to_string(TIMINGS_FILE_PATH)
.map_err(|x| x.to_string())
.and_then(Timings::try_from)
.unwrap_or_default()
}
/// Merge two sets of timings, overwriting `self` with `other` if present.
pub fn merge(&self, new: &Self) -> Self {
let mut data: Vec<Timing> = vec![];
for timing in &new.data {
data.push(timing.clone());
}
for timing in &self.data {
if !data.iter().any(|t| t.day == timing.day) {
data.push(timing.clone());
}
}
data.sort_unstable_by(|a, b| a.day.cmp(&b.day));
Timings { data }
}
/// Sum up total duration of timings as millis.
pub fn total_millis(&self) -> f64 {
self.data.iter().map(|x| x.total_nanos).sum::<f64>() / 1_000_000_f64
}
pub fn is_day_complete(&self, day: Day) -> bool {
self.data
.iter()
.any(|t| t.day == day && t.part_1.is_some() && t.part_2.is_some())
}
}
/* -------------------------------------------------------------------------- */
impl From<Timings> for JsonValue {
fn from(value: Timings) -> Self {
let mut map: HashMap<String, JsonValue> = HashMap::new();
map.insert(
"data".into(),
JsonValue::Array(value.data.iter().map(JsonValue::from).collect()),
);
JsonValue::Object(map)
}
}
impl TryFrom<String> for Timings {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
let json = JsonValue::from_str(&value).or(Err("not valid JSON file."))?;
let json_data = json
.get::<HashMap<String, JsonValue>>()
.ok_or("expected JSON document to be an object.")?
.get("data")
.ok_or("expected JSON document to have key `data`.")?
.get::<Vec<JsonValue>>()
.ok_or("expected `json.data` to be an array.")?;
Ok(Timings {
data: json_data
.iter()
.map(Timing::try_from)
.collect::<Result<_, _>>()?,
})
}
}
/* -------------------------------------------------------------------------- */
impl From<&Timing> for JsonValue {
fn from(value: &Timing) -> Self {
let mut map: HashMap<String, JsonValue> = HashMap::new();
map.insert("day".into(), JsonValue::String(value.day.to_string()));
map.insert("total_nanos".into(), JsonValue::Number(value.total_nanos));
let part_1 = value.part_1.clone().map(JsonValue::String);
let part_2 = value.part_2.clone().map(JsonValue::String);
map.insert(
"part_1".into(),
match part_1 {
Some(x) => x,
None => JsonValue::Null,
},
);
map.insert(
"part_2".into(),
match part_2 {
Some(x) => x,
None => JsonValue::Null,
},
);
JsonValue::Object(map)
}
}
impl TryFrom<&JsonValue> for Timing {
type Error = String;
fn try_from(value: &JsonValue) -> Result<Self, Self::Error> {
let json = value
.get::<HashMap<String, JsonValue>>()
.ok_or("Expected timing to be a JSON object.")?;
let day = json
.get("day")
.and_then(|v| v.get::<String>())
.and_then(|day| Day::from_str(day).ok())
.ok_or("Expected timing.day to be a Day struct.")?;
let part_1 = json
.get("part_1")
.map(|v| if v.is_null() { None } else { v.get::<String>() })
.ok_or("Expected timing.part_1 to be null or string.")?;
let part_2 = json
.get("part_2")
.map(|v| if v.is_null() { None } else { v.get::<String>() })
.ok_or("Expected timing.part_2 to be null or string.")?;
let total_nanos = json
.get("total_nanos")
.and_then(|v| v.get::<f64>().copied())
.ok_or("Expected timing.total_nanos to be a number.")?;
Ok(Timing {
day,
part_1: part_1.cloned(),
part_2: part_2.cloned(),
total_nanos,
})
}
}
/* -------------------------------------------------------------------------- */
#[cfg(feature = "test_lib")]
mod tests {
use crate::day;
use super::{Timing, 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: None,
total_nanos: 4e+10,
},
],
}
}
mod deserialization {
use crate::{day, template::timings::Timings};
#[test]
fn handles_json_timings() {
let json = r#"{ "data": [{ "day": "01", "part_1": "1ms", "part_2": null, "total_nanos": 1000000000 }] }"#.to_string();
let timings = Timings::try_from(json).unwrap();
assert_eq!(timings.data.len(), 1);
let timing = timings.data.first().unwrap();
assert_eq!(timing.day, day!(1));
assert_eq!(timing.part_1, Some("1ms".to_string()));
assert_eq!(timing.part_2, None);
assert_eq!(timing.total_nanos, 1_000_000_000_f64);
}
#[test]
fn handles_empty_timings() {
let json = r#"{ "data": [] }"#.to_string();
let timings = Timings::try_from(json).unwrap();
assert_eq!(timings.data.len(), 0);
}
#[test]
#[should_panic]
fn panics_for_invalid_json() {
let json = r#"{}"#.to_string();
Timings::try_from(json).unwrap();
}
#[test]
#[should_panic]
fn panics_for_malformed_timings() {
let json = r#"{ "data": [{ "day": "01" }, { "day": "26" }, { "day": "02", "part_2": null, "total_nanos": 0 }] }"#.to_string();
Timings::try_from(json).unwrap();
}
}
mod serialization {
use super::get_mock_timings;
use std::collections::HashMap;
use tinyjson::JsonValue;
#[test]
fn serializes_timings() {
let timings = get_mock_timings();
let value = JsonValue::try_from(timings).unwrap();
assert_eq!(
value
.get::<HashMap<String, JsonValue>>()
.unwrap()
.get("data")
.unwrap()
.get::<Vec<JsonValue>>()
.unwrap()
.len(),
3
);
}
}
mod is_day_complete {
use crate::{
day,
template::timings::{Timing, Timings},
};
#[test]
fn handles_completed_days() {
let timings = Timings {
data: vec![Timing {
day: day!(1),
part_1: Some("1ms".into()),
part_2: Some("2ms".into()),
total_nanos: 3_000_000_000_f64,
}],
};
assert_eq!(timings.is_day_complete(&day!(1)), true);
}
#[test]
fn handles_partial_days() {
let timings = Timings {
data: vec![Timing {
day: day!(1),
part_1: Some("1ms".into()),
part_2: None,
total_nanos: 1_000_000_000_f64,
}],
};
assert_eq!(timings.is_day_complete(&day!(1)), false);
}
#[test]
fn handles_uncompleted_days() {
let timings = Timings {
data: vec![Timing {
day: day!(1),
part_1: None,
part_2: None,
total_nanos: 0.0,
}],
};
assert_eq!(timings.is_day_complete(&day!(1)), false);
}
}
mod merge {
use crate::{
day,
template::timings::{Timing, Timings},
};
use super::get_mock_timings;
#[test]
fn handles_disjunct_timings() {
let timings = get_mock_timings();
let other = Timings {
data: vec![Timing {
day: day!(3),
part_1: None,
part_2: None,
total_nanos: 0_f64,
}],
};
let merged = timings.merge(&other);
assert_eq!(merged.data.len(), 4);
assert_eq!(merged.data[0].day, day!(1));
assert_eq!(merged.data[1].day, day!(2));
assert_eq!(merged.data[2].day, day!(3));
assert_eq!(merged.data[3].day, day!(4));
}
#[test]
fn handles_overlapping_timings() {
let timings = get_mock_timings();
let other = Timings {
data: vec![Timing {
day: day!(2),
part_1: None,
part_2: None,
total_nanos: 0_f64,
}],
};
let merged = timings.merge(&other);
assert_eq!(merged.data.len(), 3);
assert_eq!(merged.data[0].day, day!(1));
assert_eq!(merged.data[1].day, day!(2));
assert_eq!(merged.data[1].total_nanos, 0_f64);
assert_eq!(merged.data[2].day, day!(4));
}
#[test]
fn handles_empty_timings() {
let timings = Timings::default();
let other = get_mock_timings();
let merged = timings.merge(&other);
assert_eq!(merged.data.len(), 3);
}
#[test]
fn handles_empty_other_timings() {
let timings = get_mock_timings();
let other = Timings::default();
let merged = timings.merge(&other);
assert_eq!(merged.data.len(), 3);
}
}
}