composable_indexes/index/
keys.rs1use crate::ShallowClone;
2use crate::core::{Index, Insert, Key, Remove, Seal};
3use crate::index::generic::{DefaultKeySet, KeySet};
4
5#[derive(Clone)]
7pub struct Keys<KeySet = DefaultKeySet> {
8 pub keys: KeySet,
9}
10
11impl<KeySet_: KeySet + Default> Default for Keys<KeySet_> {
12 fn default() -> Self {
13 Keys {
14 keys: KeySet_::default(),
15 }
16 }
17}
18
19impl<KeySet: ShallowClone> ShallowClone for Keys<KeySet> {}
20
21impl Keys<DefaultKeySet> {
22 pub fn new() -> Self {
23 Self::default()
24 }
25}
26
27impl<KeySet_: KeySet> Keys<KeySet_> {
28 pub fn with_keyset() -> Self {
29 Self::default()
30 }
31}
32
33impl<In, KeySet_: KeySet> Index<In> for Keys<KeySet_> {
34 #[inline]
35 fn insert(&mut self, _seal: Seal, op: &Insert<In>) {
36 self.keys.insert(op.key);
37 }
38 #[inline]
39 fn remove(&mut self, _seal: Seal, op: &Remove<In>) {
40 self.keys.remove(&op.key);
41 }
42}
43impl<KeySet_: KeySet> Keys<KeySet_> {
44 pub fn all(&self) -> impl Iterator<Item = Key> {
45 self.keys.iter()
46 }
47
48 pub fn contains(&self, key: &Key) -> bool {
49 self.keys.contains(key)
50 }
51
52 pub fn count(&self) -> usize {
53 self.keys.count()
54 }
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60 use crate::{
61 core::Collection,
62 testutils::{SortedVec, prop_assert_reference},
63 };
64
65 #[test]
66 fn test_basic() {
67 let mut coll = Collection::<u8, _>::new(Keys::new());
68
69 let key1 = coll.insert(1);
70 let key2 = coll.insert(2);
71
72 assert!(coll.query(|ix| ix.contains(&key1)));
73 assert!(coll.query(|ix| ix.contains(&key2)));
74 assert_eq!(coll.query(|ix| ix.count()), 2);
75 }
76
77 #[test]
78 fn test_all() {
79 prop_assert_reference(
80 Keys::new,
81 |db| {
82 db.query(|ix| ix.all().collect::<Vec<_>>())
83 .into_iter()
84 .copied()
85 .collect::<SortedVec<_>>()
86 },
87 |xs: Vec<u8>| xs.into_iter().collect::<SortedVec<_>>(),
88 None,
89 );
90 }
91}