mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
Use function pointers over dyn traits
This commit is contained in:
@@ -1,10 +1,9 @@
|
||||
use crate::Solution;
|
||||
use std::io::Read;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Day01;
|
||||
|
||||
impl Solution for Day01 {
|
||||
fn part1(&mut self, _input: &mut dyn std::io::Read) -> String {
|
||||
pub fn part1(_input: &mut dyn Read) -> String {
|
||||
todo!()
|
||||
}
|
||||
|
||||
pub fn part2(_input: &mut dyn Read) -> String {
|
||||
todo!()
|
||||
}
|
||||
|
||||
@@ -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) -> Box<dyn Solution> {
|
||||
pub fn get_implementation(day: usize, part2: bool) -> Solution {
|
||||
if !part2 {
|
||||
match day {
|
||||
1 => Box::new(day01::Day01::default()),
|
||||
_ => panic!("Unsupported day {}", day),
|
||||
1 => day01::part1,
|
||||
_ => panic!("Unsupported part one for day {}", day),
|
||||
}
|
||||
} else {
|
||||
match day {
|
||||
1 => day01::part2,
|
||||
_ => panic!("Unsupported part two for 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);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ struct Opts {
|
||||
fn main() {
|
||||
let opts: Opts = Opts::parse();
|
||||
|
||||
let mut implementation = get_implementation(opts.day.get());
|
||||
let mut input: Box<dyn Read> = if let Some(input) = opts.input {
|
||||
Box::new(File::open(&input).expect("Failed to open input"))
|
||||
} else {
|
||||
@@ -38,11 +37,7 @@ fn main() {
|
||||
};
|
||||
|
||||
let begin = Instant::now();
|
||||
let result = if opts.part2 {
|
||||
implementation.part2(&mut input)
|
||||
} else {
|
||||
implementation.part1(&mut input)
|
||||
};
|
||||
let result = get_implementation(opts.day.get(), opts.part2)(&mut *input);
|
||||
|
||||
if opts.time {
|
||||
eprintln!("Execution time: {:?}", Instant::now().duration_since(begin));
|
||||
|
||||
Reference in New Issue
Block a user