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

use std::{fs, io};
use std::path::{Path, PathBuf};
use std::marker::PhantomData;
use std::fmt::Debug;

extern crate serde;
use serde::{de::DeserializeOwned, Serialize};

extern crate serde_json;

/// A simple file system based key:value data store
pub struct FileStore<V> {
    dir: PathBuf,
    _v: PhantomData<V>,
}

#[derive(Debug)]
pub enum Error<E> {
    Io(io::Error),
    Inner(E),
}

impl <E> From<io::Error> for Error<E> {
    fn from(e: io::Error) -> Self {
        Error::Io(e)
    }
}


impl <V, E>FileStore<V> 
where
    V: EncodeDecode<Value=V, Error=E> + Serialize + DeserializeOwned + Debug,
    E: Debug
{
    /// Create a new FileStore
    pub fn new<P: AsRef<Path>>(dir: P) -> Result<Self, Error<E>> {
        Ok(FileStore{
            dir: dir.as_ref().into(), 
            _v: PhantomData
        })
    }

    /// List all files in the database
    pub fn list(&mut self) -> Result<Vec<String>, Error<E>> {
        let mut names = vec![];

        for entry in fs::read_dir(&self.dir)? {
            let entry = entry?;
            let name = entry.file_name().into_string().unwrap();
            names.push(name);
        }

        Ok(names)
    }

    /// Load a file by name
    pub fn load<P: AsRef<Path>>(&mut self, name: P) -> Result<V, Error<E>> {
        let mut path = self.dir.clone();
        path.push(name);

        let buff = fs::read(path)?;
        let obj: V = V::decode(&buff).map_err(|e| Error::Inner(e) )?;

        Ok(obj)
    }

    /// Store a file by name
    pub fn store<P: AsRef<Path>>(&mut self, name: P, v: &V) -> Result<(), Error<E>> {
        let mut path = self.dir.clone();
        path.push(name);
        
        let bin: Vec<u8> = V::encode(v).map_err(|e| Error::Inner(e) )?;
        fs::write(path, bin)?;
        Ok(())
    }

    /// Load all files from the database
    pub fn load_all(&mut self) -> Result<Vec<(String, V)>, Error<E>> {
        let mut objs = vec![];

        for entry in fs::read_dir(&self.dir)? {
            let entry = entry?;
            let name = entry.file_name().into_string().unwrap();

            let buff = fs::read(entry.path())?;
            let obj: V = V::decode(&buff).map_err(|e| Error::Inner(e) )?;

            objs.push((name, obj));
        }

        Ok(objs)
    }

    /// Store a colection of files in the database
    pub fn store_all(&mut self, data: &[(String, V)]) -> Result<(), Error<E>> {
        for (name, value) in data {
            self.store(name, value)?;
        }

        Ok(())
    }


    /// Remove a file from the database
    pub fn rm<P: AsRef<Path>>(&mut self, name: P) -> Result<(), Error<E>> {
        let mut path = self.dir.clone();
        path.push(name);

        fs::remove_file(path)?;

        Ok(())
    }

}

/// EncodeDecode trait must be implemented for FileStore types
pub trait EncodeDecode {
    type Value;
    type Error;

    fn encode(value: &Self::Value) -> Result<Vec<u8>, Self::Error>;
    fn decode(buff: &[u8]) -> Result<Self::Value, Self::Error>;
}

/// Automagic EncodeDecode implementation for serde capable types
impl <V> EncodeDecode for V
where
    V: Serialize + DeserializeOwned + Debug,
{
    type Value = V;
    type Error = serde_json::Error;

    fn encode(value: &Self::Value) -> Result<Vec<u8>, Self::Error> {
        serde_json::to_vec(value)
    }

    fn decode(buff: &[u8]) -> Result<Self::Value, Self::Error> {
        serde_json::from_slice(&buff)
    }
}


#[cfg(test)]
mod tests {
    use std::env;

    use super::*;

    const N: usize = 3;

    #[test]
    fn mock_database() {

        let dir = env::temp_dir();

        let mut s = FileStore::new(dir).unwrap();

        for i in 0..N {
            let name = format!("{}", i);

            s.store(&name, &i).unwrap();

            let v = s.load(&name).unwrap();

            assert_eq!(i, v);
        }
    }
}