Use function pointers over dyn traits

This commit is contained in:
2021-11-28 16:49:37 +01:00
parent c985ba8a1a
commit 186d91d1b7
3 changed files with 21 additions and 37 deletions

View File

@@ -1,29 +1,19 @@
use std::io::Read;
type Solution = fn(&mut dyn Read) -> String;
mod day01;
pub trait Solution {
fn part1(&mut self, input: &mut dyn Read) -> String;
fn part2(&mut self, _input: &mut dyn Read) -> String {
unimplemented!("Still working on part 1");
pub fn get_implementation(day: usize, part2: bool) -> Solution {
if !part2 {
match day {
1 => day01::part1,
_ => panic!("Unsupported part one for day {}", day),
}
} else {
match day {
1 => day01::part2,
_ => panic!("Unsupported part two for day {}", day),
}
}
}
pub fn get_implementation(day: usize) -> Box<dyn Solution> {
match day {
1 => Box::new(day01::Day01::default()),
_ => panic!("Unsupported day {}", day),
}
}
#[cfg(test)]
fn test_implementation(mut day: impl Solution, part: u8, mut input: &[u8], answer: impl ToString) {
let result = match part {
1 => day.part1(&mut input),
2 => day.part2(&mut input),
_ => panic!("Invalid part: {}", part),
};
assert_eq!(answer.to_string(), result);
}