Skip to main content

ruma_state_res/utils/
event_id_map.rs

1//! A map of event IDs to a type `V`.
2
3use std::{
4    borrow::Borrow,
5    collections::{HashMap, hash_map},
6    hash::Hash,
7    iter::FusedIterator,
8    ops::Index,
9};
10
11use ruma_common::EventId;
12
13/// A map of event IDs to a type `V`.
14#[derive(Clone, Debug)]
15pub struct EventIdMap<E: Borrow<EventId>, V>(HashMap<E, V>);
16
17impl<E: Borrow<EventId>, V> EventIdMap<E, V> {
18    /// Create an empty `EventIdMap`.
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    /// Create an empty `EventIdMap` with the given capacity.
24    pub fn with_capacity(capacity: usize) -> Self {
25        Self(HashMap::with_capacity(capacity))
26    }
27
28    /// Clears the map, removing all key-value pairs.
29    pub fn clear(&mut self) {
30        self.0.clear();
31    }
32
33    /// Returns the number of elements in the map.
34    pub fn len(&self) -> usize {
35        self.0.len()
36    }
37
38    /// Returns `true` if the map contains no elements.
39    pub fn is_empty(&self) -> bool {
40        self.0.is_empty()
41    }
42
43    /// Gets an iterator over the entries of the map.
44    pub fn iter(&self) -> EventIdMapIter<'_, E, V> {
45        EventIdMapIter(self.0.iter())
46    }
47
48    /// Gets an iterator over the keys of the map.
49    pub fn keys(&self) -> EventIdMapKeys<'_, E, V> {
50        EventIdMapKeys(self.0.keys())
51    }
52
53    /// Gets an iterator over the keys of the map.
54    pub fn into_keys(self) -> EventIdMapIntoKeys<E, V> {
55        EventIdMapIntoKeys(self.0.into_keys())
56    }
57
58    /// Gets an iterator over the values of the map.
59    pub fn values(&self) -> EventIdMapValues<'_, E, V> {
60        EventIdMapValues(self.0.values())
61    }
62
63    /// Gets an iterator over the values of the map.
64    pub fn into_values(self) -> EventIdMapIntoValues<E, V> {
65        EventIdMapIntoValues(self.0.into_values())
66    }
67}
68
69impl<E, V> EventIdMap<E, V>
70where
71    E: Borrow<EventId> + Eq + Hash,
72{
73    /// Returns `true` if the map contains a value for the specified event ID.
74    pub fn contains_event_id(&self, event_id: &EventId) -> bool {
75        self.0.contains_key(event_id)
76    }
77
78    /// Returns a reference to the value corresponding to given event ID.
79    pub fn get(&self, event_id: &EventId) -> Option<&V> {
80        self.0.get(event_id)
81    }
82
83    /// Returns a mutable reference to the value corresponding to given event ID.
84    pub fn get_mut(&mut self, event_id: &EventId) -> Option<&mut V> {
85        self.0.get_mut(event_id)
86    }
87
88    /// Returns the key-value pair corresponding to the supplied event ID.
89    pub fn get_key_value(&self, event_id: &EventId) -> Option<(&E, &V)> {
90        self.0.get_key_value(event_id)
91    }
92
93    /// Gets the given event ID's corresponding entry in the map for in-place manipulation.
94    pub fn entry(&mut self, event_id: E) -> EventIdMapEntry<'_, E, V> {
95        EventIdMapEntry(self.0.entry(event_id))
96    }
97
98    /// Inserts a key-value pair into the map.
99    ///
100    /// If the map did not have this event ID present, `None` is returned.
101    ///
102    /// If the map did have this event ID present, the value is updated, and the old value is
103    /// returned.
104    pub fn insert(&mut self, event_id: E, value: V) -> Option<V> {
105        self.0.insert(event_id, value)
106    }
107
108    /// Removes an event ID from the map, returning the value at the event ID if the event ID was
109    /// previously in the map.
110    pub fn remove(&mut self, event_id: &EventId) -> Option<V> {
111        self.0.remove(event_id)
112    }
113
114    /// Removes an event ID from the map, returning the stored event ID and value if the event ID
115    /// was previously in the map.
116    pub fn remove_entry(&mut self, event_id: &EventId) -> Option<(E, V)> {
117        self.0.remove_entry(event_id)
118    }
119}
120
121impl<E: Borrow<EventId>, V> Default for EventIdMap<E, V> {
122    fn default() -> Self {
123        Self(Default::default())
124    }
125}
126
127impl<E, V> Index<&EventId> for EventIdMap<E, V>
128where
129    E: Borrow<EventId> + Hash + Eq,
130{
131    type Output = V;
132
133    fn index(&self, event_id: &EventId) -> &Self::Output {
134        &self.0[event_id]
135    }
136}
137
138impl<E, V, const N: usize> From<[(E, V); N]> for EventIdMap<E, V>
139where
140    E: Borrow<EventId> + Hash + Eq,
141{
142    fn from(value: [(E, V); N]) -> Self {
143        Self(value.into())
144    }
145}
146
147impl<E, V> Extend<(E, V)> for EventIdMap<E, V>
148where
149    E: Borrow<EventId> + Hash + Eq,
150{
151    fn extend<T: IntoIterator<Item = (E, V)>>(&mut self, iter: T) {
152        self.0.extend(iter);
153    }
154}
155
156impl<E, V> FromIterator<(E, V)> for EventIdMap<E, V>
157where
158    E: Borrow<EventId> + Hash + Eq,
159{
160    fn from_iter<T: IntoIterator<Item = (E, V)>>(iter: T) -> Self {
161        Self(HashMap::from_iter(iter))
162    }
163}
164
165impl<E: Borrow<EventId>, V> IntoIterator for EventIdMap<E, V> {
166    type Item = (E, V);
167    type IntoIter = EventIdMapIntoIter<E, V>;
168
169    fn into_iter(self) -> Self::IntoIter {
170        EventIdMapIntoIter(self.0.into_iter())
171    }
172}
173
174impl<'a, E: Borrow<EventId>, V> IntoIterator for &'a EventIdMap<E, V> {
175    type Item = (&'a E, &'a V);
176    type IntoIter = EventIdMapIter<'a, E, V>;
177
178    fn into_iter(self) -> Self::IntoIter {
179        self.iter()
180    }
181}
182
183/// An iterator over the entries of an [`EventIdMap`].
184#[derive(Clone, Debug)]
185pub struct EventIdMapIter<'a, E, V>(hash_map::Iter<'a, E, V>);
186
187impl<'a, E, V> Iterator for EventIdMapIter<'a, E, V> {
188    type Item = (&'a E, &'a V);
189
190    fn next(&mut self) -> Option<Self::Item> {
191        self.0.next()
192    }
193
194    fn size_hint(&self) -> (usize, Option<usize>) {
195        self.0.size_hint()
196    }
197
198    fn count(self) -> usize {
199        self.0.len()
200    }
201
202    fn fold<B, F>(self, init: B, f: F) -> B
203    where
204        Self: Sized,
205        F: FnMut(B, Self::Item) -> B,
206    {
207        self.0.fold(init, f)
208    }
209}
210
211impl<'a, E, V> ExactSizeIterator for EventIdMapIter<'a, E, V> {}
212
213impl<'a, E, V> FusedIterator for EventIdMapIter<'a, E, V> {}
214
215/// An iterator over the entries of an [`EventIdMap`].
216#[derive(Debug)]
217pub struct EventIdMapIntoIter<E, V>(hash_map::IntoIter<E, V>);
218
219impl<E, V> Iterator for EventIdMapIntoIter<E, V> {
220    type Item = (E, V);
221
222    fn next(&mut self) -> Option<Self::Item> {
223        self.0.next()
224    }
225
226    fn size_hint(&self) -> (usize, Option<usize>) {
227        self.0.size_hint()
228    }
229
230    fn count(self) -> usize {
231        self.0.len()
232    }
233
234    fn fold<B, F>(self, init: B, f: F) -> B
235    where
236        Self: Sized,
237        F: FnMut(B, Self::Item) -> B,
238    {
239        self.0.fold(init, f)
240    }
241}
242
243impl<E, V> ExactSizeIterator for EventIdMapIntoIter<E, V> {}
244
245impl<E, V> FusedIterator for EventIdMapIntoIter<E, V> {}
246
247/// An iterator over the keys of an [`EventIdMap`].
248#[derive(Clone, Debug)]
249pub struct EventIdMapKeys<'a, E, V>(hash_map::Keys<'a, E, V>);
250
251impl<'a, E, V> Iterator for EventIdMapKeys<'a, E, V> {
252    type Item = &'a E;
253
254    fn next(&mut self) -> Option<Self::Item> {
255        self.0.next()
256    }
257
258    fn size_hint(&self) -> (usize, Option<usize>) {
259        self.0.size_hint()
260    }
261
262    fn count(self) -> usize {
263        self.0.len()
264    }
265
266    fn fold<B, F>(self, init: B, f: F) -> B
267    where
268        Self: Sized,
269        F: FnMut(B, Self::Item) -> B,
270    {
271        self.0.fold(init, f)
272    }
273}
274
275impl<'a, E, V> ExactSizeIterator for EventIdMapKeys<'a, E, V> {}
276
277impl<'a, E, V> FusedIterator for EventIdMapKeys<'a, E, V> {}
278
279/// An iterator over the keys of an [`EventIdMap`].
280#[derive(Debug)]
281pub struct EventIdMapIntoKeys<E, V>(hash_map::IntoKeys<E, V>);
282
283impl<E, V> Iterator for EventIdMapIntoKeys<E, V> {
284    type Item = E;
285
286    fn next(&mut self) -> Option<Self::Item> {
287        self.0.next()
288    }
289
290    fn size_hint(&self) -> (usize, Option<usize>) {
291        self.0.size_hint()
292    }
293
294    fn count(self) -> usize {
295        self.0.len()
296    }
297
298    fn fold<B, F>(self, init: B, f: F) -> B
299    where
300        Self: Sized,
301        F: FnMut(B, Self::Item) -> B,
302    {
303        self.0.fold(init, f)
304    }
305}
306
307impl<E, V> ExactSizeIterator for EventIdMapIntoKeys<E, V> {}
308
309impl<E, V> FusedIterator for EventIdMapIntoKeys<E, V> {}
310
311/// An iterator over the values of an [`EventIdMap`].
312#[derive(Clone, Debug)]
313pub struct EventIdMapValues<'a, E, V>(hash_map::Values<'a, E, V>);
314
315impl<'a, E, V> Iterator for EventIdMapValues<'a, E, V> {
316    type Item = &'a V;
317
318    fn next(&mut self) -> Option<Self::Item> {
319        self.0.next()
320    }
321
322    fn size_hint(&self) -> (usize, Option<usize>) {
323        self.0.size_hint()
324    }
325
326    fn count(self) -> usize {
327        self.0.len()
328    }
329
330    fn fold<B, F>(self, init: B, f: F) -> B
331    where
332        Self: Sized,
333        F: FnMut(B, Self::Item) -> B,
334    {
335        self.0.fold(init, f)
336    }
337}
338
339impl<'a, E, V> ExactSizeIterator for EventIdMapValues<'a, E, V> {}
340
341impl<'a, E, V> FusedIterator for EventIdMapValues<'a, E, V> {}
342
343/// An iterator over the values of an [`EventIdMap`].
344#[derive(Debug)]
345pub struct EventIdMapIntoValues<E, V>(hash_map::IntoValues<E, V>);
346
347impl<E, V> Iterator for EventIdMapIntoValues<E, V> {
348    type Item = V;
349
350    fn next(&mut self) -> Option<Self::Item> {
351        self.0.next()
352    }
353
354    fn size_hint(&self) -> (usize, Option<usize>) {
355        self.0.size_hint()
356    }
357
358    fn count(self) -> usize {
359        self.0.len()
360    }
361
362    fn fold<B, F>(self, init: B, f: F) -> B
363    where
364        Self: Sized,
365        F: FnMut(B, Self::Item) -> B,
366    {
367        self.0.fold(init, f)
368    }
369}
370
371impl<E, V> ExactSizeIterator for EventIdMapIntoValues<E, V> {}
372
373impl<E, V> FusedIterator for EventIdMapIntoValues<E, V> {}
374
375/// A view into a single entry in an [`EventIdMap`].
376#[derive(Debug)]
377pub struct EventIdMapEntry<'a, E: Borrow<EventId>, V>(hash_map::Entry<'a, E, V>);
378
379impl<'a, E: Borrow<EventId>, V> EventIdMapEntry<'a, E, V> {
380    /// Ensures a value is in the entry by inserting the default if empty, and returns a mutable
381    /// reference to the value in the entry.
382    pub fn or_insert(self, default: V) -> &'a mut V {
383        self.0.or_insert(default)
384    }
385
386    /// Ensures a value is in the entry by inserting the result of the default function if empty,
387    /// and returns a mutable reference to the value in the entry.
388    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
389        self.0.or_insert_with(default)
390    }
391
392    /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
393    ///
394    /// This method allows for generating key-derived values for insertion by providing the default
395    /// function a reference to the key that was moved during the .entry(key) method call.
396    pub fn or_insert_with_key<F: FnOnce(&E) -> V>(self, default: F) -> &'a mut V {
397        self.0.or_insert_with_key(default)
398    }
399
400    /// Sets the value of the entry, and returns a mutable reference to the value.
401    pub fn insert_entry(self, value: V) -> &'a mut V {
402        self.0.insert_entry(value).into_mut()
403    }
404}
405
406impl<'a, E: Borrow<EventId>, V: Default> EventIdMapEntry<'a, E, V> {
407    /// Ensures a value is in the entry by inserting the default value if empty, and returns a
408    /// mutable reference to the value in the entry.
409    pub fn or_default(self) -> &'a mut V {
410        self.0.or_default()
411    }
412}