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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
use std::{cmp, env, fs};
use std::io::{self, Read, Write};
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use maidsafe_utilities::serialisation::{self, SerialisationError};
use rustc_serialize::{Decodable, Encodable};
use rustc_serialize::hex::{FromHex, ToHex};
use tempdir::TempDir;
quick_error! {
#[derive(Debug)]
pub enum Error {
Io(error: io::Error) {
description("IO error")
display("IO error: {}", error)
cause(error)
from()
}
Serialisation(error: SerialisationError) {
description("Serialisation error")
display("Serialisation error: {}", error)
cause(error)
from()
}
NotEnoughSpace {
description("Not enough space")
display("Not enough space")
from()
}
NotFound {
description("Key, Value not found")
display("Key, Value not found")
from()
}
}
}
pub struct ChunkStore<Key, Value> {
tempdir: TempDir,
max_space: u64,
used_space: u64,
phantom: PhantomData<(Key, Value)>,
}
impl<Key, Value> ChunkStore<Key, Value>
where Key: Decodable + Encodable,
Value: Decodable + Encodable
{
pub fn new_in<P: AsRef<Path>>(root: P,
prefix: &str,
max_space: u64)
-> Result<ChunkStore<Key, Value>, Error> {
fs::create_dir_all(root.as_ref())
.and_then(|()| TempDir::new_in(root.as_ref(), prefix))
.map(|tempdir| {
ChunkStore {
tempdir: tempdir,
max_space: max_space,
used_space: 0,
phantom: PhantomData,
}
})
.map_err(From::from)
}
pub fn new(prefix: &str, max_space: u64) -> Result<ChunkStore<Key, Value>, Error> {
Self::new_in(&env::temp_dir(), prefix, max_space)
}
pub fn put(&mut self, key: &Key, value: &Value) -> Result<(), Error> {
let serialised_value = try!(serialisation::serialise(value));
if self.used_space + serialised_value.len() as u64 > self.max_space {
return Err(Error::NotEnoughSpace);
}
let file_path = try!(self.file_path(key));
let _ = self.do_delete(&file_path);
fs::File::create(&file_path)
.and_then(|mut file| {
file.write_all(&serialised_value)
.and_then(|()| file.sync_all())
.and_then(|()| file.metadata())
.map(|metadata| {
self.used_space += metadata.len();
})
})
.map_err(From::from)
}
pub fn delete(&mut self, key: &Key) -> Result<(), Error> {
let file_path = try!(self.file_path(key));
self.do_delete(&file_path)
}
pub fn get(&self, key: &Key) -> Result<Value, Error> {
match fs::File::open(try!(self.file_path(key))) {
Ok(mut file) => {
let mut contents = Vec::<u8>::new();
let _ = try!(file.read_to_end(&mut contents));
Ok(try!(serialisation::deserialise::<Value>(&contents)))
}
Err(_) => Err(Error::NotFound),
}
}
pub fn has(&self, key: &Key) -> bool {
let file_path = if let Ok(path) = self.file_path(key) {
path
} else {
return false;
};
if let Ok(metadata) = fs::metadata(file_path) {
return metadata.is_file();
} else {
false
}
}
pub fn keys(&self) -> Vec<Key> {
fs::read_dir(&self.tempdir.path())
.and_then(|dir_entries| {
let dir_entry_to_routing_name = |dir_entry: io::Result<fs::DirEntry>| {
dir_entry.ok()
.and_then(|entry| entry.file_name().into_string().ok())
.and_then(|hex_name| hex_name.from_hex().ok())
.and_then(|bytes| serialisation::deserialise::<Key>(&*bytes).ok())
};
Ok(dir_entries.filter_map(dir_entry_to_routing_name).collect())
})
.unwrap_or_else(|_| Vec::new())
}
pub fn max_space(&self) -> u64 {
self.max_space
}
pub fn used_space(&self) -> u64 {
self.used_space
}
fn do_delete(&mut self, file_path: &Path) -> Result<(), Error> {
if let Ok(metadata) = fs::metadata(file_path) {
self.used_space -= cmp::min(metadata.len(), self.used_space);
fs::remove_file(file_path).map_err(From::from)
} else {
Ok(())
}
}
fn file_path(&self, key: &Key) -> Result<PathBuf, Error> {
let filename = try!(serialisation::serialise(key)).to_hex();
let path_name = Path::new(&filename);
Ok(self.tempdir.path().join(path_name))
}
}