minigrep_kingh0730/
lib.rs1use std::error::Error;
2use std::fs;
3
4mod config;
5mod search;
6
7pub use config::Config;
8
9pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
10 let matched_lines = find_matched_lines(config)?;
11
12 matched_lines
13 .into_iter()
14 .for_each(|line| println!("{line}"));
15
16 Ok(())
17}
18
19fn find_matched_lines(config: Config) -> Result<Vec<String>, Box<dyn Error>> {
20 let contents = fs::read_to_string(config.file_path())?;
21
22 let search_fn = match config.ignore_case() {
24 true => search::search_case_insensitive,
25 false => search::search_case_sensitive,
26 };
27
28 let results = search_fn(&config.query(), &contents)
29 .into_iter()
30 .map(|s| s.to_owned())
31 .collect();
32
33 Ok(results)
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39
40 #[test]
41 fn case_sensitive() {
42 let args = vec![
43 String::from("minigrep"),
44 String::from("to"),
45 String::from("poem.txt"),
46 ]
47 .into_iter();
48
49 let config = Config::build(args).unwrap();
50
51 assert_eq!(
52 vec!["Are you nobody, too?", "How dreary to be somebody!"],
53 find_matched_lines(config).unwrap()
54 );
55 }
56
57 #[test]
58 fn case_insensitive() {
59 }
61}