1
0

Replace filename const by sanitise() function

This commit is contained in:
Stefan Müller
2025-12-08 17:07:34 +01:00
parent 449e7f75ac
commit c03eca490e
6 changed files with 27 additions and 14 deletions
+19 -11
View File
@@ -1,6 +1,8 @@
use sanitise_file_name;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::path;
use std::path::Path;
pub mod cafeteria;
@@ -10,12 +12,13 @@ pub mod trash_compactor;
pub trait Solver {
const PUZZLE_INDEX: u8;
const PUZZLE_NAME: &'static str;
// TODO: Replace constant input filename by a conversion from the puzzle name in the runner.
const INPUT_FILENAME: &'static str;
fn puzzle_index(&self) -> u8 { Self::PUZZLE_INDEX }
fn puzzle_name(&self) -> &'static str { Self::PUZZLE_NAME }
fn input_filename(&self) -> &'static str { Self::INPUT_FILENAME }
fn puzzle_index(&self) -> u8 {
Self::PUZZLE_INDEX
}
fn puzzle_name(&self) -> &'static str {
Self::PUZZLE_NAME
}
fn process_data<R: BufRead>(&self, reader: R) -> (u64, u64);
}
@@ -32,7 +35,11 @@ pub fn run<S: Solver>(solver: S) {
// "target/release/" directory with "data/" directory in package root or parent directory.
let paths = vec!["./data", "../data", "../../data", "../../../data"];
match read_data_file(solver.input_filename(), &paths) {
let filename = sanitise_file_name::sanitise(solver.puzzle_name())
.to_lowercase()
.replace(" ", "_")
+ ".txt";
match read_data_file(filename, &paths) {
Ok(reader) => {
let result = solver.process_data(reader);
print_result(result);
@@ -45,10 +52,7 @@ fn print_result(result: (u64, u64)) {
println!("Part 1: {:?}\nPart 2: {:?}\n", result.0, result.1);
}
fn read_data_file<T>(
filename: T,
search_paths: &Vec<T>,
) -> Result<io::BufReader<File>, String>
fn read_data_file<T>(filename: String, search_paths: &Vec<T>) -> Result<io::BufReader<File>, String>
where
T: AsRef<Path>,
{
@@ -60,7 +64,11 @@ where
let message = search_paths
.iter()
.map(|path| path.as_ref().join(&filename).display().to_string())
.filter_map(|p| {
path::absolute(p.as_ref().join(&filename))
.ok()
.and_then(|p| Some(p.display().to_string()))
})
.collect::<Vec<_>>()
.join("\n");
Err(format!(