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
//! A storage system for objects (structs) stored by key.

use std::marker::PhantomData;
use std::str::from_utf8;

use serde::{de::DeserializeOwned, Serialize};
use serde_json::{from_str, to_string};

type Result<T> = std::result::Result<T, Error>;

/// The errors this package returns.
#[derive(Debug)]
pub enum Error {
    /// This is more of a generic error that something bad happened.
    SystemError(String),

    /// Serailization/Deserialization failed for some reason.
    Serialization(String),

    /// The process did not have permissions to perform the operation.
    PermissionDenied,
}

/// A Collection contains serializable objects which are accessible by
/// a key.
pub trait Collection {
    /// Put the given value into the collection under the given
    /// key. If the key already exists, it's replaced with the given
    /// value and the old value is returned.
    fn put<T>(&mut self, key: &str, value: T) -> Result<Option<T>>
    where
        T: Serialize + DeserializeOwned;

    // Get the value associated with the given key.
    fn get<T>(&mut self, key: &str) -> Result<Option<T>>
    where
        T: Serialize + DeserializeOwned;

    /// Find all the files that have the given prefix and iterate over
    /// them.
    fn prefix<'a, T>(&mut self, prefix: &str) -> Box<dyn Iterator<Item = Result<T>> + 'a>
    where
        T: Serialize + DeserializeOwned + 'a;
}

/// Sled is an impementation of a Collection using Sled to store the objects.
pub struct Sled {
    db: sled::Db,
}

impl Sled {
    /// Open the given sled database.
    pub fn open(file: &str) -> Result<Self> {
        let db = match sled::open(file) {
            Ok(db) => db,
            Err(e) => return Err(Error::SystemError(e.to_string())),
        };

        Ok(Self { db: db })
    }
}

impl Collection for Sled {
    fn put<T>(&mut self, key: &str, value: T) -> Result<Option<T>>
    where
        T: Serialize + DeserializeOwned,
    {
        // Convert to JSON.
        let json = match to_string(&value) {
            Ok(str) => str,
            Err(err) => return Err(Error::Serialization(err.to_string())),
        };

        // Insert into database.
        let value = match self.db.insert(key.as_bytes(), json.as_bytes()) {
            Ok(value) => match value {
                Some(value) => value,
                None => return Ok(None),
            },
            Err(err) => return Err(Error::SystemError(err.to_string())),
        };

        // If we replaced an existing value, convert it to it's type
        // so we can return it.
        let json = match from_utf8(&value) {
            Ok(json) => json,
            Err(err) => return Err(Error::Serialization(err.to_string())),
        };
        let obj: T = match from_str(json) {
            Ok(json) => json,
            Err(err) => return Err(Error::Serialization(err.to_string())),
        };

        Ok(Some(obj))
    }

    fn get<T>(&mut self, key: &str) -> Result<Option<T>>
    where
        T: Serialize + DeserializeOwned,
    {
        // Get the value from the database.
        let ivec = match self.db.get(key.as_bytes()) {
            Err(err) => return Err(Error::SystemError(err.to_string())),
            Ok(ivec) => match ivec {
                Some(ivec) => ivec,
                None => return Ok(None),
            },
        };

        // Convert it to the given type and return it.
        let json = match from_utf8(&ivec) {
            Ok(json) => json,
            Err(err) => return Err(Error::Serialization(err.to_string())),
        };
        let json: T = match from_str(json) {
            Ok(json) => json,
            Err(err) => return Err(Error::Serialization(err.to_string())),
        };

        Ok(Some(json))
    }

    fn prefix<'a, T>(&mut self, prefix: &str) -> Box<dyn Iterator<Item = Result<T>> + 'a>
    where
        T: Serialize + DeserializeOwned + 'a,
    {
        Box::new(SledIter {
            p: PhantomData,
            iter: self.db.scan_prefix(prefix.as_bytes()),
        })
    }
}

/// SledIter implements the std Iterator for the prefix method.
pub struct SledIter<T> {
    p: PhantomData<T>,
    iter: sled::Iter,
}

impl<T> Iterator for SledIter<T>
where
    T: DeserializeOwned,
{
    type Item = Result<T>;
    fn next(&mut self) -> Option<Self::Item> {
        // Get the next value.
        let data = match self.iter.next() {
            Some(r) => match r {
                Ok(data) => data,
                Err(e) => return Some(Err(Error::SystemError(e.to_string()))),
            },
            None => return None,
        };

        // Convert it to the given type and return it.
        let json = match from_utf8(&(data.1)) {
            Ok(json) => json,
            Err(err) => return Some(Err(Error::Serialization(err.to_string()))),
        };
        let json: T = match from_str(json) {
            Ok(json) => json,
            Err(err) => return Some(Err(Error::Serialization(err.to_string()))),
        };
        Some(Ok(json))
    }
}

#[cfg(test)]
mod tests {
    use crate::collection::*;
    use serde::{Deserialize, Serialize};
    use tempfile::tempdir;

    #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
    struct Person {
        name: String,
    }

    #[test]
    fn collection_get_put() {
        let file = tempdir().expect("unable to make temp file");
        let mut s = Sled::open(file.path().to_str().unwrap()).expect("failed to open with sled");

        let p = Person {
            name: "foo".to_string(),
        };
        s.put::<Person>(p.name.as_str(), p.clone())
            .expect("failed to put foo");

        let r = s
            .get::<Person>(p.name.as_str())
            .expect("failed to get foo")
            .unwrap();
        assert_eq!(p, r);

        assert_eq!(
            s.get::<Person>("i don't exist")
                .expect("failed to get non-existant"),
            None
        );
    }

    #[test]
    fn collection_prefix() {
        let file = tempdir().expect("unable to make temp file");
        let mut s = Sled::open(file.path().to_str().unwrap()).expect("failed to open with sled");

        let pp = vec![
            Person {
                name: "foo".to_string(),
            },
            Person {
                name: "bar/foo0".to_string(),
            },
            Person {
                name: "bar/foo1".to_string(),
            },
            Person {
                name: "bar/foo2".to_string(),
            },
            Person {
                name: "baz".to_string(),
            },
        ];

        for p in pp {
            s.put::<Person>(p.name.as_str(), p.clone())
                .expect("failed to put");
        }

        let rr = s
            .prefix::<Person>("bar/")
            .map(|r| r.expect("collecting"))
            .collect::<Vec<Person>>();

        let exp = vec![
            Person {
                name: "bar/foo0".to_string(),
            },
            Person {
                name: "bar/foo1".to_string(),
            },
            Person {
                name: "bar/foo2".to_string(),
            },
        ];

        assert_eq!(rr, exp);
    }
}