ds_learn_rust/
lib.rs

1mod front_of_house;
2
3use crate::front_of_house::hosting::add_to_waitlist;
4use std::{error::Error, fs};
5
6pub fn eat_at_restaurant() {
7    // front_of_house::hosting::add_to_waitlist();
8    add_to_waitlist();
9}
10
11pub struct Config {
12    query: String,
13    file_path: String,
14}
15
16impl Config {
17    pub fn build(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
18        args.next();
19        let default_config = Config {
20            query: String::from("de"),
21            file_path: String::from("Cargo.toml"),
22        };
23        let query = match args.next() {
24            Some(arg) => arg,
25            None => return Ok(default_config),
26        };
27        let file_path = match args.next() {
28            Some(arg) => arg,
29            None => return Ok(default_config),
30        };
31        Ok(Config { query, file_path })
32    }
33}
34
35fn search<'a>(query: String, content: &'a String) -> Vec<&'a str> {
36    content
37        .lines()
38        .filter(|line| line.contains(&query))
39        .collect()
40}
41
42pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
43    let content = fs::read_to_string(config.file_path)?;
44    dbg!(&content);
45    for line in search(config.query, &content) {
46        println!("{line}");
47    }
48    Ok(())
49}
50
51#[cfg(test)]
52mod test {
53    use super::*;
54
55    #[test]
56    fn one_result() {
57        let query = "foo".to_string();
58        let content = "\
59limp fimp
60fimp foop
61gloop sloop"
62            .to_string();
63        assert_eq!(vec!["fimp foop"], search(query, &content));
64    }
65}