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
use crate::Result;
use std::convert::TryFrom;
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 try_from_os_str(path: &OsStr) -> std::result::Result<Self, std::ffi::OsString> {
TryFrom::try_from(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),
}
}
}
impl TryFrom<&OsStr> for Input {
type Error = std::ffi::OsString;
fn try_from(file_name: &OsStr) -> std::result::Result<Self, std::ffi::OsString> {
Input::new(file_name).map_err(|e| e.to_os_string(file_name))
}
}