composable_indexes_core/
collection.rs1use std::collections::HashMap;
2
3use crate::index::{Index, QueryEnv};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6pub struct Key {
7 pub id: u64,
8}
9
10pub struct Collection<In, Ix> {
11 index: Ix,
12 data: HashMap<Key, In>,
13 next_key_id: u64,
14}
15
16impl<'t, In, Ix> Collection<In, Ix>
17where
18 Ix: Index<'t, In>,
19{
20 pub fn new(ix: Ix) -> Self {
21 Collection {
22 data: HashMap::new(),
23 next_key_id: 0,
24 index: ix,
25 }
26 }
27
28 pub fn get(&self, key: Key) -> Option<&In> {
29 self.data.get(&key)
30 }
31
32 pub fn iter(&self) -> impl Iterator<Item = (&Key, &In)> {
33 self.data.iter()
34 }
35
36 pub fn insert(&mut self, value: In) -> Key {
37 let key = self.mk_key();
38 let existing = self.data.insert(key, value);
39
40 debug_assert!(existing.is_none());
42
43 self.index.insert(&Insert {
44 key,
45 new: &self.data[&key],
46 });
47
48 key
49 }
50
51 pub fn update<F>(&mut self, key: Key, f: F)
52 where
53 F: FnOnce(Option<&In>) -> In,
54 {
55 let existing = self.data.get(&key);
56 let new = f(existing);
57
58 match existing {
59 Some(existing) => {
60 self.index.update(&Update {
61 key,
62 new: &new,
63 existing,
64 });
65 self.data.insert(key, new);
66 }
67 None => {
68 self.index.insert(&Insert { key, new: &new });
69 self.data.insert(key, new);
70 }
71 };
72 }
73
74 pub fn delete(&mut self, key: Key) {
75 match self.data.remove(&key) {
76 Some(ref existing) => {
77 self.index.remove(&Remove { key, existing });
78 }
79 None => {}
80 }
81 }
82
83 pub fn query(&'t self) -> Ix::Query<In> {
84 let env = QueryEnv { data: &self.data };
85 self.index.query(env)
86 }
87
88 pub fn len(&self) -> usize {
89 self.data.len()
90 }
91
92 fn mk_key(&mut self) -> Key {
93 let k = Key {
94 id: self.next_key_id,
95 };
96 self.next_key_id += 1;
97 k
98 }
99}
100
101#[derive(Clone)]
102pub struct Insert<'t, In> {
103 pub key: Key,
104 pub new: &'t In,
105}
106
107#[derive(Clone)]
108pub struct Update<'t, In> {
109 pub key: Key,
110 pub new: &'t In,
111 pub existing: &'t In,
112}
113
114#[derive(Clone)]
115pub struct Remove<'t, In> {
116 pub key: Key,
117 pub existing: &'t In,
118}