risingwave_stream/common/change_buffer/
insertion_ordered_map.rs1use std::hash::{BuildHasher, Hash, RandomState};
16
17use hashbrown::HashTable;
18
19#[derive(Debug)]
23pub(super) struct InsertionOrderedMap<K, V> {
24 index: HashTable<usize>,
26 entries: Vec<Option<(K, V)>>,
28 hasher: RandomState,
29}
30
31pub(super) enum Entry<'a, K, V> {
32 Occupied(OccupiedEntry<'a, K, V>),
33 Vacant(VacantEntry<'a, K, V>),
34}
35
36pub(super) struct OccupiedEntry<'a, K, V> {
37 map: &'a mut InsertionOrderedMap<K, V>,
38 hash: u64,
39 pos: usize,
40}
41
42pub(super) struct VacantEntry<'a, K, V> {
43 map: &'a mut InsertionOrderedMap<K, V>,
44 hash: u64,
45 key: K,
46}
47
48impl<K, V> InsertionOrderedMap<K, V> {
49 pub(super) fn with_capacity(capacity: usize) -> Self {
50 Self {
51 index: HashTable::with_capacity(capacity),
52 entries: Vec::with_capacity(capacity),
53 hasher: RandomState::new(),
54 }
55 }
56
57 pub(super) fn len(&self) -> usize {
58 self.index.len()
59 }
60
61 pub(super) fn is_empty(&self) -> bool {
62 self.index.is_empty()
63 }
64
65 pub(super) fn into_values(self) -> impl Iterator<Item = V> {
66 self.entries.into_iter().flatten().map(|(_, value)| value)
67 }
68}
69
70impl<K: Hash + Eq, V> InsertionOrderedMap<K, V> {
71 pub(super) fn entry(&mut self, key: K) -> Entry<'_, K, V> {
72 let hash = self.hasher.hash_one(&key);
73 match self
74 .index
75 .find(hash, |&i| {
76 self.entries[i].as_ref().is_some_and(|(k, _)| *k == key)
77 })
78 .copied()
79 {
80 Some(pos) => Entry::Occupied(OccupiedEntry {
81 map: self,
82 hash,
83 pos,
84 }),
85 None => Entry::Vacant(VacantEntry {
86 map: self,
87 hash,
88 key,
89 }),
90 }
91 }
92
93 pub(super) fn insert(&mut self, key: K, value: V) {
95 match self.entry(key) {
96 Entry::Occupied(mut e) => *e.get_mut() = value,
97 Entry::Vacant(e) => e.insert(value),
98 }
99 }
100}
101
102impl<K, V> OccupiedEntry<'_, K, V> {
103 pub(super) fn get_mut(&mut self) -> &mut V {
104 &mut self.map.entries[self.pos]
105 .as_mut()
106 .expect("indexed entry should exist")
107 .1
108 }
109
110 pub(super) fn remove(self) {
111 let entry = self.map.index.find_entry(self.hash, |&i| i == self.pos);
112 entry.expect("entry should be indexed").remove();
113 self.map.entries[self.pos] = None;
114 }
115}
116
117impl<K: Hash, V> VacantEntry<'_, K, V> {
118 pub(super) fn insert(self, value: V) {
119 let InsertionOrderedMap {
120 index,
121 entries,
122 hasher,
123 } = self.map;
124 index.insert_unique(self.hash, entries.len(), |&i| {
125 hasher.hash_one(&entries[i].as_ref().expect("indexed entry should exist").0)
126 });
127 entries.push(Some((self.key, value)));
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use itertools::Itertools;
134
135 use super::*;
136
137 fn remove(map: &mut InsertionOrderedMap<i32, i32>, key: i32) {
138 let Entry::Occupied(e) = map.entry(key) else {
139 panic!("key {key} should be in the map");
140 };
141 e.remove();
142 }
143
144 #[test]
145 fn test_removed_key_goes_to_the_end_when_inserted_again() {
146 let mut map = InsertionOrderedMap::with_capacity(0);
147 map.insert(1, 10);
148 map.insert(2, 20);
149 map.insert(3, 30);
150 remove(&mut map, 1);
151 assert_eq!(map.len(), 2);
152
153 map.insert(1, 11);
154 map.insert(4, 40);
155 assert_eq!(map.len(), 4);
156 assert_eq!(map.into_values().collect_vec(), [20, 30, 11, 40]);
157 }
158
159 #[test]
160 fn test_replaced_key_keeps_its_position() {
161 let mut map = InsertionOrderedMap::with_capacity(0);
162 map.insert(1, 10);
163 map.insert(2, 20);
164 map.insert(1, 11);
165 assert_eq!(map.len(), 2);
166 assert_eq!(map.into_values().collect_vec(), [11, 20]);
167 }
168}