zrx_store/store.rs
1// Copyright (c) 2025-2026 Zensical and contributors
2
3// SPDX-License-Identifier: MIT
4// All contributions are certified under the DCO
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to
8// deal in the Software without restriction, including without limitation the
9// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10// sell copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in
14// all copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22// IN THE SOFTWARE.
23
24// ----------------------------------------------------------------------------
25
26//! Store traits.
27
28use std::borrow::Borrow;
29use std::ops::RangeBounds;
30
31pub mod adapter;
32pub mod collection;
33pub mod comparator;
34pub mod decorator;
35pub mod item;
36
37use comparator::Comparator;
38use item::{Key, Value};
39
40// ----------------------------------------------------------------------------
41// Traits
42// ----------------------------------------------------------------------------
43
44/// Immutable store.
45///
46/// This trait defines the required methods for an immutable key-value store,
47/// abstracting over implementations like [`HashMap`][] and [`BTreeMap`][]. It
48/// forms the foundation for a set of further traits that define complementary
49/// capabilities for stores, like [`StoreMut`] and [`StoreIterable`].
50///
51/// There are several of those traits, all of which can be composed in trait
52/// bounds to require specific store capabilities. These are:
53///
54/// - [`StoreMut`]: Mutable store
55/// - [`StoreMutRef`]: Mutable store that can return mutable references
56/// - [`StoreIterable`]: Immutable store that is iterable
57/// - [`StoreIterableMut`]: Mutable store that is iterable
58/// - [`StoreKeys`]: Immutable store that is iterable over its keys
59/// - [`StoreValues`]: Immutable store that is iterable over its values
60/// - [`StoreRange`]: Immutable store that is iterable over a range
61///
62/// This trait is implemented for [`HashMap`][] and [`BTreeMap`][], as well as
63/// all of the store [`decorators`][] that allow to wrap stores with additional
64/// capabilities. Note that stores are not thread-safe, so they can't be shared
65/// among worker threads.
66///
67/// All methods deliberately have [`Infallible`] signatures, as stores must be
68/// fast and reliable, and should never fail under normal circumstances. Stores
69/// should not need to serialize data, write to the filesystem, or send data
70/// over the network. They should only have in-memory representations.
71///
72/// [`decorators`]: crate::store::decorator
73/// [`BTreeMap`]: std::collections::BTreeMap
74/// [`HashMap`]: std::collections::HashMap
75/// [`Infallible`]: std::convert::Infallible
76///
77/// # Examples
78///
79/// ```
80/// use std::collections::HashMap;
81/// use zrx_store::StoreMut;
82///
83/// // Create store and initial state
84/// let mut store = HashMap::new();
85/// store.insert("key", 42);
86///
87/// // Obtain reference to value
88/// let value = store.get(&"key");
89/// assert_eq!(value, Some(&42));
90/// ```
91pub trait Store<K, V>
92where
93 K: Key,
94{
95 /// Returns a reference to the value identified by the key.
96 fn get<Q>(&self, key: &Q) -> Option<&V>
97 where
98 K: Borrow<Q>,
99 Q: Key;
100
101 /// Returns whether the store contains the key.
102 fn contains_key<Q>(&self, key: &Q) -> bool
103 where
104 K: Borrow<Q>,
105 Q: Key;
106
107 /// Returns the number of items in the store.
108 fn len(&self) -> usize;
109
110 /// Returns whether the store is empty.
111 #[inline]
112 fn is_empty(&self) -> bool {
113 self.len() == 0
114 }
115}
116
117/// Mutable store.
118///
119/// This trait extends [`Store`], requiring further additional mutable methods
120/// which can be used to alter the store, like inserting and removing items.
121///
122/// # Examples
123///
124/// ```
125/// use std::collections::HashMap;
126/// use zrx_store::StoreMut;
127///
128/// // Create store and initial state
129/// let mut store = HashMap::new();
130/// store.insert("key", 42);
131///
132/// // Remove value from store
133/// let value = store.remove(&"key");
134/// assert_eq!(value, Some(42));
135/// ```
136pub trait StoreMut<K, V>: Store<K, V>
137where
138 K: Key,
139{
140 /// Inserts the value identified by the key.
141 fn insert(&mut self, key: K, value: V) -> Option<V>;
142
143 /// Inserts the value identified by the key if it changed.
144 fn insert_if_changed(&mut self, key: &K, value: &V) -> bool
145 where
146 V: Clone + Eq,
147 {
148 (self.get(key) != Some(value))
149 .then(|| self.insert(key.clone(), value.clone()))
150 .is_some()
151 }
152
153 /// Removes the value identified by the key.
154 fn remove<Q>(&mut self, key: &Q) -> Option<V>
155 where
156 K: Borrow<Q>,
157 Q: Key;
158
159 /// Removes the value identified by the key and returns both.
160 fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
161 where
162 K: Borrow<Q>,
163 Q: Key;
164
165 /// Clears the store, removing all items.
166 fn clear(&mut self);
167}
168
169/// Mutable store that can return mutable references.
170///
171/// This trait extends [`StoreMut`], adding the possibility to obtain mutable
172/// references as a requirement, so values can be mutated in-place.
173///
174/// # Examples
175///
176/// ```
177/// use std::collections::HashMap;
178/// use zrx_store::{StoreMut, StoreMutRef};
179///
180/// // Create store and initial state
181/// let mut store = HashMap::new();
182/// store.insert("key", 42);
183///
184/// // Obtain mutable reference to value
185/// let mut value = store.get_mut(&"key");
186/// assert_eq!(value, Some(&mut 42));
187/// ```
188pub trait StoreMutRef<K, V>: Store<K, V>
189where
190 K: Key,
191{
192 /// Returns a mutable reference to the value identified by the key.
193 fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
194 where
195 K: Borrow<Q>,
196 Q: Key;
197
198 /// Returns a mutable reference to the value or creates the default.
199 fn get_or_insert_default(&mut self, key: &K) -> &mut V
200 where
201 V: Default;
202}
203
204/// Immutable store that is iterable.
205///
206/// This trait extends [`Store`], adding iteration capabilities as a further
207/// requirement, so a store can enumerate its items.
208///
209/// # Examples
210///
211/// ```
212/// use std::collections::HashMap;
213/// use zrx_store::{StoreIterable, StoreMut};
214///
215/// // Create store and initial state
216/// let mut store = HashMap::new();
217/// store.insert("key", 42);
218///
219/// // Create iterator over the store
220/// for (key, value) in store.iter() {
221/// println!("{key}: {value}");
222/// }
223/// ```
224pub trait StoreIterable<K, V>: Store<K, V>
225where
226 K: Key,
227 V: Value,
228{
229 type Iter<'a>: Iterator<Item = (&'a K, &'a V)>
230 where
231 Self: 'a;
232
233 /// Creates an iterator over the items of the store.
234 fn iter(&self) -> Self::Iter<'_>;
235}
236
237/// Mutable store that is iterable.
238///
239/// This trait extends [`StoreMut`], adding mutable iteration capabilities as a
240/// requirement, so a store can enumerate its items mutably.
241///
242/// # Examples
243///
244/// ```
245/// use std::collections::HashMap;
246/// use zrx_store::{StoreIterableMut, StoreMut};
247///
248/// // Create store and initial state
249/// let mut store = HashMap::new();
250/// store.insert("key", 42);
251///
252/// // Create iterator over the store
253/// for (key, value) in store.iter_mut() {
254/// println!("{key}: {value}");
255/// }
256/// ```
257pub trait StoreIterableMut<K, V>: StoreMut<K, V>
258where
259 K: Key,
260 V: Value,
261{
262 type IterMut<'a>: Iterator<Item = (&'a K, &'a mut V)>
263 where
264 Self: 'a;
265
266 /// Creates a mutable iterator over the items of the store.
267 fn iter_mut(&mut self) -> Self::IterMut<'_>;
268}
269
270/// Immutable store that is iterable over its keys.
271///
272/// This trait extends [`Store`], adding key iteration capabilities as a
273/// requirement, so a store can enumerate its keys.
274///
275/// # Examples
276///
277/// ```
278/// use std::collections::HashMap;
279/// use zrx_store::{StoreKeys, StoreMut};
280///
281/// // Create store and initial state
282/// let mut store = HashMap::new();
283/// store.insert("key", 42);
284///
285/// // Create iterator over the store
286/// for key in store.keys() {
287/// println!("{key}");
288/// }
289/// ```
290pub trait StoreKeys<K, V>: Store<K, V>
291where
292 K: Key,
293{
294 type Keys<'a>: Iterator<Item = &'a K>
295 where
296 Self: 'a;
297
298 /// Creates an iterator over the keys of the store.
299 fn keys(&self) -> Self::Keys<'_>;
300}
301
302/// Immutable store that is iterable over its values.
303///
304/// This trait extends [`Store`], adding value iteration capabilities as a
305/// requirement, so a store can enumerate its values.
306///
307/// # Examples
308///
309/// ```
310/// use std::collections::HashMap;
311/// use zrx_store::{StoreMut, StoreValues};
312///
313/// // Create store and initial state
314/// let mut store = HashMap::new();
315/// store.insert("key", 42);
316///
317/// // Create iterator over the store
318/// for value in store.values() {
319/// println!("{value}");
320/// }
321/// ```
322pub trait StoreValues<K, V>: Store<K, V>
323where
324 K: Key,
325 V: Value,
326{
327 type Values<'a>: Iterator<Item = &'a V>
328 where
329 Self: 'a;
330
331 /// Creates an iterator over the values of the store.
332 fn values(&self) -> Self::Values<'_>;
333}
334
335/// Immutable store that is iterable over a range.
336///
337/// This trait extends [`Store`], adding iteration capabilities as a further
338/// requirement, so a store can enumerate its items over a given range.
339///
340/// # Examples
341///
342/// ```
343/// use std::collections::BTreeMap;
344/// use zrx_store::{StoreMut, StoreRange};
345///
346/// // Create store and initial state
347/// let mut store = BTreeMap::new();
348/// store.insert("a", 42);
349/// store.insert("b", 84);
350///
351/// // Create iterator over the store
352/// for (key, value) in store.range("b"..) {
353/// println!("{key}: {value}");
354/// }
355/// ```
356pub trait StoreRange<K, V>: Store<K, V>
357where
358 K: Key,
359 V: Value,
360{
361 type Range<'a>: Iterator<Item = (&'a K, &'a V)>
362 where
363 Self: 'a;
364
365 /// Creates an iterator over a range of items of the store.
366 fn range<R>(&self, range: R) -> Self::Range<'_>
367 where
368 R: RangeBounds<K>;
369}
370
371// ----------------------------------------------------------------------------
372
373/// Creates a store with a comparator.
374///
375/// This trait extends [`Store`], adding the capability to create a store with
376/// a custom comparator, allowing to customize the ordering of values.
377///
378/// # Examples
379///
380/// ```
381/// use std::collections::HashMap;
382/// use zrx_store::comparator::Descending;
383/// use zrx_store::decorator::Ordered;
384/// use zrx_store::{StoreMut, StoreWithComparator};
385///
386/// // Create store
387/// let mut store: Ordered::<_, _, HashMap<_, _>, _> =
388/// Ordered::with_comparator(Descending);
389///
390/// // Insert value
391/// store.insert("key", 42);
392/// ```
393pub trait StoreWithComparator<K, V, C>: Store<K, V>
394where
395 K: Key,
396 C: Comparator<V>,
397{
398 /// Creates a store with the given comparator.
399 fn with_comparator(comparator: C) -> Self;
400}
401
402// ----------------------------------------------------------------------------
403
404/// Creates a store from an iterator.
405pub trait StoreFromIterator<K, V>: FromIterator<(K, V)> {}
406
407/// Creates an iterator over the items of the store.
408pub trait StoreIntoIterator<K, V>: IntoIterator<Item = (K, V)> {}
409
410// ----------------------------------------------------------------------------
411// Blanket implementations
412// ----------------------------------------------------------------------------
413
414#[rustfmt::skip]
415impl<K, V, T> StoreFromIterator<K, V> for T
416where
417 T: FromIterator<(K, V)> {}
418
419#[rustfmt::skip]
420impl<K, V, T> StoreIntoIterator<K, V> for T
421where
422 T: IntoIterator<Item = (K, V)> {}