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
use std::fs::File;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::str;
pub trait LineProcessorT<C> {
fn process(&self, line: &str, context: &C) -> Vec<u8>;
}
pub trait RtoolT<C, P: LineProcessorT<C>> {
fn process_lines<R: Read, W: Write>(
&self,
line_processor: &P,
input: BufReader<R>,
output: &mut BufWriter<W>,
context: &C,
) {
for line in input.lines() {
let out_bytes = line_processor.process(&line.unwrap(), context);
output.write(&out_bytes).unwrap();
}
}
fn process_readable<R: std::io::Read, W: std::io::Write>(
&self,
line_processor: &P,
input: BufReader<R>,
output: &mut BufWriter<W>,
context: &C,
) {
self.process_lines(line_processor, input, output, &context);
}
fn process_files<W: std::io::Write>(
&self,
line_processor: &P,
files: &Vec<&str>,
writable: W,
context: &C,
) {
let mut output = BufWriter::new(writable);
for file in files {
match File::open(file) {
Ok(file) => {
let input = BufReader::new(file);
self.process_readable(line_processor, input, &mut output, context);
}
Err(err) => {
eprintln!("Could not read the file `{}`. The error: {:?}", file, err);
}
}
}
}
fn process(&self, line_processor: &P, files: &Vec<&str>, context: &C) {
if files.is_empty() {
self.process_readable(
line_processor,
BufReader::new(std::io::stdin()),
&mut BufWriter::new(std::io::stdout()),
context,
);
} else {
self.process_files(line_processor, &files, &mut std::io::stdout(), context);
}
}
}