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
use crate::storage::{ResourceStorage, Stream};
use memmap::Mmap;
use std::{
cell::RefCell,
collections::BTreeMap,
fs::{self, File},
io,
path::PathBuf,
rc::Rc,
slice,
};
#[derive(Debug, Default)]
struct MemoryMappedFileStorage {
maps: RefCell<BTreeMap<String, Mmap>>,
}
impl MemoryMappedFileStorage {
pub fn read(&self, path: &str) -> Result<&[u8], io::Error> {
if !self.maps.borrow().contains_key(path) {
let file = File::open(path)?;
let file_mmap = unsafe { Mmap::map(&file)? };
self.maps.borrow_mut().insert(path.into(), file_mmap);
}
let data = &self.maps.borrow()[path];
let extended_lifetime_data = unsafe { slice::from_raw_parts(data.as_ptr(), data.len()) };
Ok(&extended_lifetime_data)
}
}
#[derive(Debug)]
pub struct FileResourceStorage {
storage: MemoryMappedFileStorage,
path: PathBuf,
}
impl FileResourceStorage {
pub fn new<P: Into<PathBuf>>(path: P) -> Rc<Self> {
Rc::new(Self {
storage: MemoryMappedFileStorage::default(),
path: path.into(),
})
}
}
impl ResourceStorage for FileResourceStorage {
fn subdir(&self, dir: &str) -> Rc<dyn ResourceStorage> {
Self::new(self.path.join(dir))
}
fn exists(&self, resource_name: &str) -> bool {
self.path.join(resource_name).exists()
}
fn read_resource(&self, resource_name: &str) -> Result<&[u8], io::Error> {
let resource_path = self.path.join(resource_name);
if !resource_path.exists() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
String::from(resource_path.to_str().unwrap_or(resource_name)),
));
}
match resource_path.to_str() {
Some(p) => self.storage.read(p),
None => Err(io::Error::new(
io::ErrorKind::InvalidData,
String::from(resource_path.to_str().unwrap_or(resource_name)),
)),
}
}
fn create_output_stream(
&self,
resource_name: &str,
) -> Result<Rc<RefCell<dyn Stream>>, io::Error> {
if !self.path.exists() {
fs::create_dir_all(self.path.clone())?;
}
let resource_path = self.path.join(resource_name);
let file = File::create(resource_path)?;
Ok(Rc::new(RefCell::new(file)))
}
}