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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
extern crate bincode;
extern crate serde;

use std::borrow::Borrow;
use std::cmp::Eq;
use std::collections::HashMap as StdHashMap;
use std::error::Error;
use std::fs::OpenOptions;
use std::hash::Hash;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::result::Result;

use bincode::{deserialize, serialize, Infinite};
use serde::de::DeserializeOwned;
use serde::ser::Serialize;

pub struct Store<K, V>
where
    K: Serialize + DeserializeOwned + Eq + Hash,
    V: Serialize + DeserializeOwned + Eq + Hash,
{
    file_path: PathBuf,
    data: StdHashMap<K, V>,
    _modified: bool,
}

impl<K, V> Store<K, V>
where
    K: Serialize + DeserializeOwned + Eq + Hash,
    V: Serialize + DeserializeOwned + Eq + Hash,
{
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, String> {
        let path = path.as_ref();

        let _new = !path.exists();

        let data = if !_new {
            let mut file = OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .append(true)
                .open(path)
                .map_err(|e| e.description().to_string())?;

            let mut buf = Vec::new();

            let read = file
                .read_to_end(&mut buf)
                .map_err(|e| e.description().to_string())?;

            let mut _data: StdHashMap<K, V> = StdHashMap::new();

            if read > 0 {
                _data = deserialize(&buf).map_err(|e| e.description().to_string())?;
            }
            _data
        } else {
            StdHashMap::new()
        };

        Ok(Store {
            file_path: path.to_path_buf(),
            data,
            _modified: false,
        })
    }

    pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
    where
        Q: ?Sized + std::hash::Hash + Eq,
        K: Borrow<Q>,
    {
        self.data.get(key.borrow())
    }

    pub fn exists<Q>(&mut self, key: &Q) -> bool
    where
        Q: ?Sized + std::hash::Hash + Eq,
        K: Borrow<Q>,
    {
        self.data.get(key.borrow()).is_some()
    }

    pub fn insert<X, Y>(&mut self, key: X, v: Y)
    where
        X: Into<K>,
        Y: Into<V>,
        K: Clone,
        Y: Clone,
    {
        self.data.insert(key.into(), v.into());
        self._modified = true;
    }

    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
    where
        Q: ?Sized + std::hash::Hash + Eq,
        K: Borrow<Q>,
    {
        let rv = self.data.remove(key);
        self._modified = true;
        rv
    }

    pub fn flush(&mut self) -> Result<(), String> {
        if self._modified {
            let mut file = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&self.file_path)
                .map_err(|e| e.description().to_string())?;

            let encoded = serialize(&self.data, Infinite).unwrap();

            let rv = file
                .write_all(&*encoded)
                .map_err(|e| e.description().to_string());

            self._modified = false;

            rv
        } else {
            Ok(())
        }
    }

    pub fn get_path<'a>(&'a self) -> &Path {
        self.file_path.as_path()
    }

    pub fn clear(&mut self) {
        self.data.clear();
    }
}

impl<K, V> Drop for Store<K, V>
where
    K: Serialize + DeserializeOwned + Eq + Hash,
    V: Serialize + DeserializeOwned + Eq + Hash,
{
    fn drop(&mut self) {
        match self.flush() {
            Err(e) => {
                eprintln!("Cannot flush {}: {:?}", self.file_path.display(), e);
                panic!(format!(
                    "Cannot flush {}: {:?}",
                    self.file_path.display(),
                    e
                ));
            }
            _ => (),
        }
    }
}

#[cfg(test)]
mod test {

    extern crate rand;

    use super::*;
    use std::env;
    use std::fs::remove_file;
    use test::rand::Rng;

    fn _gen_filename() -> String {
        let mut dir = env::temp_dir();
        let file_name: String = rand::thread_rng().gen_ascii_chars().take(12).collect();
        dir.push(file_name);
        dir.set_extension("kafidb");
        println!("{:?}", dir.as_path().display());
        dir.into_os_string().into_string().unwrap()
    }

    fn _gen_col() -> Store<String, String> {
        let mut col = Store::open(&_gen_filename()).unwrap();
        col.insert("satu", "111".to_string());
        let _ = col.flush();
        col
    }

    #[test]
    fn test_exists() {
        let mut col = _gen_col();
        assert_eq!(col.exists("satu"), true);
        assert_eq!(col.exists("dua"), false);
        remove_file(col.get_path()).unwrap();
    }

    #[test]
    fn test_get() {
        let mut col = _gen_col();
        assert_eq!(col.get("satu"), Some(&"111".to_string()));
        assert_eq!(col.get("lima"), None);
        remove_file(col.get_path()).unwrap();
    }

    #[test]
    fn test_remove() {
        let mut col = _gen_col();
        assert_eq!(col.remove("satu"), Some("111".to_string()));
        assert_eq!(col.exists("satu"), false);
        remove_file(col.get_path()).unwrap();
    }

    #[test]
    fn test_clear() {
        let mut col = _gen_col();
        col.clear();
        assert_eq!(col.exists("satu"), false);
        remove_file(col.get_path()).unwrap();
    }

    #[test]
    fn test_already_filled() {
        let path = _gen_filename();
        {
            use std::fs;
            let _ = fs::remove_file(&path);
        }
        {
            let mut col: Store<String, String> = Store::open(&path).unwrap();
            col.insert("satu".to_string(), "111".to_string());
            col.flush().unwrap();
        }
        {
            let mut col: Store<String, String> = Store::open(&path).unwrap();
            assert_eq!(col.exists("satu"), true);
            assert_eq!(col.get("satu"), Some(&"111".to_string()));
            assert_eq!(col.get("lima"), None);
            col.insert("lima".to_string(), "555".to_string());
            assert_eq!(col.get("lima"), Some(&"555".to_string()));
            col.flush().unwrap();
        }
        remove_file(path).unwrap();
    }

    #[test]
    fn test_auto_flush() {
        let path = _gen_filename();
        {
            use std::fs;
            let _ = fs::remove_file(&path);
        }
        {
            let mut col: Store<String, String> = Store::open(&path).unwrap();
            col.insert("satu".to_string(), "111".to_string());
            assert_eq!(std::path::Path::new(&path).exists(), false);
        }
        assert_eq!(std::path::Path::new(&path).exists(), true);
        remove_file(path).unwrap();
    }

    #[test]
    fn test_another_inserts() {
        let mut col = _gen_col();
        col.insert("two", "2");
        let three = "three".to_string();
        col.insert(three, "3");
        assert_eq!(col.get("two"), Some(&"2".to_owned()));
        assert_eq!(col.get("three"), Some(&"3".to_owned()));
    }
}