Skip to main content

risingwave_stream/common/change_buffer/
insertion_ordered_map.rs

1// Copyright 2026 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::hash::{BuildHasher, Hash, RandomState};
16
17use hashbrown::HashTable;
18
19/// A hash map that iterates in insertion order like `IndexMap`, but removes a key in O(1): the
20/// key leaves a hole instead of shifting the entries after it, and goes to the end if inserted
21/// again.
22#[derive(Debug)]
23pub(super) struct InsertionOrderedMap<K, V> {
24    /// Positions in `entries` of the keys in the map.
25    index: HashTable<usize>,
26    /// `None` marks a removed entry.
27    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    /// Insert the value, replacing the value of an existing key in place.
94    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}