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
// #![deny(missing_docs)]
//! Sled engine implementation
use sled::Db;
use std::path::PathBuf;

use crate::engine::KvsEngine;
use crate::error::{KVSError, Result};

const DATABASE_FILENAME: &str = "sled.db";

/// Usage
/// ```rust
/// # use std::error::Error;
/// # use assert_cmd::prelude::*;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use std::path::Path;
/// use crate::kvs::KvsEngine;
/// use kvs::SledStore;
///
/// let mut path = Path::new("/tmp/sled");
///
/// let mut store = SledStore::open(path).unwrap();
/// store.set("key1".to_owned(), "value1".to_owned());
/// assert_eq!(store.get("key1".to_owned())?, Some("value1".to_owned()));
/// store.remove("key1".to_owned());
/// #
/// #     Ok(())
/// # }
/// ```

/// In memory key value storage String:String
///
#[derive(Debug)]
pub struct SledStore {
    tree: Db,
}

impl KvsEngine for SledStore {
    /// Set up value by key into Sled
    fn set(&mut self, key: String, value: String) -> Result<()> {
        self.tree.insert(key, value.as_bytes())?;
        self.tree.flush()?;
        Ok(())
    }
    /// Get value by key
    fn get(&mut self, key: String) -> Result<Option<String>> {
        let val_ivec = self.tree.get(&key)?;

        match val_ivec {
            Some(ivec) => {
                let value = String::from_utf8(ivec.to_vec())?;
                Ok(Some(value))
            }
            None => Ok(None),
        }
    }
    /// Removes value by key
    fn remove(&mut self, key: String) -> Result<()> {
        if let Ok(old_value_option) = self.tree.remove(&key) {
            match old_value_option {
                Some(_v) => {
                    self.tree.flush()?;
                    Ok(())
                }
                None => Err(KVSError::GeneralKVSError),
            }
        } else {
            Err(KVSError::GeneralKVSError)
        }
    }
}

impl SledStore {
    /// Create new instance of Sled
    pub fn new(path: PathBuf) -> Result<Self> {
        let tree = sled::open(path)?;
        let obj = Self { tree };
        Ok(obj)
    }

    /// Open the Sled at a given path. Return the Sled tree.
    pub fn open(path: impl Into<PathBuf>) -> Result<SledStore> {
        let mut path_buf = path.into();
        path_buf.push(DATABASE_FILENAME);
        SledStore::new(path_buf)
    }
}