aoc_toolbox/
utils.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
use std::env;
use std::fs::read_dir;
use std::fs::read_to_string;
use std::io;
use std::io::ErrorKind;
use std::path::PathBuf;

fn get_project_root() -> io::Result<PathBuf> {
    let path = env::current_dir()?;
    let path_ancestors = path.as_path().ancestors();

    for p in path_ancestors {
        let has_cargo = read_dir(p)?.any(|p| p.unwrap().file_name() == *"Cargo.lock");
        if has_cargo {
            return Ok(PathBuf::from(p));
        }
    }
    Err(io::Error::new(
        ErrorKind::NotFound,
        "Ran out of places to find Cargo.toml",
    ))
}

pub fn load_input(filename: &str) -> String {
    let mut path = get_project_root().expect("Cannot get root");
    path.push("input/");
    path.push(filename);
    path.set_extension("txt");

    read_to_string(&path)
        .unwrap_or_else(|_| panic!("Cannot read input file \"{}\"", path.display()))
}