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
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]

#[cfg(all(rocksdb_backend, sled_backend, redb_backend))]
compile_error!(
    "the \"rocksdb\", \"redb\" and \"sled\" features may not be enabled at the same time"
);

#[cfg(not(any(rocksdb_backend, sled_backend, redb_backend, wasm)))]
compile_error!("either the \"rocksdb\", \"redb\" or \"sled\" feature must be enabled on native");

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

trait StoreImpl {
    type GetError;
    type SetError;

    fn set_string(&mut self, key: &str, value: &str) -> Result<(), Self::SetError> {
        self.set(key, &value.to_string())
    }
    fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T, Self::GetError>;
    fn set<T: Serialize>(&mut self, key: &str, value: &T) -> Result<(), Self::SetError>;
    fn clear(&mut self) -> Result<(), Self::SetError>;
}

#[cfg(wasm)]
mod local_storage_store;

#[cfg(wasm)]
use local_storage_store::{self as backend};

#[cfg(sled_backend)]
mod sled_store;

#[cfg(sled_backend)]
use sled_store::{self as backend};

#[cfg(rocksdb_backend)]
mod rocksdb_store;

#[cfg(rocksdb_backend)]
use rocksdb_store::{self as backend};

// todo: Look into unifying these types?
pub use backend::{GetError, SetError};

enum Location<'a> {
    PlatformDefault(&'a PlatformDefault),
    #[cfg(any(sled_backend, rocksdb_backend, redb_backend))]
    CustomPath(&'a std::path::Path),
}

#[cfg(redb_backend)]
mod redb_store;

#[cfg(redb_backend)]
use redb_store::{self as backend};

#[cfg(any(sled_backend, rocksdb_backend, redb_backend))]
mod path;

/// Main resource for setting/getting values
#[derive(Debug)]
#[cfg_attr(feature = "bevy", derive(bevy_ecs::prelude::Resource))]
pub struct PkvStore {
    inner: backend::InnerStore,
}

impl PkvStore {
    /// Creates or opens a persistent key value store
    ///
    /// The given `organization` and `application` are used to create a backing file
    /// in a corresponding location on the users device. Usually within the home or user folder
    pub fn new(organization: &str, application: &str) -> Self {
        let config = PlatformDefault {
            qualifier: None,
            organization: organization.to_string(),
            application: application.to_string(),
        };
        Self::new_in_location(&config)
    }

    /// Creates or opens a persistent key value store
    ///
    /// Like [`PkvStore::new`], but also provide a qualifier.
    /// Some operating systems use the qualifier as part of the path to the store.
    /// The qualifier is usually "com", "org" etc.
    pub fn new_with_qualifier(qualifier: &str, organization: &str, application: &str) -> Self {
        let config = PlatformDefault {
            qualifier: Some(qualifier.to_string()),
            organization: organization.to_string(),
            application: application.to_string(),
        };
        Self::new_in_location(&config)
    }

    /// Creates or opens a persistent key value store
    ///
    /// Like [`PkvStore::new`], but requires a direct path.
    /// The `path` is used to create a backing file
    /// in a corresponding location on the users device.
    #[cfg(any(sled_backend, rocksdb_backend, redb_backend))]
    pub fn new_in_dir<P: AsRef<std::path::Path>>(path: P) -> Self {
        let inner = backend::InnerStore::new(Location::CustomPath(path.as_ref()));
        Self { inner }
    }

    fn new_in_location(config: &PlatformDefault) -> Self {
        let inner = backend::InnerStore::new(Location::PlatformDefault(config));
        Self { inner }
    }

    /// Serialize and store the value
    pub fn set<T: Serialize>(&mut self, key: impl AsRef<str>, value: &T) -> Result<(), SetError> {
        self.inner.set(key.as_ref(), value)
    }

    /// More or less the same as set::<String>, but can take a &str
    pub fn set_string(&mut self, key: impl AsRef<str>, value: &str) -> Result<(), SetError> {
        self.inner.set_string(key.as_ref(), value)
    }

    /// Get the value for the given key
    /// returns Err(GetError::NotFound) if the key does not exist in the key value store.
    pub fn get<T: DeserializeOwned>(&self, key: impl AsRef<str>) -> Result<T, GetError> {
        self.inner.get(key.as_ref())
    }

    /// Clear all key values data
    /// returns Err(SetError) if clear error
    pub fn clear(&mut self) -> Result<(), SetError> {
        self.inner.clear()
    }
}

struct PlatformDefault {
    qualifier: Option<String>,
    organization: String,
    application: String,
}

#[cfg(test)]
mod tests {
    use crate::PkvStore;
    use serde::{Deserialize, Serialize};

    // note: These tests use the real deal. Might be a good idea to clean the BevyPkv folder in .local/share
    // to get fresh tests.

    fn setup() {
        // When building for WASM, print panics to the browser console
        #[cfg(target_arch = "wasm32")]
        console_error_panic_hook::set_once();
    }

    #[test]
    fn set_string() {
        setup();
        let mut store = PkvStore::new("BevyPkv", "test_set_string");
        store.set_string("hello", "goodbye").unwrap();
        let ret = store.get::<String>("hello");
        assert_eq!(ret.unwrap(), "goodbye");
    }

    #[cfg(any(sled_backend, rocksdb_backend, redb_backend))]
    #[test]
    fn new_in_dir() {
        setup();

        let dirs = directories::ProjectDirs::from("", "BevyPkv", "test_new_in_dir");
        let parent_dir = match dirs.as_ref() {
            Some(dirs) => dirs.data_dir(),
            None => std::path::Path::new("."), // todo: maybe warn?
        };

        let mut store = PkvStore::new_in_dir(parent_dir);

        store
            .set_string("hello_custom_path", "goodbye_custom_path")
            .unwrap();
        let ret = store.get::<String>("hello_custom_path");
        assert_eq!(ret.unwrap(), "goodbye_custom_path");
    }

    #[cfg(any(sled_backend, rocksdb_backend, redb_backend))]
    #[test]
    fn empty_db_not_found() {
        use crate::GetError;

        setup();

        let dir = tempfile::tempdir().expect("failed to create temp dir");
        let store = PkvStore::new_in_dir(dir.path());

        let err = store.get::<String>("not_there").unwrap_err();

        // todo: Use assert_matches! when stable
        assert!(matches!(err, GetError::NotFound));
    }

    #[test]
    fn clear() {
        setup();
        let mut store = PkvStore::new("BevyPkv", "test_clear");

        // More than 1 key-value pair was added to the test because the
        // RocksDB adapter uses an iterator in order to implement .clear()
        store.set_string("key1", "goodbye").unwrap();
        store.set_string("key2", "see yeah!").unwrap();

        let ret = store.get::<String>("key1").unwrap();
        let ret2 = store.get::<String>("key2").unwrap();

        assert_eq!(ret, "goodbye");
        assert_eq!(ret2, "see yeah!");

        store.clear().unwrap();
        let ret = store.get::<String>("key1").ok();
        let ret2 = store.get::<String>("key2").ok();
        assert_eq!((ret, ret2), (None, None))
    }

    #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
    struct User {
        name: String,
        age: u8,
    }

    #[test]
    fn set() {
        setup();
        let mut store = PkvStore::new("BevyPkv", "test_set");
        let user = User {
            name: "alice".to_string(),
            age: 32,
        };
        store.set("user", &user).unwrap();
        assert_eq!(store.get::<User>("user").unwrap(), user);
    }
}