mkz_aoc/src/file.rs

65 lines
1.7 KiB
Rust

//! This module proposes reading file helper functions.
use std::fs;
use crate::parse::string_to_numbers;
/// Read a file & return its contents in a Vec<String> structure
///
/// ```
/// use mkz_aoc::file;
///
/// fn main() {
/// let lines = file ::read_to_numbers("input.txt");
/// }
/// ```
pub fn read_to_lines(_filename: &str) -> Result<Vec<String>, String> {
let _contents = fs::read_to_string(_filename);
if let Err(v) = _contents {
return Err(format!("Could not read file: {}", v));
}
let lines = _contents.unwrap().lines().map(|x| x.to_string()).collect::<Vec<String>>();
Ok(lines)
}
/// Read a file & return its contents in a Vec<i128> structure
pub fn read_to_numbers(_filename: &str) -> Result<Vec<i128>, String> {
let _lines = read_to_lines(_filename);
if let Err(v) = _lines {
return Err(v);
}
Ok(_lines.unwrap().iter().map(|x| x.parse::<i128>().unwrap()).collect::<Vec<i128>>())
}
/// Read a file & return its first line in a String
pub fn read_to_string(_filename: &str) -> Result<String, String> {
let _lines = read_to_lines(_filename);
match _lines {
Ok(lines) => if lines.len() >= 1 {
Ok(lines[0].clone())
} else {
Err(String::from("Missing content"))
},
Err(v) => Err(v)
}
}
/// Read a file for a matrix & return it in a Vec<Vec<i128>> data structure.
pub fn read_to_matrix(_filename: &str) -> Result<Vec<Vec<i128>>, String> {
let _lines = read_to_lines(_filename);
if let Err(v) = _lines {
return Err(v);
}
Ok(_lines
.unwrap()
.iter()
.map(|x| string_to_numbers(x.to_string()))
.collect()
)
}