learning rust do not look

stuff

besaid.zone 8161aafb 2f37125e

verified
Changed files
+36 -14
src
+36 -14
src/main.rs
··· 1 - use std::{env, fs}; 1 + use std::{env, fs, process}; 2 2 3 3 struct Config { 4 4 file_path: String, ··· 6 6 } 7 7 8 8 impl Config { 9 - fn new(args: &[String]) -> Config { 9 + fn new(args: &[String]) -> Result<Config, &'static str> { 10 + 11 + if args.len() < 3 || args.len() == 0 { 12 + return Err("invalid arguments") 13 + } 14 + 10 15 let path = args[2].clone(); 11 16 let command = args[1].clone(); 12 17 13 - Config { file_path: path, command } 18 + Ok(Config { file_path: path, command }) 14 19 } 15 20 } 16 21 17 22 fn main() { 18 23 let args: Vec<String> = env::args().collect(); 19 24 20 - let config = Config::new(&args); 25 + let config = Config::new(&args).unwrap_or_else(|_err| { 26 + print_help(); 27 + process::exit(1) 28 + }); 21 29 22 30 23 31 let file_contents = fs::read_to_string(config.file_path).expect("Invalid file path, please make sure the path to the file is correct"); 24 - // println!("file contents length with spaces: {}", file_contents.chars().count()); 25 - dbg!(count_words(file_contents)); 26 32 27 33 match config.command.as_str() { 28 - "-c" | "--bytes"=> println!("bytes"), 29 - _ => println!("Unknown command, see --help") 34 + "-c" | "--bytes" => count_bytes(&file_contents), 35 + "-l" | "--lines" => count_lines(&file_contents), 36 + "-w" | "--words" => count_words(&file_contents), 37 + "-m" | "--chars" => count_chars(&file_contents), 38 + "-h" | "--help" => print_help(), 39 + _ => print_help(), 30 40 } 31 41 } 32 42 33 - fn count_bytes() { 34 - todo!("not impl") 43 + 44 + fn count_bytes(contents: &String) { 45 + println!("{}", contents.bytes().count()) 35 46 } 36 47 37 - fn count_chars() { 38 - todo!("not impl") 48 + fn count_chars(contents: &String) { 49 + println!("{}", contents.chars().count()) 39 50 } 40 51 41 - fn count_lines(contents: String) { 52 + fn count_lines(contents: &String) { 42 53 println!("{}", contents.lines().count()) 43 54 } 44 55 45 - fn count_words(contents: String) { 56 + fn count_words(contents: &String) { 46 57 print!("{}", contents.split_whitespace().count()) 58 + } 59 + 60 + fn print_help() { 61 + println!(" 62 + yap [-COMMAND] [PATH_TO_FILE] 63 + 64 + -c, --bytes - count the amount of bytes in a file 65 + -m, --chars - count the amount of characters in a file 66 + -h, --help - list the available command line arguments 67 + " 68 + ); 47 69 }