1
0
Fork 0
2023/src/input.rs
Matej Focko 3afb870cf1
chore: initialize with '22 template
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-02 18:46:37 +01:00

56 lines
1.6 KiB
Rust

//! # Input-related utilities
use std::fmt::Debug;
use std::fs::read_to_string;
use std::ops::Deref;
use std::path::Path;
use std::str::FromStr;
/// Reads file to the string.
pub fn file_to_string<P: AsRef<Path>>(pathname: P) -> String {
read_to_string(pathname).expect("Unable to open file")
}
/// Reads file and returns it as a vector of characters.
pub fn file_to_chars<P: AsRef<Path>>(pathname: P) -> Vec<char> {
read_to_string(pathname)
.expect("Unable to open file")
.chars()
.collect()
}
/// Reads file and returns a vector of parsed structures. Expects each structure
/// on its own line in the file. And `T` needs to implement `FromStr` trait.
pub fn file_to_structs<P: AsRef<Path>, T: FromStr>(pathname: P) -> Vec<T>
where
<T as FromStr>::Err: Debug,
{
strings_to_structs(
read_to_string(pathname)
.expect("Unable to open files")
.lines(),
)
}
/// Converts iterator over strings to a vector of parsed structures. `T` needs
/// to implement `FromStr` trait and its error must derive `Debug` trait.
pub fn strings_to_structs<T: FromStr, U>(iter: impl Iterator<Item = U>) -> Vec<T>
where
<T as std::str::FromStr>::Err: std::fmt::Debug,
U: Deref<Target = str>,
{
iter.map(|line| {
line.parse()
.expect("Could not parse the struct from the line")
})
.collect()
}
/// Reads file and returns it as a vector of its lines.
pub fn file_to_lines<P: AsRef<Path>>(pathname: P) -> Vec<String> {
read_to_string(pathname)
.expect("Unable to open file")
.lines()
.map(str::to_string)
.collect()
}