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
use clap::Parser;
use rustutils_runnable::Runnable;
use std::collections::BTreeMap;
use std::error::Error;
use std::fs::File;
use std::io::{self, stdin, BufReader, Read};
use std::path::PathBuf;

/// Print newline, word, and byte counts for each file.
#[derive(Parser, Clone, Debug)]
#[clap(author, version, about, long_about = None)]
pub struct Wc {
    /// Print the byte counts
    #[clap(long, short)]
    pub bytes: bool,
    /// Print the character counts (input is interpreted as UTF-8).
    #[clap(long, short)]
    pub chars: bool,
    /// Print the line count.
    #[clap(long, short)]
    pub lines: bool,
    /// Print the word count.
    #[clap(long, short)]
    pub words: bool,
    /// Output result as JSON.
    #[clap(long, short)]
    pub json: bool,
    /// Files to read, if not specified, standard input is read.
    pub files: Vec<PathBuf>,
}

impl Wc {
    pub fn count_file(&self, file: &mut dyn Read) -> Result<WordCount, io::Error> {
        let mut count = WordCount::default();
        for byte in file.bytes() {
            let byte = byte?;
            count.bytes += 1;
            if byte == b' ' {
                count.lines += 1;
            }
        }
        Ok(count)
    }

    pub fn count_all(&self) -> Result<BTreeMap<PathBuf, WordCount>, Box<dyn Error>> {
        let mut result = BTreeMap::new();
        if self.files.len() == 0 {
            let mut stdin = stdin();
            result.insert(PathBuf::new(), self.count_file(&mut stdin)?);
        } else {
            for path in &self.files {
                let file = File::open(path)?;
                let mut reader = BufReader::new(file);
                result.insert(path.clone(), self.count_file(&mut reader)?);
            }
        }

        Ok(result)
    }

    pub fn run(&self) -> Result<(), Box<dyn Error>> {
        let results = self.count_all()?;
        for (file, counts) in results.iter() {
            println!(
                " {}  {}  {} {}",
                counts.lines,
                counts.words,
                counts.bytes,
                file.display()
            );
        }
        Ok(())
    }
}

impl Runnable for Wc {
    fn run(&self) -> Result<(), Box<dyn Error>> {
        self.run()
    }
}

#[derive(Clone, Debug, Default)]
pub struct WordCount {
    bytes: u64,
    chars: u64,
    lines: u64,
    words: u64,
}