summaryrefslogtreecommitdiffstats
path: root/aoc/src
diff options
context:
space:
mode:
authorGravatar Tom van der Lee <tom@vanderlee.io>2024-12-02 09:05:35 +0100
committerGravatar Tom van der Lee <tom@vanderlee.io>2024-12-02 09:05:35 +0100
commitc459715f321248cab0cc7081667bb61116d4fc31 (patch)
treec2e40266d630a82200c65b1dee0d8ad542242a4a /aoc/src
download2024-c459715f321248cab0cc7081667bb61116d4fc31.tar.gz
2024-c459715f321248cab0cc7081667bb61116d4fc31.tar.bz2
2024-c459715f321248cab0cc7081667bb61116d4fc31.zip
Base framework
Diffstat (limited to 'aoc/src')
-rw-r--r--aoc/src/lib.rs74
1 files changed, 74 insertions, 0 deletions
diff --git a/aoc/src/lib.rs b/aoc/src/lib.rs
new file mode 100644
index 0000000..5fad72d
--- /dev/null
+++ b/aoc/src/lib.rs
@@ -0,0 +1,74 @@
1use clap::Parser;
2use std::fs::File;
3use std::io;
4use std::io::{BufRead, BufReader, Read};
5
6#[derive(Parser, Debug)]
7#[command(version, about, long_about = None)]
8struct Args {
9 #[arg(short, long, default_value = "-")]
10 file: String,
11
12 #[arg(short, long, default_value_t = 1)]
13 part: u8,
14}
15
16pub trait Day {
17 fn example_input(&self) -> &'static str;
18 fn example_result_part_1(&self) -> &'static str;
19 fn example_result_part_2(&self) -> &'static str;
20
21 fn read_lines(&self, input: BufReader<Box<dyn Read>>) -> Vec<String> {
22 let mut lines = Vec::new();
23
24 for line in input.lines() {
25 match line {
26 Ok(content) => lines.push(content),
27 Err(e) => eprintln!("Error reading line: {}", e),
28 }
29 }
30
31 lines
32 }
33
34 fn part_1(&self, input: BufReader<Box<dyn Read>>) -> String;
35 fn part_2(&self, input: BufReader<Box<dyn Read>>) -> String;
36}
37
38pub fn main(day: &dyn Day) {
39 let args = Args::parse();
40
41 let reader: Box<dyn Read> = if args.file == "-" {
42 Box::new(io::stdin())
43 } else {
44 Box::new(File::open(&args.file).expect("Failed to open file"))
45 };
46
47 let buffer = BufReader::new(reader);
48
49 let result: String;
50 if args.part == 1 {
51 result = day.part_1(buffer);
52 } else {
53 result = day.part_2(buffer);
54 }
55
56 println!("Result: {result}")
57}
58
59pub fn test_day<T: Day>(day: &T) {
60 use std::io::Cursor;
61 use std::io::{BufReader, Read};
62
63 let example_input = day.example_input();
64
65 // Test Part 1
66 let input = BufReader::new(Box::new(Cursor::new(example_input)) as Box<dyn Read>);
67 let output = day.part_1(input);
68 assert_eq!(output.trim(), day.example_result_part_1(), "Part 1 failed");
69
70 // Test Part 2
71 let input = BufReader::new(Box::new(Cursor::new(example_input)) as Box<dyn Read>);
72 let output = day.part_2(input);
73 assert_eq!(output.trim(), day.example_result_part_2(), "Part 2 failed");
74} \ No newline at end of file