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
use crate::asyncronous::encryption::{sym_aes_decrypt, sym_aes_encrypt};
use crate::error::NetworkError;
use serde::{de::DeserializeOwned, Serialize};
use std::collections::hash_map::{IntoIter, Iter, IterMut};
use std::collections::HashMap;
use std::fmt;
use std::iter::IntoIterator;
use std::path::Path;
use std::path::PathBuf;
use std::fs::File;
use std::io::{Read, Write};
use std::{fmt::Debug, hash::Hash};
use walkdir::WalkDir;
pub trait HashValue: 'static + Debug + Serialize + DeserializeOwned + Clone + Send + Sync {}
pub trait HashKey: 'static + Hash + AsRef<Path> + PartialEq + Eq + Clone + Send + Sync {}
impl<V> HashValue for V where V: 'static + Debug + Serialize + DeserializeOwned + Send + Clone + Sync
{}
impl<K> HashKey for K where K: 'static + AsRef<Path> + Hash + PartialEq + Eq + Clone + Send + Sync {}
impl<V: HashValue, K: HashKey> Debug for HashDatabase<V, K>
where
K: Debug,
V: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Point")
.field("data", &self.data)
.field("key", &self.key)
.field("root", &self.root)
.finish()
}
}
impl<'a, V: HashValue, K: HashKey> IntoIterator for &'a HashDatabase<V, K> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
#[inline]
fn into_iter(self) -> Iter<'a, K, V> {
self.data.iter()
}
}
impl<V: HashValue, K: HashKey> IntoIterator for HashDatabase<V, K> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> IntoIter<K, V> {
self.data.into_iter()
}
}
impl<'a, V: HashValue, K: HashKey> IntoIterator for &'a mut HashDatabase<V, K> {
type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>;
#[inline]
fn into_iter(self) -> IterMut<'a, K, V> {
self.data.iter_mut()
}
}
#[derive(Clone)]
pub struct HashDatabase<V: HashValue, K: HashKey = String> {
data: HashMap<K, V>,
key: Vec<u8>,
root: PathBuf,
}
impl<V: HashValue, K: HashKey> HashDatabase<V, K> {
pub fn new<P: AsRef<Path>>(path: P, key: Vec<u8>) -> Result<Self, NetworkError> {
let root = path.as_ref().to_path_buf();
if !root.exists() {
std::fs::create_dir(root.clone())?;
}
Ok(Self {
data: HashMap::new(),
key,
root,
})
}
pub fn insert(&mut self, key: K, item: V) -> Result<(), NetworkError> {
self.data.insert(key.clone(), item.clone());
let path = self.root.join(key.as_ref());
let mut file = File::create(path)?;
let mut data = serde_json::to_string(&item)?.into_bytes();
sym_aes_encrypt(&self.key, &mut data);
Ok(file.write_all(&data)?)
}
pub fn get(&self, key: &K) -> Option<&V> {
self.data.get(key)
}
pub fn load(&mut self, key: &K) -> Result<(), NetworkError> {
let path = self.root.join(key);
if !path.exists() {
return Err(NetworkError::IOError(std::io::Error::new(std::io::ErrorKind::NotFound, "entry not found")));
}
let mut file = File::open(path)?;
let mut invec = Vec::new();
file.read_to_end(&mut invec)?;
sym_aes_decrypt(&self.key, &mut invec);
let entry = serde_json::from_str(&String::from_utf8(invec)?)?;
self.data.insert(key.clone(), entry);
Ok(())
}
pub fn decompose(self) -> (HashMap<K, V>, PathBuf) {
(self.data, self.root)
}
pub fn index_entries(&self) -> Result<Vec<PathBuf>, NetworkError> {
let results: Vec<Result<PathBuf, NetworkError>> = WalkDir::new(self.root.clone())
.into_iter()
.map(|p| Ok(p?.path().to_path_buf()))
.collect();
let mut paths = Vec::with_capacity(results.len());
for result in results.into_iter() {
let path = result?;
if path.is_file() {
paths.push(path);
}
}
Ok(paths)
}
pub fn index_subdatabases(&self) -> Result<Vec<PathBuf>, NetworkError> {
let results: Vec<Result<PathBuf, NetworkError>> = WalkDir::new(self.root.clone())
.into_iter()
.map(|p| Ok(p?.path().to_path_buf()))
.collect();
let mut paths = Vec::with_capacity(results.len());
for result in results.into_iter() {
let path = result?;
if path.is_dir() {
paths.push(path);
}
}
Ok(paths)
}
}