use std::error::Error; use std::fs; use std::env; pub struct Config { pub query: String, pub filename: String, pub case_sensitive: bool } impl Config { pub fn new(args: &[String]) -> Result { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let filename = args[2].clone(); let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); Ok(Config { query, filename, case_sensitive }) } } pub fn run(config: Config) -> Result<(), Box> { let contents = fs::read_to_string(config.filename)?; for line in search(&config.query, &contents, config.case_sensitive) { println!("{}", line); } Ok(()) } pub fn search<'a>(query: &str, contents: &'a str, case_sensitive: bool) -> Vec<&'a str> { let all_lines: Vec<&str> = contents.lines().collect(); all_lines.iter() .cloned() // why?? .filter(|&line| { if case_sensitive { line.contains(query) } else { line.to_lowercase().contains(&query.to_lowercase()) } }) .collect::>() } #[cfg(test)] mod tests { use super::*; #[test] fn search_case_sensitive() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!( vec!["safe, fast, productive."], search(query, contents, true) ); } #[test] fn search_case_insensitive() { let query = "Duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!( vec!["safe, fast, productive."], search(query, contents, false) ); } }