2023-12-02 18:46:37 +01:00
|
|
|
//! # 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")
|
|
|
|
}
|
|
|
|
|
2023-12-04 10:57:50 +01:00
|
|
|
/// Reads file and returns it as a collection of characters.
|
|
|
|
pub fn file_to_chars<B, P: AsRef<Path>>(pathname: P) -> B
|
|
|
|
where
|
|
|
|
B: FromIterator<char>,
|
|
|
|
{
|
2023-12-02 18:46:37 +01:00
|
|
|
read_to_string(pathname)
|
|
|
|
.expect("Unable to open file")
|
|
|
|
.chars()
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
2023-12-04 10:57:50 +01:00
|
|
|
/// Reads file and returns a collection 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<B, P: AsRef<Path>, T: FromStr>(pathname: P) -> B
|
2023-12-02 18:46:37 +01:00
|
|
|
where
|
2023-12-04 10:57:50 +01:00
|
|
|
B: FromIterator<T>,
|
2023-12-02 18:46:37 +01:00
|
|
|
<T as FromStr>::Err: Debug,
|
|
|
|
{
|
|
|
|
strings_to_structs(
|
|
|
|
read_to_string(pathname)
|
|
|
|
.expect("Unable to open files")
|
|
|
|
.lines(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2023-12-04 10:57:50 +01:00
|
|
|
/// Converts iterator over strings to a collection of parsed structures. `T`
|
|
|
|
/// needs to implement `FromStr` trait and its error must derive `Debug` trait.
|
|
|
|
pub fn strings_to_structs<B, T: FromStr, U>(iter: impl Iterator<Item = U>) -> B
|
2023-12-02 18:46:37 +01:00
|
|
|
where
|
2023-12-04 10:57:50 +01:00
|
|
|
B: FromIterator<T>,
|
|
|
|
<T as FromStr>::Err: Debug,
|
2023-12-02 18:46:37 +01:00
|
|
|
U: Deref<Target = str>,
|
|
|
|
{
|
|
|
|
iter.map(|line| {
|
|
|
|
line.parse()
|
|
|
|
.expect("Could not parse the struct from the line")
|
|
|
|
})
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
2023-12-04 10:57:50 +01:00
|
|
|
/// Reads file and returns it as a collection of its lines.
|
|
|
|
pub fn file_to_lines<B, P: AsRef<Path>>(pathname: P) -> B
|
|
|
|
where
|
|
|
|
B: FromIterator<String>,
|
|
|
|
{
|
2023-12-02 18:46:37 +01:00
|
|
|
read_to_string(pathname)
|
|
|
|
.expect("Unable to open file")
|
|
|
|
.lines()
|
|
|
|
.map(str::to_string)
|
|
|
|
.collect()
|
|
|
|
}
|