@@ -9,13 +9,20 @@ pub struct Config {
9
9
}
10
10
11
11
impl Config {
12
- pub fn build ( args : & [ String ] ) -> Result < Config , & ' static str > {
13
- if args . len ( ) < 3 {
14
- return Err ( "Not enough arguments. " ) ;
15
- }
12
+ pub fn build ( mut args : impl Iterator < Item = String > ) -> Result < Config , & ' static str > {
13
+ // The first value in the arguments is the name of the program
14
+ // We dont use this so we get rid of it
15
+ args . next ( ) ;
16
16
17
- let query = args[ 1 ] . clone ( ) ;
18
- let file_path = args[ 2 ] . clone ( ) ;
17
+ let query = match args. next ( ) {
18
+ Some ( arg) => arg,
19
+ None => return Err ( "Didn't get a query string" ) ,
20
+ } ;
21
+
22
+ let file_path = match args. next ( ) {
23
+ Some ( file_path) => file_path,
24
+ None => return Err ( "Didn't get a file path" ) ,
25
+ } ;
19
26
20
27
let ignore_case = env:: var ( "IGNORE_CASE" ) . is_ok ( ) ;
21
28
@@ -44,28 +51,17 @@ pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
44
51
}
45
52
46
53
pub fn search < ' a > ( query : & str , contents : & ' a str ) -> Vec < & ' a str > {
47
- let mut results = Vec :: new ( ) ;
48
-
49
- for line in contents. lines ( ) {
50
- if line. contains ( query) {
51
- results. push ( line) ;
52
- }
53
- }
54
-
55
- return results;
54
+ contents
55
+ . lines ( )
56
+ . filter ( |line| line. contains ( query) )
57
+ . collect ( )
56
58
}
57
59
58
60
pub fn search_case_insensitive < ' a > ( query : & str , contents : & ' a str ) -> Vec < & ' a str > {
59
- let query = query. to_lowercase ( ) ;
60
- let mut results = Vec :: new ( ) ;
61
-
62
- for line in contents. lines ( ) {
63
- if line. to_lowercase ( ) . contains ( & query) {
64
- results. push ( line) ;
65
- }
66
- }
67
-
68
- return results;
61
+ contents
62
+ . lines ( )
63
+ . filter ( |line| line. to_lowercase ( ) . contains ( query. to_lowercase ( ) . as_str ( ) ) )
64
+ . collect ( )
69
65
}
70
66
71
67
#[ cfg( test) ]
@@ -75,23 +71,17 @@ mod tests {
75
71
#[ test]
76
72
fn case_sensitive ( ) {
77
73
let query = "duct" ;
78
- let contents = "\
79
- Rust:
80
- safe, fast, productive.
81
- Pick three.
82
- Duct tape." ;
74
+
75
+ let contents = "Rust:\n safe, fast, productive.\n Pick three.\n Duct tape." ;
83
76
84
77
assert_eq ! ( vec![ "safe, fast, productive." ] , search( query, contents) ) ;
85
78
}
86
79
87
80
#[ test]
88
81
fn case_insensitive ( ) {
89
82
let query = "rUsT" ;
90
- let contents = "\
91
- Rust:
92
- safe, fast, productive.
93
- Pick three.
94
- Trust me." ;
83
+
84
+ let contents = "Rust:\n safe, fast, productive.\n Pick three.\n Trust me." ;
95
85
96
86
assert_eq ! (
97
87
vec![ "Rust:" , "Trust me." ] ,
0 commit comments