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
91
92
93
94
95
96
97
98
99
100
101
use clap::Parser;
use rustutils_runnable::Runnable;
use std::error::Error;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

pub const BUFFER_SIZE: usize = 4 * 1024;

/// Concatenate files to standard output.
#[derive(Parser, Clone, Debug)]
#[clap(author, version, about, long_about = None)]
pub struct Cat {
    /// List of files to concatenate.
    files: Vec<PathBuf>,
}

impl Cat {
    pub fn iter(&self) -> CatIterator {
        CatIterator::new(self.files.iter().map(|p| p.as_path()))
    }
}

#[derive(thiserror::Error, Debug)]
pub enum CatIteratorError {
    #[error("Opening file {0:?}: {1:}")]
    OpeningFile(PathBuf, std::io::Error),
    #[error("Reading from file {0:?}: {1:}")]
    ReadingFile(PathBuf, std::io::Error),
}

pub struct CatIterator<'f> {
    /// Current file to read from.
    current: Option<(&'f Path, Box<dyn Read>)>,
    /// List of files to read still.
    files: Box<dyn Iterator<Item = &'f Path> + 'f>,
}

impl<'f> CatIterator<'f> {
    pub fn new(files: impl Iterator<Item = &'f Path> + 'f) -> Self {
        CatIterator {
            current: None,
            files: Box::new(files),
        }
    }
}

impl<'f> Iterator for CatIterator<'f> {
    type Item = Result<Vec<u8>, CatIteratorError>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.current.is_none() {
            if let Some(next) = self.files.next() {
                let reader: Box<dyn Read> = if next.as_os_str() == "-" {
                    Box::new(std::io::stdin())
                } else {
                    match File::open(next) {
                        Err(error) => {
                            return Some(Err(CatIteratorError::OpeningFile(
                                next.to_path_buf(),
                                error,
                            )))
                        }
                        Ok(file) => Box::new(file),
                    }
                };
                self.current = Some((next, reader));
            } else {
                return None;
            }
        }
        let (next, reader) = match &mut self.current {
            Some((next, reader)) => (next, reader),
            None => unreachable!(),
        };
        let mut buffer = vec![0; BUFFER_SIZE];
        let length = match reader.read(&mut buffer[..]) {
            Err(error) => {
                return Some(Err(CatIteratorError::ReadingFile(
                    next.to_path_buf(),
                    error,
                )))
            }
            Ok(length) => length,
        };
        buffer.truncate(length);
        if length == 0 {
            self.current = None;
        }
        Some(Ok(buffer))
    }
}

impl Runnable for Cat {
    fn run(&self) -> Result<(), Box<dyn Error>> {
        let mut stdout = std::io::stdout();
        for data in self.iter() {
            stdout.write_all(&data?)?;
        }
        Ok(())
    }
}