Replace `BTreeSet` in `IndexedMap` with sorted `Vec`
[rust-lightning] / lightning / src / util / indexed_map.rs
1 //! This module has a map which can be iterated in a deterministic order. See the [`IndexedMap`].
2
3 use crate::prelude::{HashMap, hash_map};
4 use alloc::vec::Vec;
5 use alloc::slice::Iter;
6 use core::hash::Hash;
7 use core::cmp::Ord;
8 use core::ops::{Bound, RangeBounds};
9
10 /// A map which can be iterated in a deterministic order.
11 ///
12 /// This would traditionally be accomplished by simply using a [`BTreeMap`], however B-Trees
13 /// generally have very slow lookups. Because we use a nodes+channels map while finding routes
14 /// across the network graph, our network graph backing map must be as performant as possible.
15 /// However, because peers expect to sync the network graph from us (and we need to support that
16 /// without holding a lock on the graph for the duration of the sync or dumping the entire graph
17 /// into our outbound message queue), we need an iterable map with a consistent iteration order we
18 /// can jump to a starting point on.
19 ///
20 /// Thus, we have a custom data structure here - its API mimics that of Rust's [`BTreeMap`], but is
21 /// actually backed by a [`HashMap`], with some additional tracking to ensure we can iterate over
22 /// keys in the order defined by [`Ord`].
23 ///
24 /// [`BTreeMap`]: alloc::collections::BTreeMap
25 #[derive(Clone, Debug, Eq)]
26 pub struct IndexedMap<K: Hash + Ord, V> {
27         map: HashMap<K, V>,
28         keys: Vec<K>,
29 }
30
31 impl<K: Clone + Hash + Ord, V> IndexedMap<K, V> {
32         /// Constructs a new, empty map
33         pub fn new() -> Self {
34                 Self {
35                         map: HashMap::new(),
36                         keys: Vec::new(),
37                 }
38         }
39
40         #[inline(always)]
41         /// Fetches the element with the given `key`, if one exists.
42         pub fn get(&self, key: &K) -> Option<&V> {
43                 self.map.get(key)
44         }
45
46         /// Fetches a mutable reference to the element with the given `key`, if one exists.
47         pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
48                 self.map.get_mut(key)
49         }
50
51         #[inline]
52         /// Returns true if an element with the given `key` exists in the map.
53         pub fn contains_key(&self, key: &K) -> bool {
54                 self.map.contains_key(key)
55         }
56
57         /// Removes the element with the given `key`, returning it, if one exists.
58         pub fn remove(&mut self, key: &K) -> Option<V> {
59                 let ret = self.map.remove(key);
60                 if let Some(_) = ret {
61                         let idx = self.keys.iter().position(|k| k == key).expect("map and keys must be consistent");
62                         self.keys.remove(idx);
63                 }
64                 ret
65         }
66
67         /// Inserts the given `key`/`value` pair into the map, returning the element that was
68         /// previously stored at the given `key`, if one exists.
69         pub fn insert(&mut self, key: K, value: V) -> Option<V> {
70                 let ret = self.map.insert(key.clone(), value);
71                 if ret.is_none() {
72                         self.keys.push(key);
73                 }
74                 ret
75         }
76
77         /// Returns an [`Entry`] for the given `key` in the map, allowing access to the value.
78         pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
79                 match self.map.entry(key.clone()) {
80                         hash_map::Entry::Vacant(entry) => {
81                                 Entry::Vacant(VacantEntry {
82                                         underlying_entry: entry,
83                                         key,
84                                         keys: &mut self.keys,
85                                 })
86                         },
87                         hash_map::Entry::Occupied(entry) => {
88                                 Entry::Occupied(OccupiedEntry {
89                                         underlying_entry: entry,
90                                         keys: &mut self.keys,
91                                 })
92                         }
93                 }
94         }
95
96         /// Returns an iterator which iterates over the keys in the map, in a random order.
97         pub fn unordered_keys(&self) -> impl Iterator<Item = &K> {
98                 self.map.keys()
99         }
100
101         /// Returns an iterator which iterates over the `key`/`value` pairs in a random order.
102         pub fn unordered_iter(&self) -> impl Iterator<Item = (&K, &V)> {
103                 self.map.iter()
104         }
105
106         /// Returns an iterator which iterates over the `key`s and mutable references to `value`s in a
107         /// random order.
108         pub fn unordered_iter_mut(&mut self) -> impl Iterator<Item = (&K, &mut V)> {
109                 self.map.iter_mut()
110         }
111
112         /// Returns an iterator which iterates over the `key`/`value` pairs in a given range.
113         pub fn range<R: RangeBounds<K>>(&mut self, range: R) -> Range<K, V> {
114                 self.keys.sort_unstable();
115                 let start = match range.start_bound() {
116                         Bound::Unbounded => 0,
117                         Bound::Included(key) => self.keys.binary_search(key).unwrap_or_else(|index| index),
118                         Bound::Excluded(key) => self.keys.binary_search(key).and_then(|index| Ok(index + 1)).unwrap_or_else(|index| index),
119                 };
120                 let end = match range.end_bound() {
121                         Bound::Unbounded => self.keys.len(),
122                         Bound::Included(key) => self.keys.binary_search(key).and_then(|index| Ok(index + 1)).unwrap_or_else(|index| index),
123                         Bound::Excluded(key) => self.keys.binary_search(key).unwrap_or_else(|index| index),
124                 };
125
126                 Range {
127                         inner_range: self.keys[start..end].iter(),
128                         map: &self.map,
129                 }
130         }
131
132         /// Returns the number of `key`/`value` pairs in the map
133         pub fn len(&self) -> usize {
134                 self.map.len()
135         }
136
137         /// Returns true if there are no elements in the map
138         pub fn is_empty(&self) -> bool {
139                 self.map.is_empty()
140         }
141 }
142
143 impl<K: Hash + Ord + PartialEq, V: PartialEq> PartialEq for IndexedMap<K, V> {
144         fn eq(&self, other: &Self) -> bool {
145                 self.map == other.map
146         }
147 }
148
149 /// An iterator over a range of values in an [`IndexedMap`]
150 pub struct Range<'a, K: Hash + Ord, V> {
151         inner_range: Iter<'a, K>,
152         map: &'a HashMap<K, V>,
153 }
154 impl<'a, K: Hash + Ord, V: 'a> Iterator for Range<'a, K, V> {
155         type Item = (&'a K, &'a V);
156         fn next(&mut self) -> Option<(&'a K, &'a V)> {
157                 self.inner_range.next().map(|k| {
158                         (k, self.map.get(k).expect("map and keys must be consistent"))
159                 })
160         }
161 }
162
163 /// An [`Entry`] for a key which currently has no value
164 pub struct VacantEntry<'a, K: Hash + Ord, V> {
165         #[cfg(feature = "hashbrown")]
166         underlying_entry: hash_map::VacantEntry<'a, K, V, hash_map::DefaultHashBuilder>,
167         #[cfg(not(feature = "hashbrown"))]
168         underlying_entry: hash_map::VacantEntry<'a, K, V>,
169         key: K,
170         keys: &'a mut Vec<K>,
171 }
172
173 /// An [`Entry`] for an existing key-value pair
174 pub struct OccupiedEntry<'a, K: Hash + Ord, V> {
175         #[cfg(feature = "hashbrown")]
176         underlying_entry: hash_map::OccupiedEntry<'a, K, V, hash_map::DefaultHashBuilder>,
177         #[cfg(not(feature = "hashbrown"))]
178         underlying_entry: hash_map::OccupiedEntry<'a, K, V>,
179         keys: &'a mut Vec<K>,
180 }
181
182 /// A mutable reference to a position in the map. This can be used to reference, add, or update the
183 /// value at a fixed key.
184 pub enum Entry<'a, K: Hash + Ord, V> {
185         /// A mutable reference to a position within the map where there is no value.
186         Vacant(VacantEntry<'a, K, V>),
187         /// A mutable reference to a position within the map where there is currently a value.
188         Occupied(OccupiedEntry<'a, K, V>),
189 }
190
191 impl<'a, K: Hash + Ord, V> VacantEntry<'a, K, V> {
192         /// Insert a value into the position described by this entry.
193         pub fn insert(self, value: V) -> &'a mut V {
194                 self.keys.push(self.key);
195                 self.underlying_entry.insert(value)
196         }
197 }
198
199 impl<'a, K: Hash + Ord, V> OccupiedEntry<'a, K, V> {
200         /// Remove the value at the position described by this entry.
201         pub fn remove_entry(self) -> (K, V) {
202                 let res = self.underlying_entry.remove_entry();
203                 let idx = self.keys.iter().position(|k| k == &res.0).expect("map and keys must be consistent");
204                 self.keys.remove(idx);
205                 res
206         }
207
208         /// Get a reference to the value at the position described by this entry.
209         pub fn get(&self) -> &V {
210                 self.underlying_entry.get()
211         }
212
213         /// Get a mutable reference to the value at the position described by this entry.
214         pub fn get_mut(&mut self) -> &mut V {
215                 self.underlying_entry.get_mut()
216         }
217
218         /// Consume this entry, returning a mutable reference to the value at the position described by
219         /// this entry.
220         pub fn into_mut(self) -> &'a mut V {
221                 self.underlying_entry.into_mut()
222         }
223 }