From 186d91d1b70968e40e62d0f713467fb54cfc3a7a Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Sun, 28 Nov 2021 16:49:37 +0100 Subject: [PATCH] Use function pointers over dyn traits --- 2021/src/day01.rs | 15 +++++++-------- 2021/src/lib.rs | 36 +++++++++++++----------------------- 2021/src/main.rs | 7 +------ 3 files changed, 21 insertions(+), 37 deletions(-) diff --git a/2021/src/day01.rs b/2021/src/day01.rs index 1a26a6a..113ba49 100644 --- a/2021/src/day01.rs +++ b/2021/src/day01.rs @@ -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 { - todo!() - } +pub fn part1(_input: &mut dyn Read) -> String { + todo!() +} + +pub fn part2(_input: &mut dyn Read) -> String { + todo!() } diff --git a/2021/src/lib.rs b/2021/src/lib.rs index 016638d..9c60b8b 100644 --- a/2021/src/lib.rs +++ b/2021/src/lib.rs @@ -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 { - 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); -} diff --git a/2021/src/main.rs b/2021/src/main.rs index 4d775b1..00e7778 100644 --- a/2021/src/main.rs +++ b/2021/src/main.rs @@ -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 = 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));