1- use std:: { env, error:: Error , fs, vec } ;
1+ use std:: { env, error:: Error , fs } ;
22
33pub fn run ( config : Config ) -> Result < ( ) , Box < dyn Error > > {
44 let contents = fs:: read_to_string ( & config. filepath ) ?;
@@ -22,20 +22,24 @@ pub struct Config {
2222}
2323
2424impl Config {
25- pub fn build ( mut args : Vec < String > ) -> Result < Config , & ' static str > {
26- if args. len ( ) < 3 {
27- return Err ( "Not Enough Arguments" ) ;
28- }
29- let query = args. remove ( 1 ) ;
30- let filepath = args. remove ( 1 ) ;
31-
32- let mut ignore_case = env:: var ( "IGNORE_CASE" ) . is_ok ( ) ;
33-
34- for arg in args. iter ( ) {
35- if arg == "-i" {
36- ignore_case = true ;
25+ pub fn build ( mut args : impl Iterator < Item = String > ) -> Result < Config , & ' static str > {
26+ args. next ( ) ;
27+
28+ let query = match args. next ( ) {
29+ Some ( q) => q,
30+ None => {
31+ return Err ( "Didn't get the query string" ) ;
32+ }
33+ } ;
34+
35+ let filepath = match args. next ( ) {
36+ Some ( q) => q,
37+ None => {
38+ return Err ( "Didn't get the filepath" ) ;
3739 }
38- }
40+ } ;
41+
42+ let ignore_case = env:: var ( "IGNORE_CASE" ) . is_ok ( ) ;
3943
4044 Ok ( Config {
4145 query,
@@ -46,28 +50,19 @@ impl Config {
4650}
4751
4852fn search < ' a > ( query : & str , contents : & ' a str ) -> Vec < & ' a str > {
49- let mut results = vec ! [ ] ;
50-
51- contents. lines ( ) . for_each ( |line| {
52- if line. contains ( query) {
53- results. push ( line) ;
54- }
55- } ) ;
56-
57- results
53+ contents
54+ . lines ( )
55+ . filter ( |line| line. contains ( query) )
56+ . collect ( )
5857}
5958
6059fn search_case_insensitive < ' a > ( query : & str , contents : & ' a str ) -> Vec < & ' a str > {
61- let mut results = vec ! [ ] ;
6260 let query = query. to_lowercase ( ) ;
6361
64- contents. lines ( ) . for_each ( |line| {
65- if line. to_lowercase ( ) . contains ( & query) {
66- results. push ( line) ;
67- }
68- } ) ;
69-
70- results
62+ contents
63+ . lines ( )
64+ . filter ( |line| line. to_lowercase ( ) . contains ( & query) )
65+ . collect ( )
7166}
7267
7368#[ cfg( test) ]
0 commit comments