1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
extern crate clap; use std::fs; use std::error::Error; use clap::ArgMatches; pub fn wc_line(s: &String) -> usize { let split = s.lines(); let len = split.count(); println!("Count by lines: {}", len); len } pub fn wc_word(s: &String) -> usize { let split = s.split_whitespace(); let len = split.count(); println!("Count by words: {}", len); len } pub fn wc_char(s: &String) -> usize { let len = s.chars().count(); println!("Count by chars: {}", len); len } pub fn wc_byte(s: &String) -> usize { let len = s.len(); println!("Count by bytes: {}", len); len } pub fn run(matches: ArgMatches) -> Result<(), Box<dyn Error>> { let file = matches.value_of("input").unwrap(); println!("Input is: {}", file); let contents = fs::read_to_string(file)?; println!("file contains: {}", contents); if matches.is_present("chars") { println!("by char"); wc_char(&contents); } else if matches.is_present("lines") { println!("by line"); wc_line(&contents); } else if matches.is_present("bytes") { println!("by bytes"); wc_byte(&contents); } else { println!("by word"); wc_word(&contents); } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_wc_word() { let hi = String::from("hi there"); assert_eq!(wc_word(&hi), 2); } #[test] fn test_wc_char() { let hi = String::from("hi"); assert_eq!(wc_char(&hi), 2); } #[test] fn test_wc_byte() { let hi = String::from("hi"); assert_eq!(wc_byte(&hi), 2); } #[test] fn test_wc_line() { let hi = String::from("hi"); assert_eq!(wc_line(&hi), 1); } }