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
use crate::Result;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{self, Read, Result as IoResult};
pub enum Input {
Pipe,
File(File),
}
impl Input {
pub fn new(path: &OsStr) -> Result<Self> {
if path == "-" {
Ok(Input::Pipe)
} else {
Ok(Input::File(File::open(path)?))
}
}
pub fn len(&self) -> Option<u64> {
match self {
Input::Pipe => None,
Input::File(file) => file.metadata().ok().map(|x| x.len()),
}
}
pub fn is_empty(&self) -> Option<bool> {
self.len().map(|l| l == 0)
}
}
impl Read for Input {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
match self {
Input::Pipe => io::stdin().read(buf),
Input::File(file) => file.read(buf),
}
}
}