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
use std::collections::hash_map::{Entry, HashMap};
use std::io;
use std::path::{Path, PathBuf};
use super::Source;
pub struct Mem {
files: HashMap<PathBuf, String>,
}
impl Default for Mem {
fn default() -> Self {
Self {
files: HashMap::new(),
}
}
}
impl Mem {
pub fn new() -> Self {
Self::default()
}
pub fn builder() -> MemBuilder {
MemBuilder {
source: Self::new(),
}
}
pub fn add_file(&mut self, name: &Path, data: String) -> io::Result<()> {
match self.files.entry(name.to_path_buf()) {
Entry::Occupied(_) => Err(io::ErrorKind::AlreadyExists.into()),
Entry::Vacant(v) => {
v.insert(data);
Ok(())
}
}
}
fn read_file(&self, path: &Path) -> Option<String> {
self.files.get(path).cloned()
}
}
pub struct MemBuilder {
source: Mem,
}
impl MemBuilder {
pub fn add_file(mut self, name: &Path, data: String) -> io::Result<Self> {
self.source.add_file(name, data).map(|()| self)
}
pub fn build(self) -> Mem {
self.source
}
}
impl Source for Mem {
fn read(&self, path: &Path, dir: Option<&Path>) -> io::Result<(PathBuf, String)> {
dir.and_then(|dir| {
let path = dir.join(path);
self.read_file(&path).map(|data| (path, data))
})
.or_else(|| {
self.files
.get(path)
.map(|data| (path.to_path_buf(), data.clone()))
})
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("path: {:?}, dir: {:?}", path, dir),
)
})
}
}