aoc_framework/
input.rs

1use std::fs;
2
3/// The `InputLoader` trait is used to load the input data for the challenge.
4/// It is implemented for different types of input data such as files, strings and https.
5pub trait InputLoader {
6    /// Loads the input data and returns it as a `Vec<String>`.
7    fn load(&self) -> Vec<String>;
8}
9
10/// Creates a `InputLoader` which loads the input data from a file.
11/// Each line of the file will be returned as a `String` in the `Vec`.
12/// This method is a convenience method for `FileLoader::new(path)`.
13pub fn from_file(path: &str) -> FileLoader {
14    FileLoader::new(path.to_string())
15}
16
17/// The `FileLoader` is used to load the input data from a file.
18pub struct FileLoader {
19    path: String
20}
21
22impl FileLoader {
23    /// Creates a new `FileLoader` for the given path.
24    pub fn new(path: String) -> Self {
25        FileLoader {
26            path
27        }
28    }
29}
30
31impl InputLoader for FileLoader {
32    fn load(&self) -> Vec<String> {
33        let file_content = fs::read_to_string(&self.path).expect("Unable to read file");
34        file_content.lines().map(|line| line.to_string()).collect()
35    }
36}
37
38pub struct StringLoader {
39    input: String
40}
41
42impl StringLoader {
43    pub fn new(input: String) -> Self {
44        StringLoader {
45            input
46        }
47    }
48}
49
50impl InputLoader for StringLoader {
51    fn load(&self) -> Vec<String> {
52        self.input.lines().map(|line| line.to_string()).collect()
53    }
54}
55
56pub struct HTTPLoader {
57    url: String
58}
59
60impl HTTPLoader {
61    pub fn new(url: String) -> Self {
62        HTTPLoader {
63            url
64        }
65    }
66}
67
68impl InputLoader for HTTPLoader {
69    fn load(&self) -> Vec<String> {
70        let body = reqwest::blocking::get(&self.url).unwrap().text().unwrap();
71        body.lines().map(|line| line.to_string()).collect()
72    }
73}