From 38dc536984b08f246b13d54632fd380255d6293e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20Sp=C3=B6ttel?= <1682504+fspoettel@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:25:07 +0100 Subject: [PATCH] feat: add `read_file_part()` helper closes #37 --- README.md | 3 +++ src/template/mod.rs | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/README.md b/README.md index 59d1adf..85aba56 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,9 @@ 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/commands/scaffold.rs#L9-L35) has _tests_ referencing its _example_ file in `./data/examples`. Use these tests to develop and debug your solutions against the example input. +> [!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`. + > [!TIP] > when editing a solution, `rust-analyzer` will display buttons for running / debugging unit tests above the unit test blocks. diff --git a/src/template/mod.rs b/src/template/mod.rs index 4403b95..a87ceed 100644 --- a/src/template/mod.rs +++ b/src/template/mod.rs @@ -19,6 +19,15 @@ pub fn read_file(folder: &str, day: Day) -> String { 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. #[macro_export] macro_rules! solution {