1
0
Fork 0

feat(input): make parsing functions generic

Make parsing functions generic with regards to the containers they
return.

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-12-04 10:57:50 +01:00
parent 19604eafb2
commit b31e46487a
Signed by: mfocko
GPG key ID: 7C47D46246790496
2 changed files with 21 additions and 12 deletions

View file

@ -29,7 +29,7 @@ struct Day03 {
}
impl Solution<Output1, Output2> for Day03 {
fn new<P: AsRef<Path>>(pathname: P) -> Self {
let lines = file_to_lines(pathname);
let lines: Vec<String> = file_to_lines(pathname);
let symbols = lines
.iter()

View file

@ -11,18 +11,23 @@ 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> {
/// 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 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>
/// 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(
@ -32,11 +37,12 @@ where
)
}
/// 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>
/// 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
<T as std::str::FromStr>::Err: std::fmt::Debug,
B: FromIterator<T>,
<T as FromStr>::Err: Debug,
U: Deref<Target = str>,
{
iter.map(|line| {
@ -46,8 +52,11 @@ where
.collect()
}
/// Reads file and returns it as a vector of its lines.
pub fn file_to_lines<P: AsRef<Path>>(pathname: P) -> Vec<String> {
/// 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()