kvdb_lib/lib.rs
1use std::sync::Arc;
2use dashmap::DashMap;
3use dashmap::mapref::multiple::RefMulti;
4use dashmap::mapref::one::Ref;
5
6/// A thread-safe key-value storage using DashMap.
7///
8/// # Examples
9///
10///
11
12/// use kvdb_lib::Storage;
13///
14/// let storage = Storage::new();
15/// storage.set(1, "value1");
16///
17/// assert_eq!(storage.get(&1), Some("value1"));
18///
19
20pub struct Storage<K, V> {
21 map: Arc<DashMap<K, V>>,
22}
23
24impl<K, V> Storage<K, V>
25where
26 K: Eq + std::hash::Hash + Clone + Copy,
27 V: Clone + Copy,
28{
29 /// Creates a new, empty `Storage`.
30 ///
31 /// # Examples
32 ///
33 ///
34
35 /// use kvdb_lib::Storage;
36 ///
37 /// let storage: Storage<i32, &str> = Storage::new();
38 ///
39
40 pub fn new() -> Self {
41 Storage {
42 map: Arc::new(DashMap::new()),
43 }
44 }
45
46 /// Inserts a key-value pair into the storage.
47 ///
48 /// If the storage did not have this key present, `None` is returned.
49 /// If the storage did have this key present, the value is updated, and the old value is returned.
50 ///
51 /// # Examples
52 ///
53 ///
54
55 /// use kvdb_lib::Storage;
56 ///
57 /// let storage = Storage::new();
58 /// storage.set(1, "value1");
59 ///
60 /// assert_eq!(storage.get(&1), Some("value1"));
61 ///
62
63 pub fn set(&self, key: K, value: V) {
64 self.map.insert(key, value);
65 }
66
67 /// Retrieves a value from the storage, given a key.
68 ///
69 /// # Examples
70 ///
71 ///
72
73 /// use kvdb_lib::Storage;
74 ///
75 /// let storage = Storage::new();
76 /// storage.set(1, "value1");
77 ///
78 /// assert_eq!(storage.get(&1), Some("value1"));
79 ///
80
81 pub fn get(&self, key: &K) -> Option<V> {
82 self.map.get(key).map(|entry: Ref<K, V>| entry.value().clone())
83 }
84
85 /// Retrieves all key-value pairs from the storage as a vector of tuples.
86 ///
87 /// # Examples
88 ///
89 ///
90
91 /// use kvdb_lib::Storage;
92 ///
93 /// let storage = Storage::new();
94 ///
95 /// storage.set(1, "value1");
96 /// storage.set(2, "value2");
97 /// let all = storage.get_all();
98 ///
99 /// assert_eq!(all.len(), 2);
100 /// assert!(all.contains(&(1, "value1")));
101 /// assert!(all.contains(&(2, "value2")));
102 ///
103
104 pub fn get_all(&self) -> Vec<(K, V)> {
105 self.map.iter()
106 .map(|entry: RefMulti<K, V>| (entry.key().clone(), entry.value().clone()))
107 .collect()
108 }
109
110 /// Removes a key-value pair from the storage.
111 ///
112 /// # Examples
113 ///
114 ///
115
116 /// use kvdb_lib::Storage;
117 ///
118 /// let storage = Storage::new();
119 ///
120 /// storage.set(1, "value1");
121 /// storage.remove(1);
122 ///
123 /// assert_eq!(storage.get(&1), None);
124 ///
125
126 pub fn remove(&self, key: K) {
127 self.map.remove(&key);
128 }
129}