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
use std::path::{Path, PathBuf};
use std::{fs, io};

use crate::error::Error;
use serde::{Deserialize, Serialize};

/// Config is used to create a new store
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Config {
    /// The `path` field determines where the database will be created
    pub path: PathBuf,

    /// The `temporary` field specifies if the database will be destroyed on close
    #[serde(default)]
    pub temporary: bool,

    /// Enable compression by setting `use_compression` to true
    #[serde(default)]
    pub use_compression: bool,

    /// Specify the flush frequency
    #[serde(default)]
    pub flush_every_ms: Option<u64>,

    /// Specify the cache capacity in bytes
    #[serde(default)]
    pub cache_capacity: Option<u64>,

    /// Specify the segment size for compatibility
    #[serde(default)]
    pub segment_size: Option<usize>,
}

impl Config {
    /// Create a default configuration object
    pub fn new<P: AsRef<Path>>(p: P) -> Config {
        Config {
            path: p.as_ref().to_path_buf(),
            temporary: false,
            use_compression: false,
            flush_every_ms: None,
            cache_capacity: None,
            segment_size: None,
        }
    }

    /// Save Config to an io::Write
    pub fn save_to<W: io::Write>(&self, mut w: W) -> Result<(), Error> {
        let s = match toml::to_string(self) {
            Ok(s) => s,
            Err(_) => return Err(Error::InvalidConfiguration),
        };
        w.write_all(s.as_ref())?;
        Ok(())
    }

    /// Save Config to a file
    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
        let file = fs::File::create(path.as_ref())?;
        self.save_to(file)
    }

    /// Load configuration from an io::Read
    pub fn load_from<R: io::Read>(mut r: R) -> Result<Config, Error> {
        let mut buf = Vec::new();
        r.read_to_end(&mut buf)?;
        match toml::from_slice(buf.as_ref()) {
            Ok(cfg) => Ok(cfg),
            Err(_) => Err(Error::InvalidConfiguration),
        }
    }

    /// Load configuration to a file
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Config, Error> {
        let file = fs::File::open(path.as_ref())?;
        Self::load_from(file)
    }

    /// Set compression field
    pub fn use_compression(mut self, use_compression: bool) -> Config {
        self.use_compression = use_compression;
        self
    }

    /// Toggle `temporary` value
    pub fn temporary(mut self, temporary: bool) -> Config {
        self.temporary = temporary;
        self
    }

    /// Set flush frequency
    pub fn flush_every_ms(mut self, ms: u64) -> Config {
        self.flush_every_ms = Some(ms);
        self
    }

    /// Set cache capacity
    pub fn cache_capacity(mut self, bytes: u64) -> Config {
        self.cache_capacity = Some(bytes);
        self
    }

    /// Set cache capacity
    pub fn segment_size(mut self, kb: usize) -> Config {
        self.segment_size = Some(kb);
        self
    }

    pub(crate) fn open(&mut self) -> Result<sled::Db, Error> {
        let config = sled::Config::new()
            .path(&self.path)
            .temporary(self.temporary)
            .flush_every_ms(self.flush_every_ms)
            .use_compression(self.use_compression);
        let config = if let Some(cache_capacity) = self.cache_capacity {
            config.cache_capacity(cache_capacity)
        } else {
            config
        };
        let config = if let Some(segment_size) = self.segment_size {
            // allow old database to work
            config.segment_size(segment_size)
        } else {
            config
        };
        let db = config.open()?;
        Ok(db)
    }
}