use std::fs;
use std::error::Error;
pub struct Config<'a> {
pattern: &'a String,
filename: &'a String,
}
#[derive(Debug)]
#[derive(PartialEq)]
pub struct Row {
row: String,
row_num: usize
}
impl Row {
pub fn new(row: String, row_num: usize) -> Self {
Row{row, row_num}
}
}
impl ToString for Row {
fn to_string(&self) -> String {
format!("{} : {}", self.row_num, self.row)
}
}
impl<'a> Config<'a> {
pub fn new(pattern: &'a String, filename: &'a String) -> Self {
Config { pattern, filename }
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = dbg!(fs::read_to_string(config.filename)?);
let rows = filter(config.pattern, &contents);
for row in rows.iter() {
println!("{}", row.to_string());
}
Ok(())
}
pub fn filter(pattern: &String, content: &String) -> Vec<Row> {
let res: Vec<Row> = content.split("\r\n").enumerate().filter(|(index, row)| {
row.contains(pattern)
})
.map(|(index, row)| { Row::new(row.to_string(), index) })
.collect();
res
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filter_test() {
let ret = filter(&"human".to_string(), &"I'm a human\r\nI will never die".to_string());
assert_eq!(ret, vec![Row{row_num: 0, row: "I'm a human".to_string()}]);
}
}