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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use errors::Result;
use std::fmt;
use std::fs::File;
use std::io::{self, Cursor, Read};
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub enum Readable {
Empty,
Bytes(Arc<Vec<u8>>),
Path(Arc<PathBuf>),
Stdin,
}
impl Readable {
fn read(&self) -> Result<Box<Read>> {
use self::Readable::*;
let out: Box<Read> = match *self {
Empty => Box::new(Cursor::new(&[])),
Bytes(ref bytes) => Box::new(Cursor::new(ArcCursor(Arc::clone(&bytes)))),
Path(ref path) => Box::new(File::open(path.as_ref())?),
Stdin => Box::new(io::stdin()),
};
Ok(out)
}
}
impl fmt::Display for Readable {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use self::Readable::*;
match *self {
Empty => "empty".fmt(fmt),
Bytes(ref bytes) => write!(fmt, "bytes:{}", bytes.len()),
Path(ref path) => write!(fmt, "path:{}", path.display()),
Stdin => "stdin".fmt(fmt),
}
}
}
#[derive(Debug, Clone)]
pub struct Source {
name: Option<Arc<String>>,
path: Option<Arc<PathBuf>>,
readable: Readable,
}
impl Source {
pub fn empty<S: AsRef<str>>(name: S) -> Self {
Self {
name: Some(Arc::new(name.as_ref().to_string())),
path: None,
readable: Readable::Empty,
}
}
pub fn bytes<S: AsRef<str>>(name: S, bytes: Vec<u8>) -> Self {
Self {
name: Some(Arc::new(name.as_ref().to_string())),
path: None,
readable: Readable::Bytes(Arc::new(bytes)),
}
}
pub fn from_path<P: AsRef<Path>>(path: P) -> Self {
Self {
name: None,
path: None,
readable: Readable::Path(Arc::new(path.as_ref().to_owned())),
}
}
pub fn stdin() -> Self {
Self {
name: None,
path: None,
readable: Readable::Stdin,
}
}
pub fn path(&self) -> Option<&Path> {
if let Some(path) = self.path.as_ref() {
return Some(path.as_ref());
}
if let Readable::Path(ref path) = self.readable {
return Some(path.as_ref());
}
None
}
pub fn read(&self) -> Result<Box<Read>> {
self.readable.read()
}
pub fn with_name(&self, name: String) -> Self {
Self {
name: Some(Arc::new(name)),
path: self.path.as_ref().map(Arc::clone),
readable: self.readable.clone(),
}
}
}
impl fmt::Display for Source {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if let Readable::Path(ref path) = self.readable {
return path.display().fmt(fmt);
}
match self.name {
Some(ref name) => write!(fmt, "<{} {}>", name, self.readable),
None => write!(fmt, "<{}>", self.readable),
}
}
}
struct ArcCursor(Arc<Vec<u8>>);
impl AsRef<[u8]> for ArcCursor {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}