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;

/// this is marker trait for any value of HashDatabase
pub trait HashValue: 'static + Debug + Serialize + DeserializeOwned + Clone + Send + Sync {}
/// this is a marker trait for any key value of HashDatabase
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()
    }
}
/// these trait implementations are taken directly from std::collections::HashMap
/// note that currently these implementations will only return data already loaded into memory
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> {
    /// # Arguments
    ///
    /// path: path to the root of the database
    /// key: an option of bytes used to encrypt and decrypt the database
    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)
    }
    /// # Arguments
    ///
    /// path: path to the root of the database
    /// key: an option of bytes used to encrypt and decrypt the database
    /*pub fn from_hashmap<P: AsRef<Path>>(data: HashMap<K, V>, path: P, key: Vec<u8>) -> Self {
        let root = path.as_ref().to_path_buf();
        let (sender, mut receiver): (Sender<(K, V)>, Receiver<(K, V)>) = channel(1);
        let encrypt_key = key.clone();
        let send_root = root.clone();
        tokio::spawn(async move {
            let (key, value) = receiver.recv().await.unwrap();
            let path = send_root.join(key.as_ref());
            let mut file = AsyncFile::create(path).await.unwrap();
            let mut data = serde_json::to_string(&value).unwrap().into_bytes();
            sym_aes_encrypt(&encrypt_key, &mut data);
            file.write_all(&data).await.unwrap();
        });
        Self {
            data,
            root,
            key,
            temp_map: Arc::new(RwLock::new(Vec::new())),
            writer: sender,
        }
    }*/
    /// indexes all files in the root
    /// note that this function is highly inefficient, as such it should only be called when absolutely needed
    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)
    }
    /// indexes all directories in the root
    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)
    }
    /*/// spawns a thread to load a large amount of data into memory
    pub async fn load(&self, entries: Vec<K>) -> JoinHandle<Result<usize, NetworkError>> {
        let root = self.root.clone();
        let temp_map = self.temp_map.clone();
        let key = self.key.clone();
        tokio::spawn(async move {
            let len = entries.len();
            for entry in entries.into_iter() {
                let path = root.join(entry.as_ref());
                let mut file = AsyncFile::open(path).await?;
                let mut buffer = Vec::new();
                file.read_to_end(&mut buffer).await?;
                sym_aes_decrypt(&key, &mut buffer);
                let value = serde_json::from_str(&String::from_utf8(buffer)?)?;
                temp_map.write().await.push((entry, value));
            }
            Ok(len)
        })
    }
    /// after loading data into memory it needs to be inserted into the HashMap
    pub async fn memory_sync(&mut self) {
        for (k, v) in self.temp_map.read().await.iter() {
            println!("inserting: {:?}", v);
            self.data.insert(k.clone(), v.clone());
        }
        self.temp_map.write().await.clear();
    }*/
}