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
use storage::{MemoryDescriptor, ResourceStorage, Stream};
use memmap::Mmap;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io;
use std::path;
use std::rc::Rc;
#[derive(Debug, Default)]
struct MemoryMappedFileStorage {
maps: BTreeMap<String, Mmap>,
}
impl MemoryMappedFileStorage {
pub fn read(&mut self, path: &str) -> Result<MemoryDescriptor, io::Error> {
if let Some(mapping) = self.maps.get(path) {
return Ok(MemoryDescriptor::new(mapping.as_ptr(), mapping.len()));
}
let file = File::open(path)?;
let file_mmap = unsafe { Mmap::map(&file)? };
let mem_descr = MemoryDescriptor::new(file_mmap.as_ptr(), file_mmap.len());
self.maps.insert(path.into(), file_mmap);
Ok(mem_descr)
}
}
impl Stream for File {}
#[derive(Debug)]
pub struct FileResourceStorage {
storage: MemoryMappedFileStorage,
path: path::PathBuf,
}
impl FileResourceStorage {
pub fn new(path: path::PathBuf) -> Self {
Self {
storage: MemoryMappedFileStorage::default(),
path,
}
}
}
impl ResourceStorage for FileResourceStorage {
fn subdir(&self, dir: &str) -> Rc<RefCell<ResourceStorage>> {
Rc::new(RefCell::new(Self::new(self.path.join(dir))))
}
fn exists(&self, resource_name: &str) -> bool {
self.path.join(resource_name).exists()
}
fn read_resource(&mut self, resource_name: &str) -> Result<MemoryDescriptor, 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(
&mut self,
resource_name: &str,
) -> Result<Rc<RefCell<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)))
}
}