diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 2475a54..4ce7b67 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -2,6 +2,7 @@ "recommendations": [ "vadimcn.vscode-lldb", "rust-lang.rust-analyzer", - "serayuzgur.crates" + "serayuzgur.crates", + "editorConfig.editorConfig" ] -} \ No newline at end of file +} diff --git a/.vscode/launch.json b/.vscode/launch.json index 0a9370e..8f244cf 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -7,13 +7,15 @@ { "type": "lldb", "request": "launch", - "name": "Debug unit tests in executable 'advent_of_code'", + "name": "Debug unit tests for a solution", "cargo": { - "args": ["test", "--no-run", "--bin=advent_of_code", "--package=advent_of_code"], - "filter": { - "name": "advent_of_code", - "kind": "bin" - } + "args": [ + "test", + "--no-run", + // replace `01` here with the solution you like to debug. + "--bin=01", + "--package=advent_of_code" + ], }, "args": [], "cwd": "${workspaceFolder}" @@ -21,15 +23,15 @@ { "type": "lldb", "request": "launch", - "name": "Debug executable 'advent_of_code'", + "name": "Debug a solution", "cargo": { - "args": ["build", "--bin=advent_of_code", "--package=advent_of_code"], - "filter": { - "name": "advent_of_code", - "kind": "bin" - } + "args": [ + "build", + // replace `01` here with the solution you like to debug. + "--bin=01", + "--package=advent_of_code" + ], }, - "args": ["1"], "cwd": "${workspaceFolder}" }, { @@ -37,7 +39,13 @@ "request": "launch", "name": "Debug unit tests in library 'advent_of_code'", "cargo": { - "args": ["test", "--no-run", "--lib", "--package=advent_of_code"], + "args": [ + "test", + "--no-run", + "--lib", + "--features=test_lib", + "--package=advent_of_code" + ], "filter": { "name": "advent_of_code", "kind": "lib" diff --git a/Cargo.lock b/Cargo.lock index 6111560..1ae9464 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,7 +19,7 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "advent_of_code" -version = "0.10.0" +version = "0.11.0" dependencies = [ "chrono", "dhat", diff --git a/Cargo.toml b/Cargo.toml index 584e150..3396495 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "advent_of_code" -version = "0.10.0" +version = "0.11.0" authors = ["Felix Spöttel <1682504+fspoettel@users.noreply.github.com>"] edition = "2021" default-run = "advent_of_code" @@ -20,7 +20,11 @@ today = ["chrono"] test_lib = [] [dependencies] + +# Template dependencies chrono = { version = "0.4.31", optional = true } dhat = { version = "0.3.2", optional = true } pico-args = "0.5.0" -tinyjson = "2" +tinyjson = "2.5.1" + +# Solution dependencies diff --git a/README.md b/README.md index 472f8ba..a155efa 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Individual solutions live in the `./src/bin/` directory as separate binaries. _I Every [solution](https://github.com/fspoettel/advent-of-code-rust/blob/main/src/template.txt) has _tests_ referencing its _example_ file in `./data/examples`. Use these tests to develop and debug your solutions against the example input. In VS Code, `rust-analyzer` will display buttons for running / debugging these unit tests above the unit test blocks. > [!TIP] -> If a day has different example inputs for both parts, you can use the `read_file_part()` helper in your tests instead of `read_file()`. For example, if this applies to day 1, you can create a second example file `01-2.txt` and invoke the helper like `let result = part_two(&advent_of_code::template::read_file_part("examples", DAY, 2));` to read it in `test_part_two`. +> If a day has multiple example inputs, you can use the `read_file_part()` helper in your tests instead of `read_file()`. If this e.g. applies to day 1, you can create a second example file `01-2.txt` and invoke the helper like `let result = part_two(&advent_of_code::template::read_file_part("examples", DAY, 2));`. This supports an arbitrary number of example files. ### ➡️ Download input for a day @@ -89,16 +89,12 @@ cargo solve The `solve` command runs your solution against real puzzle inputs. To run an optimized build of your code, append the `--release` flag as with any other rust program. -By default, `solve` executes your code once and shows the execution time. If you append the `--time` flag to the command, the runner will run your code between `10` and `10.000` times (depending on execution time of first execution) and print the average execution time. - -For example, running a benchmarked, optimized execution of day 1 would look like `cargo solve 1 --release --time`. Displayed _timings_ show the raw execution time of your solution without overhead like file reads. - #### Submitting solutions > [!IMPORTANT] > This requires [installing the aoc-cli crate](#configure-aoc-cli-integration). -In order to submit part of a solution for checking, append the `--submit ` option to the `solve` command. +Append the `--submit ` option to the `solve` command to submit your solution for checking. ### ➡️ Run all solutions @@ -116,36 +112,45 @@ cargo all # Total: 0.20ms ``` -This runs all solutions sequentially and prints output to the command-line. Same as for the `solve` command, the `--release` flag runs an optimized build and the `--time` flag outputs benchmarks. - -### ➡️ Update readme benchmarks +This runs all solutions sequentially and prints output to the command-line. Same as for the `solve` command, the `--release` flag runs an optimized build. -The template can write benchmark times to the README via the `cargo time` command. +### ➡️ Benchmark your solutions -By default, this command checks for missing benchmarks, runs those solutions, and then updates the table. If you want to (re-)time all solutions, run `cargo time --all`. If you want to (re-)time one specific solution, run `cargo time `. +```sh +# example: `cargo time 8 --store` +cargo time [--all] [--store] -Please note that these are not _scientific_ benchmarks, understand them as a fun approximation. 😉 Timings, especially in the microseconds range, might change a bit between invocations. +# output: +# Day 08 +# ------ +# Part 1: 1 (39.0ns @ 10000 samples) +# Part 2: 2 (39.0ns @ 10000 samples) +# +# Total (Run): 0.00ms +# +# Stored updated benchmarks. +``` -### ➡️ Run all tests +The `cargo time` command allows you to benchmark your code and store timings in the readme. When benching, the runner will run your code between `10` and `10.000` times, depending on execution time of first execution, and print the average execution time. -```sh -cargo test -``` +`cargo time` has three modes of execution: -To run tests for a specific day, append `--bin `, e.g. `cargo test --bin 01`. You can further scope it down to a specific part, e.g. `cargo test --bin 01 part_one`. + 1. `cargo time` without arguments incrementally benches solutions that do not have been stored in the readme yet and skips the rest. + 2. `cargo time ` benches a single solution. + 3. `cargo time --all` benches all solutions. -### ➡️ Format code +By default, `cargo time` does not write to the readme. In order to do so, append the `--store` flag: `cargo time --store`. -```sh -cargo fmt -``` +> Please note that these are not _scientific_ benchmarks, understand them as a fun approximation. 😉 Timings, especially in the microseconds range, might change a bit between invocations. -### ➡️ Lint code +### ➡️ Run all tests ```sh -cargo clippy +cargo test ``` +To run tests for a specific day, append `--bin `, e.g. `cargo test --bin 01`. You can further scope it down to a specific part, e.g. `cargo test --bin 01 part_one`. + ### ➡️ Read puzzle description > [!IMPORTANT] @@ -196,12 +201,24 @@ cargo today # ...the input... ``` +### ➡️ Format code + +```sh +cargo fmt +``` + +### ➡️ Lint code + +```sh +cargo clippy +``` + ## Optional template features ### Configure aoc-cli integration 1. Install [`aoc-cli`](https://github.com/scarvalhojr/aoc-cli/) via cargo: `cargo install aoc-cli --version 0.12.0` -2. Create an `.adventofcode.session` file in your home directory and paste your session cookie. To retrieve the session cookie, press F12 anywhere on the Advent of Code website to open your browser developer tools. Look in _Cookies_ under the _Application_ or _Storage_ tab, and copy out the `session` cookie value. [^1] +2. Create the file `/.adventofcode.session` and paste your session cookie into it. To retrieve the session cookie, press F12 anywhere on the Advent of Code website to open your browser developer tools. Look in _Cookies_ under the _Application_ or _Storage_ tab, and copy out the `session` cookie value. [^1] Once installed, you can use the [download command](#download-input--description-for-a-day), the read command, and automatically submit solutions via the [`--submit` flag](#submitting-solutions). @@ -229,7 +246,7 @@ Go to the _Variables_ tab in your repository settings and create the following v ✨ You can now run this action manually via the _Run workflow_ button on the workflow page. If you want the workflow to run automatically, uncomment the `schedule` section in the `readme-stars.yml` workflow file or add a `push` trigger. -### Check code formatting / clippy lints in CI +### Enable code formatting / clippy checks in the CI Uncomment the respective sections in the `ci.yml` workflow. diff --git a/src/lib.rs b/src/lib.rs index 612b5b9..27d7df8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,3 @@ pub mod template; + +// Use this file to add helper functions and additional modules. diff --git a/src/main.rs b/src/main.rs index 57d4fe3..9322423 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,17 +24,16 @@ mod args { Solve { day: Day, release: bool, - time: bool, dhat: bool, submit: Option, }, All { release: bool, - time: bool, }, Time { all: bool, day: Option, + store: bool, }, #[cfg(feature = "today")] Today, @@ -46,14 +45,15 @@ mod args { let app_args = match args.subcommand()?.as_deref() { Some("all") => AppArguments::All { release: args.contains("--release"), - time: args.contains("--time"), }, 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 { @@ -70,7 +70,6 @@ mod args { day: args.free_from_str()?, release: args.contains("--release"), submit: args.opt_value_from_str("--submit")?, - time: args.contains("--time"), dhat: args.contains("--dhat"), }, #[cfg(feature = "today")] @@ -101,8 +100,8 @@ fn main() { std::process::exit(1); } Ok(args) => match args { - AppArguments::All { release, time } => all::handle(release, time), - AppArguments::Time { day, all } => time::handle(day, all), + 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 } => { @@ -114,10 +113,9 @@ fn main() { AppArguments::Solve { day, release, - time, dhat, submit, - } => solve::handle(day, release, time, dhat, submit), + } => solve::handle(day, release, dhat, submit), #[cfg(feature = "today")] AppArguments::Today => { match Day::today() { diff --git a/src/template/commands/all.rs b/src/template/commands/all.rs index 444497d..b844e1e 100644 --- a/src/template/commands/all.rs +++ b/src/template/commands/all.rs @@ -1,5 +1,5 @@ use crate::template::{all_days, run_multi::run_multi}; -pub fn handle(is_release: bool, is_timed: bool) { - run_multi(all_days().collect(), is_release, is_timed); +pub fn handle(is_release: bool) { + run_multi(&all_days().collect(), is_release, false); } diff --git a/src/template/commands/scaffold.rs b/src/template/commands/scaffold.rs index 8afdaed..4e7d7c0 100644 --- a/src/template/commands/scaffold.rs +++ b/src/template/commands/scaffold.rs @@ -65,5 +65,5 @@ pub fn handle(day: Day) { } println!("---"); - println!("🎄 Type `cargo solve {}` to run your solution.", day); + println!("🎄 Type `cargo solve {day}` to run your solution."); } diff --git a/src/template/commands/solve.rs b/src/template/commands/solve.rs index 66771c0..ec92a6f 100644 --- a/src/template/commands/solve.rs +++ b/src/template/commands/solve.rs @@ -2,7 +2,7 @@ use std::process::{Command, Stdio}; use crate::template::Day; -pub fn handle(day: Day, release: bool, time: bool, dhat: bool, submit_part: Option) { +pub fn handle(day: Day, release: bool, dhat: bool, submit_part: Option) { let mut cmd_args = vec!["run".to_string(), "--bin".to_string(), day.to_string()]; if dhat { @@ -23,10 +23,6 @@ pub fn handle(day: Day, release: bool, time: bool, dhat: bool, submit_part: Opti cmd_args.push(submit_part.to_string()); } - if time { - cmd_args.push("--time".to_string()); - } - let mut cmd = Command::new("cargo") .args(&cmd_args) .stdout(Stdio::inherit()) diff --git a/src/template/commands/time.rs b/src/template/commands/time.rs index ce110ab..49b91a8 100644 --- a/src/template/commands/time.rs +++ b/src/template/commands/time.rs @@ -4,32 +4,37 @@ use crate::template::run_multi::run_multi; use crate::template::timings::Timings; use crate::template::{all_days, readme_benchmarks, Day}; -pub fn handle(day: Option, recreate_all: bool) { +pub fn handle(day: Option, run_all: bool, store: bool) { let stored_timings = Timings::read_from_file(); - let days_to_run = day.map(|day| HashSet::from([day])).unwrap_or_else(|| { - if recreate_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() - } - }); + 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(); + let timings = run_multi(&days_to_run, true, true).unwrap(); - let merged_timings = stored_timings.merge(&timings); - merged_timings.store_file().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."); + println!(); + match readme_benchmarks::update(merged_timings) { + Ok(()) => { + println!("Stored updated benchmarks."); + } + Err(_) => { + eprintln!("Failed to store updated benchmarks."); + } } } } diff --git a/src/template/day.rs b/src/template/day.rs index ca264b8..99b8280 100644 --- a/src/template/day.rs +++ b/src/template/day.rs @@ -3,7 +3,10 @@ use std::fmt::Display; use std::str::FromStr; #[cfg(feature = "today")] -use chrono::{Datelike, Local}; +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). /// @@ -44,7 +47,8 @@ impl Day { impl Day { /// Returns the current day if it's between the 1st and the 25th of december, `None` otherwise. pub fn today() -> Option { - let today = Local::now(); + 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 { diff --git a/src/template/run_multi.rs b/src/template/run_multi.rs index 0fdf2d5..5bafefb 100644 --- a/src/template/run_multi.rs +++ b/src/template/run_multi.rs @@ -7,31 +7,32 @@ use super::{ timings::{Timing, Timings}, }; -pub fn run_multi(days_to_run: HashSet, is_release: bool, is_timed: bool) -> Option { +pub fn run_multi(days_to_run: &HashSet, is_release: bool, is_timed: bool) -> Option { let mut timings: Vec = Vec::with_capacity(days_to_run.len()); - all_days().for_each(|day| { - if day > 1 { - println!(); - } + let mut need_space = false; - println!("{ANSI_BOLD}Day {day}{ANSI_RESET}"); - println!("------"); + // 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; - if !days_to_run.contains(&day) { - println!("Skipped."); - return; - } + println!("{ANSI_BOLD}Day {day}{ANSI_RESET}"); + println!("------"); - let output = child_commands::run_solution(day, is_timed, is_release).unwrap(); + 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 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 }; diff --git a/src/template/timings.rs b/src/template/timings.rs index f7dc091..194464e 100644 --- a/src/template/timings.rs +++ b/src/template/timings.rs @@ -38,7 +38,7 @@ impl Timings { match s { Ok(timings) => timings, Err(e) => { - eprintln!("{}", e); + eprintln!("{e}"); Timings::default() } } @@ -67,10 +67,10 @@ impl Timings { self.data.iter().map(|x| x.total_nanos).sum::() / 1_000_000_f64 } - pub fn is_day_complete(&self, day: &Day) -> bool { + 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()) + .any(|t| t.day == day && t.part_1.is_some() && t.part_2.is_some()) } }