]> git.proxmox.com Git - rustc.git/blob - src/doc/book/listings/ch12-an-io-project/listing-12-18/src/lib.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / book / listings / ch12-an-io-project / listing-12-18 / src / lib.rs
1 use std::error::Error;
2 use std::fs;
3
4 pub struct Config {
5 pub query: String,
6 pub file_path: String,
7 }
8
9 impl Config {
10 pub fn build(args: &[String]) -> Result<Config, &'static str> {
11 if args.len() < 3 {
12 return Err("not enough arguments");
13 }
14
15 let query = args[1].clone();
16 let file_path = args[2].clone();
17
18 Ok(Config { query, file_path })
19 }
20 }
21
22 pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
23 let contents = fs::read_to_string(config.file_path)?;
24
25 Ok(())
26 }
27
28 // ANCHOR: here
29 pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
30 for line in contents.lines() {
31 if line.contains(query) {
32 // do something with line
33 }
34 }
35 }
36 // ANCHOR_END: here
37
38 #[cfg(test)]
39 mod tests {
40 use super::*;
41
42 #[test]
43 fn one_result() {
44 let query = "duct";
45 let contents = "\
46 Rust:
47 safe, fast, productive.
48 Pick three.";
49
50 assert_eq!(vec!["safe, fast, productive."], search(query, contents));
51 }
52 }