1
0
Fork 0
2023/src/input.rs
Matej Focko 153f02a831
feat(input): implement parsing from ws-separated string
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-04 11:00:45 +01:00

77 lines
2 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 collection of characters.
pub fn file_to_chars<B, P: AsRef<Path>>(pathname: P) -> B
where
B: FromIterator<char>,
{
read_to_string(pathname)
.expect("Unable to open file")
.chars()
.collect()
}
/// 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
where
B: FromIterator<T>,
<T as FromStr>::Err: Debug,
{
strings_to_structs(
read_to_string(pathname)
.expect("Unable to open files")
.lines(),
)
}
/// 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
where
B: FromIterator<T>,
<T as FromStr>::Err: 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 collection of its lines.
pub fn file_to_lines<B, P: AsRef<Path>>(pathname: P) -> B
where
B: FromIterator<String>,
{
read_to_string(pathname)
.expect("Unable to open file")
.lines()
.map(str::to_string)
.collect()
}
/// Parses a string of whitespace separated elements and returns them as
/// a collection.
pub fn parse_ws_separated<B, T: FromStr>(s: &str) -> B
where
B: FromIterator<T>,
<T as FromStr>::Err: Debug,
{
s.split_ascii_whitespace()
.map(|n| n.parse().unwrap())
.collect()
}