Skip to main content

wt_indexset/concurrent/
multimap.rs

1use std::fmt::Debug;
2use std::sync::Arc;
3use std::{borrow::Borrow, iter::FusedIterator, ops::RangeBounds};
4
5use parking_lot::Mutex;
6
7use crate::core::node::NodeLike;
8use crate::{cdc::change::ChangeEvent, core::multipair::MultiPair};
9
10use super::set::BTreeSet;
11
12#[derive(Debug)]
13pub struct BTreeMultiMap<K, V, Node = Vec<MultiPair<K, V>>>
14where
15    K: Debug + Send + Ord + Clone + 'static,
16    V: Debug + Send + Clone + PartialEq + 'static,
17    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
18{
19    pub(crate) set: BTreeSet<MultiPair<K, V>, Node>,
20}
21
22impl<K, V, Node> Default for BTreeMultiMap<K, V, Node>
23where
24    K: Debug + Send + Ord + Clone + 'static,
25    V: Debug + Send + Clone + PartialEq + 'static,
26    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
27{
28    fn default() -> Self {
29        Self {
30            set: Default::default(),
31        }
32    }
33}
34
35pub struct Iter<'a, K, V, Node>
36where
37    K: Debug + Send + Ord + Clone + 'static,
38    V: Debug + Send + Clone + PartialEq + 'static,
39    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
40{
41    inner: super::set::Iter<'a, MultiPair<K, V>, Node>,
42}
43
44impl<'a, K, V, Node> Iterator for Iter<'a, K, V, Node>
45where
46    K: Debug + Send + Ord + Clone + 'static,
47    V: Debug + Send + Clone + PartialEq + 'static,
48    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
49{
50    type Item = (&'a K, &'a V);
51
52    fn next(&mut self) -> Option<Self::Item> {
53        if let Some(entry) = self.inner.next() {
54            return Some((&entry.key, &entry.value));
55        }
56
57        None
58    }
59}
60
61impl<'a, K, V, Node> DoubleEndedIterator for Iter<'a, K, V, Node>
62where
63    K: Debug + Send + Ord + Clone + 'static,
64    V: Debug + Send + Clone + PartialEq + 'static,
65    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
66{
67    fn next_back(&mut self) -> Option<Self::Item> {
68        if let Some(entry) = self.inner.next_back() {
69            return Some((&entry.key, &entry.value));
70        }
71
72        None
73    }
74}
75
76impl<'a, K, V, Node> FusedIterator for Iter<'a, K, V, Node>
77where
78    K: Debug + Send + Ord + Clone + 'static,
79    V: Debug + Send + Clone + PartialEq + 'static,
80    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
81{
82}
83
84pub struct RawRange<'a, K, V, Node>
85where
86    K: Debug + Send + Ord + Clone + 'static,
87    V: Debug + Send + Clone + PartialEq + 'static,
88    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
89{
90    inner: super::set::Range<'a, MultiPair<K, V>, Node>,
91}
92
93impl<'a, K, V, Node> Iterator for RawRange<'a, K, V, Node>
94where
95    K: Debug + Send + Ord + Clone + 'static,
96    V: Debug + Send + Clone + PartialEq + 'static,
97    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
98{
99    type Item = (&'a K, &'a u64, &'a V);
100
101    fn next(&mut self) -> Option<Self::Item> {
102        if let Some(entry) = self.inner.next() {
103            return Some((&entry.key, &entry.discriminator, &entry.value));
104        }
105
106        None
107    }
108}
109
110impl<'a, K, V, Node> DoubleEndedIterator for RawRange<'a, K, V, Node>
111where
112    K: Debug + Send + Ord + Clone + 'static,
113    V: Debug + Send + Clone + PartialEq + 'static,
114    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
115{
116    fn next_back(&mut self) -> Option<Self::Item> {
117        if let Some(entry) = self.inner.next_back() {
118            return Some((&entry.key, &entry.discriminator, &entry.value));
119        }
120
121        None
122    }
123}
124
125impl<'a, K, V, Node> FusedIterator for RawRange<'a, K, V, Node>
126where
127    K: Debug + Send + Ord + Clone + 'static,
128    V: Debug + Send + Clone + PartialEq + 'static,
129    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
130{
131}
132
133pub struct Range<'a, K, V, Node>
134where
135    K: Debug + Send + Ord + Clone + 'static,
136    V: Debug + Send + Clone + PartialEq + 'static,
137    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
138{
139    inner: RawRange<'a, K, V, Node>,
140}
141
142impl<'a, K, V, Node> Iterator for Range<'a, K, V, Node>
143where
144    K: Debug + Send + Ord + Clone + 'static,
145    V: Debug + Send + Clone + PartialEq + 'static,
146    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
147{
148    type Item = (&'a K, &'a V);
149
150    fn next(&mut self) -> Option<Self::Item> {
151        if let Some(raw_entry) = self.inner.next() {
152            return Some((&raw_entry.0, &raw_entry.2));
153        }
154
155        None
156    }
157}
158
159impl<'a, K, V, Node> DoubleEndedIterator for Range<'a, K, V, Node>
160where
161    K: Debug + Send + Ord + Clone + 'static,
162    V: Debug + Send + Clone + PartialEq + 'static,
163    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
164{
165    fn next_back(&mut self) -> Option<Self::Item> {
166        if let Some(raw_entry) = self.inner.next_back() {
167            return Some((&raw_entry.0, &raw_entry.2));
168        }
169
170        None
171    }
172}
173
174impl<'a, K, V, Node> FusedIterator for Range<'a, K, V, Node>
175where
176    K: Debug + Send + Ord + Clone + 'static,
177    V: Debug + Send + Clone + PartialEq + 'static,
178    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
179{
180}
181
182impl<K, V, Node> BTreeMultiMap<K, V, Node>
183where
184    K: Debug + Send + Ord + Clone + 'static,
185    V: Debug + Send + Clone + PartialEq + 'static,
186    Node: NodeLike<MultiPair<K, V>> + Send + 'static,
187{
188    /// Makes a new, empty, persistent `BTreeMultiMap`.
189    ///
190    /// # Examples
191    ///
192    /// Basic usage:
193    ///
194    /// ```
195    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
196    ///
197    /// let mut map = BTreeMultiMap::<usize, &str>::new();
198    ///
199    /// // entries can now be inserted into the empty map
200    /// map.insert(1, "a");
201    /// ```
202    pub fn new() -> Self {
203        Self {
204            set: Default::default(),
205        }
206    }
207    /// Makes a new, empty `BTreeMultiMap` with the given maximum node size. Allocates one vec with
208    /// the capacity set to be the specified node size.
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
214    ///
215    /// let map = BTreeMultiMap::<i32, i32>::with_maximum_node_size(128);
216    pub fn with_maximum_node_size(node_capacity: usize) -> Self {
217        Self {
218            set: BTreeSet::with_maximum_node_size(node_capacity),
219        }
220    }
221    /// Adds full [`Node`] to this multiset. [`Node`] should be correct node with
222    /// values sorted.
223    #[cfg(feature = "cdc")]
224    pub fn attach_multi_node(&self, node: Node) {
225        self.set.attach_node(node)
226    }
227    /// Returns iterator over this multiset's [`Node`]'s.
228    #[cfg(feature = "cdc")]
229    pub fn iter_nodes(&self) -> impl Iterator<Item = Arc<Mutex<Node>>> + '_ {
230        self.set.index.iter().map(|e| e.value().clone())
231    }
232    /// Returns `true` if the map contains at least one occurance of the specified key.
233    ///
234    /// The key may be any borrowed form of the map's key type, but the ordering
235    /// on the borrowed form *must* match the ordering on the key type.
236    ///
237    /// # Examples
238    ///
239    /// Basic usage:
240    ///
241    /// ```
242    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
243    ///
244    /// let mut map = BTreeMultiMap::<usize, &str>::new();
245    /// map.insert(1, "a");
246    /// map.insert(1, "b");
247    /// assert_eq!(map.contains_key(&1), true);
248    /// assert_eq!(map.contains_key(&2), false);
249    /// ```
250    pub fn contains_key<Q>(&self, key: &Q) -> bool
251    where
252        MultiPair<K, V>: Borrow<Q> + Ord,
253        Q: Ord + ?Sized,
254    {
255        self.set.contains(key)
256    }
257    fn _range<Q, R>(&self, range: R) -> Range<'_, K, V, Node>
258    where
259        MultiPair<K, V>: Borrow<Q> + Ord,
260        Q: Ord + ?Sized,
261        R: RangeBounds<Q>,
262    {
263        Range {
264            inner: RawRange {
265                inner: super::set::BTreeSet::range(&self.set, range),
266            },
267        }
268    }
269    fn raw_get(&self, key: &K) -> RawRange<'_, K, V, Node> {
270        let infimum = MultiPair::with_infimum(key.clone());
271        let supremum = MultiPair::with_supremum(key.clone());
272
273        RawRange {
274            inner: self.set.range(infimum..supremum),
275        }
276    }
277    /// Constructs a double-ended iterator over all key value pairs with the given key in the map.
278    ///
279    /// ```
280    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
281    /// use wt_indexset::BTreeSet;
282    ///
283    /// let mut map = BTreeMultiMap::<usize, &str>::new();
284    ///
285    /// map.insert(1, "b");
286    /// map.insert(1, "a");
287    /// map.insert(2, "c");
288    ///
289    /// let all_with_key = map.get(&1).collect::<BTreeSet<_>>();
290    /// assert_eq!(all_with_key.len(), 2);
291    /// assert_eq!(all_with_key, vec![(&1, &"a"), (&1, &"b")].into_iter().collect::<BTreeSet<_>>());
292    /// ```
293    pub fn get(&self, key: &K) -> Range<'_, K, V, Node> {
294        let infimum = MultiPair::with_infimum(key.clone());
295        let supremum = MultiPair::with_supremum(key.clone());
296
297        Range {
298            inner: RawRange {
299                inner: self.set.range(infimum..supremum),
300            },
301        }
302    }
303    /// Inserts a key-value pair into the multi map.
304    ///
305    /// # Examples
306    ///
307    /// Basic usage:
308    ///
309    /// ```
310    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
311    ///
312    /// let mut map = BTreeMultiMap::<usize, &str>::new();
313    /// assert_eq!(map.insert(37, "a"), None);
314    /// assert_eq!(map.len() == 0, false);
315    ///
316    /// map.insert(37, "b");
317    /// assert_eq!(map.insert(37, "c"), None);
318    /// ```
319    pub fn insert(&self, key: K, value: V) -> Option<V> {
320        let new_entry = MultiPair::new(key, value);
321
322        self.set
323            .put_cdc(new_entry)
324            .0
325            .and_then(|pair| Some(pair.value))
326    }
327    /// Inserts a key-value pair into the map and returns old value (if it was
328    /// already in set) with [`ChangeEvent`]'s that describes this insert
329    /// action.
330    #[cfg(feature = "cdc")]
331    pub fn insert_cdc(&self, key: K, value: V) -> (Option<V>, Vec<ChangeEvent<MultiPair<K, V>>>) {
332        let new_entry = MultiPair::new(key, value);
333
334        let (old_value, cdc) = self.set.put_cdc(new_entry);
335
336        (old_value.and_then(|pair| Some(pair.value)), cdc)
337    }
338    /// Removes some key from the map that matches the given key, returning the
339    /// key and the value if the key was previously in the map.
340    ///
341    /// The key may be any borrowed form of the map's key type, but the ordering
342    /// on the borrowed form *must* match the ordering on the key type.
343    ///
344    /// # Examples
345    ///
346    /// Basic usage:
347    ///
348    /// ```
349    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
350    ///
351    /// let map = BTreeMultiMap::<usize, &str>::new();
352    /// map.insert(1, "b");
353    /// map.insert(1, "a");
354    ///
355    /// let first_removed = map.remove_some(&1).unwrap();
356    /// let second_removed = map.remove_some(&1).unwrap();
357    /// let removals = vec![first_removed, second_removed];
358    ///
359    /// assert!(removals.contains(&(1, "a")));
360    /// assert!(removals.contains(&(1, "b")));
361    /// ```
362    pub fn remove_some<Q>(&self, key: &Q) -> Option<(K, V)>
363    where
364        MultiPair<K, V>: Borrow<Q> + Ord,
365        Q: Ord + ?Sized,
366    {
367        self.set
368            .remove(key)
369            .and_then(|pair| Some((pair.key, pair.value)))
370    }
371    /// Removes some key from the map that matches the given key, returning the
372    /// key and the value if the key was previously in the map with
373    /// [`ChangeEvent`]'s describing this `remove_some` action.
374    #[cfg(feature = "cdc")]
375    pub fn remove_some_cdc<Q>(&self, key: &Q) -> (Option<(K, V)>, Vec<ChangeEvent<MultiPair<K, V>>>)
376    where
377        MultiPair<K, V>: Borrow<Q> + Ord,
378        Q: Ord + ?Sized,
379    {
380        let (old_value, cdc) = self.set.remove_cdc(key);
381
382        (old_value.and_then(|pair| Some((pair.key, pair.value))), cdc)
383    }
384    /// Removes a specific key-value pair from the map returning the key and the value if the key
385    /// was previously in the map.
386    ///
387    /// # Examples
388    ///
389    /// Basic usage:
390    ///
391    /// ```
392    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
393    ///
394    /// let map = BTreeMultiMap::<usize, &str>::new();
395    /// map.insert(1, "b");
396    /// map.insert(1, "a");
397    ///
398    /// assert_eq!(map.remove(&1, &"a"), Some((1, "a")));
399    /// assert_eq!(map.remove(&1, &"b"), Some((1, "b")));
400    /// ```
401    pub fn remove(&self, key: &K, value: &V) -> Option<(K, V)> {
402        let discriminant_to_remove = self.raw_get(&key).find(|pair| pair.2 == value);
403        if let Some(discriminant_to_remove) = discriminant_to_remove {
404            let pair_to_remove = MultiPair {
405                key: discriminant_to_remove.0.clone(),
406                value: discriminant_to_remove.2.clone(),
407                discriminator: *discriminant_to_remove.1,
408            };
409
410            return self
411                .set
412                .remove(&pair_to_remove)
413                .and_then(|pair| Some((pair.key, pair.value)));
414        }
415
416        None
417    }
418    /// Removes a specific key-value pair from the map returning the key and the
419    /// value if the key was previously in the map with [`ChangeEvent`]'s
420    /// describing this `remove_some` action.
421    #[cfg(feature = "cdc")]
422    pub fn remove_cdc(
423        &self,
424        key: &K,
425        value: &V,
426    ) -> (Option<(K, V)>, Vec<ChangeEvent<MultiPair<K, V>>>) {
427        let discriminant_to_remove = self.raw_get(&key).find(|pair| pair.2 == value);
428        if let Some(discriminant_to_remove) = discriminant_to_remove {
429            let pair_to_remove = MultiPair {
430                key: discriminant_to_remove.0.clone(),
431                value: discriminant_to_remove.2.clone(),
432                discriminator: *discriminant_to_remove.1,
433            };
434
435            let (res, evs) = self.set.remove_cdc(&pair_to_remove);
436            return (res.map(|pair| (pair.key, pair.value)), evs);
437        }
438
439        (None, vec![])
440    }
441    /// Returns the number of elements in the map.
442    ///
443    /// # Examples
444    ///
445    /// Basic usage:
446    ///
447    /// ```
448    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
449    ///
450    /// let mut a = BTreeMultiMap::<usize, &str>::new();
451    /// assert_eq!(a.len(), 0);
452    /// a.insert(1, "a");
453    /// assert_eq!(a.len(), 1);
454    /// ```
455    pub fn len(&self) -> usize {
456        self.set.len()
457    }
458    /// Returns the total number of allocated slots across all internal nodes.
459    ///
460    /// This represents the number of key-value pairs the multimap can hold
461    /// without reallocating memory in its internal vectors.
462    ///
463    /// # Examples
464    ///
465    /// Basic usage:
466    ///
467    /// ```
468    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
469    ///
470    /// let mut a = BTreeMultiMap::<usize, &str>::with_maximum_node_size(8);
471    ///
472    /// a.insert(1, "a");
473    /// a.insert(1, "b");
474    ///
475    /// // Capacity remains unchanged until reallocation occurs
476    /// assert_eq!(a.capacity(), 8);
477    /// ```
478    pub fn capacity(&self) -> usize {
479        self.set.capacity()
480    }
481    /// Returns the total number of nodes.
482    ///
483    ///
484    /// # Examples
485    ///
486    /// Basic usage:
487    ///
488    /// ```
489    /// use wt_indexset::concurrent::map::BTreeMap;
490    ///
491    /// let mut a = BTreeMap::<usize, &str>::with_maximum_node_size(16);
492    ///
493    /// a.insert(1, "a");
494    /// a.insert(2, "b");
495    ///
496    /// assert_eq!(a.node_count(), 1);
497    /// ```
498    pub fn node_count(&self) -> usize {
499        self.set.node_count()
500    }
501    /// Gets an iterator over the entries of the map, sorted by key.
502    ///
503    /// # Examples
504    ///
505    /// Basic usage:
506    ///
507    /// ```
508    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
509    ///
510    /// let mut map = BTreeMultiMap::<usize, &str>::new();
511    /// map.insert(3, "c");
512    /// map.insert(2, "b");
513    /// map.insert(1, "a");
514    ///
515    /// for (key, value) in map.iter() {
516    ///     println!("{key}: {value}");
517    /// }
518    ///
519    /// let (first_key, first_value) = map.iter().next().unwrap();
520    /// assert_eq!((*first_key, *first_value), (1, "a"));
521    /// ```
522    pub fn iter(&self) -> Iter<'_, K, V, Node> {
523        Iter {
524            inner: self.set.iter(),
525        }
526    }
527    /// Constructs a double-ended iterator over a sub-range of elements in the map.
528    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
529    /// yield elements from min (inclusive) to max (exclusive).
530    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
531    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
532    /// range from 4 to 10.
533    ///
534    /// # Panics
535    ///
536    /// Panics if range `start > end`.
537    /// Panics if range `start == end` and both bounds are `Excluded`.
538    ///
539    /// # Examples
540    ///
541    /// Basic usage:
542    ///
543    /// ```
544    /// use wt_indexset::concurrent::multimap::BTreeMultiMap;
545    /// use std::ops::Bound::Included;
546    ///
547    /// let mut map = BTreeMultiMap::<usize, &str>::new();
548    /// map.insert(3, "a");
549    /// map.insert(5, "b");
550    /// map.insert(8, "c");
551    /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
552    ///     println!("{key}: {value}");
553    /// }
554    /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
555    /// ```
556    pub fn range<R>(&self, range: R) -> Range<'_, K, V, Node>
557    where
558        R: RangeBounds<K>,
559    {
560        let start_bound = range.start_bound();
561        let adjusted_start_bound = match start_bound {
562            std::ops::Bound::Included(start) => {
563                std::ops::Bound::Included(MultiPair::with_infimum(start.clone()))
564            }
565            std::ops::Bound::Excluded(start) => {
566                std::ops::Bound::Excluded(MultiPair::with_supremum(start.clone()))
567            }
568            _ => std::ops::Bound::Unbounded,
569        };
570        let end_bound = range.end_bound();
571        let adjusted_end_bound = match end_bound {
572            std::ops::Bound::Included(end) => {
573                std::ops::Bound::Included(MultiPair::with_supremum(end.clone()))
574            }
575            std::ops::Bound::Excluded(end) => {
576                std::ops::Bound::Excluded(MultiPair::with_infimum(end.clone()))
577            }
578            _ => std::ops::Bound::Unbounded,
579        };
580
581        self._range((adjusted_start_bound, adjusted_end_bound))
582    }
583}
584
585#[cfg(test)]
586mod tests {
587    use super::BTreeMultiMap;
588    use crate::BTreeSet;
589
590    #[test]
591    fn test_insert_works_as_expected() {
592        let maximum_node_size = 3;
593        let multi_map = BTreeMultiMap::<usize, &str>::with_maximum_node_size(maximum_node_size);
594
595        multi_map.insert(1usize, "a");
596        multi_map.insert(1usize, "b");
597        multi_map.insert(2usize, "c");
598        multi_map.insert(2usize, "d");
599        multi_map.insert(3usize, "e");
600        multi_map.insert(4usize, "f");
601        multi_map.insert(4usize, "g");
602
603        let expected_pairs = vec![
604            (&1, &"b"),
605            (&1, &"a"),
606            (&2, &"d"),
607            (&2, &"c"),
608            (&3, &"e"),
609            (&4, &"f"),
610            (&4, &"g"),
611        ]
612        .into_iter()
613        .collect::<BTreeSet<_>>();
614
615        let all_pairs = multi_map.iter().collect::<BTreeSet<_>>();
616        assert_eq!(all_pairs, expected_pairs);
617    }
618
619    #[test]
620    fn test_insert_all_same_key_works_as_expected() {
621        let maximum_node_size = 3;
622        let map = BTreeMultiMap::<usize, &str>::with_maximum_node_size(maximum_node_size);
623
624        map.insert(1usize, "a");
625        map.insert(1usize, "b");
626        map.insert(1usize, "c");
627        map.insert(1usize, "d");
628        map.insert(1usize, "e");
629        map.insert(1usize, "f");
630
631        let all_actual_pairs = map.iter().map(|(k, v)| (*k, *v)).collect::<BTreeSet<_>>();
632        let all_expected_pairs = vec![(1, "f"), (1, "e"), (1, "d"), (1, "c"), (1, "b"), (1, "a")]
633            .into_iter()
634            .collect::<BTreeSet<_>>();
635        assert_eq!(all_actual_pairs, all_expected_pairs);
636    }
637
638    #[test]
639    fn test_range_edge_cast() {
640        let maximum_node_size = 3;
641        let map = BTreeMultiMap::<usize, &str>::with_maximum_node_size(maximum_node_size);
642
643        map.insert(1usize, "a");
644        map.insert(1usize, "b");
645        map.insert(2usize, "c");
646        map.insert(2usize, "d");
647        map.insert(3usize, "e");
648        map.insert(4usize, "f");
649        map.insert(4usize, "g");
650
651        let mid_range = map.range(2..3).collect::<BTreeSet<_>>();
652        assert_eq!(
653            mid_range,
654            vec![(&2, &"c"), (&2, &"d"),]
655                .into_iter()
656                .collect::<BTreeSet<_>>()
657        );
658    }
659
660    #[test]
661    fn test_range_works_as_expected() {
662        let maximum_node_size = 3;
663        let map = BTreeMultiMap::<usize, &str>::with_maximum_node_size(maximum_node_size);
664
665        map.insert(1usize, "a");
666        map.insert(1usize, "b");
667        map.insert(2usize, "c");
668        map.insert(2usize, "d");
669        map.insert(3usize, "e");
670        map.insert(4usize, "f");
671        map.insert(4usize, "g");
672
673        let truly_all_pairs = map.iter().collect::<BTreeSet<_>>();
674        let all_pairs = map.range(..).collect::<BTreeSet<_>>();
675        assert_eq!(all_pairs, truly_all_pairs);
676
677        let mid_range = map.range(2..3).collect::<BTreeSet<_>>();
678        assert_eq!(
679            mid_range,
680            vec![(&2, &"c"), (&2, &"d"),]
681                .into_iter()
682                .collect::<BTreeSet<_>>()
683        );
684
685        let reverse_range = map.range(1..4).rev().collect::<BTreeSet<_>>();
686        assert_eq!(
687            reverse_range,
688            vec![(&3, &"e"), (&2, &"d"), (&2, &"c"), (&1, &"b"), (&1, &"a"),]
689                .into_iter()
690                .collect::<BTreeSet<_>>()
691        );
692
693        let empty_range = map.range(5..).collect::<BTreeSet<_>>();
694        assert_eq!(empty_range, vec![].into_iter().collect::<BTreeSet<_>>());
695    }
696
697    #[test]
698    fn test_get_works_as_expected() {
699        let maximum_node_size = 10;
700        let map = BTreeMultiMap::<usize, &str>::with_maximum_node_size(maximum_node_size);
701
702        map.insert(1usize, "a");
703        map.insert(1usize, "b");
704        map.insert(2usize, "c");
705        map.insert(2usize, "d");
706        map.insert(3usize, "e");
707        map.insert(4usize, "f");
708        map.insert(4usize, "g");
709
710        let range = map.get(&1).collect::<BTreeSet<_>>();
711
712        assert_eq!(
713            range,
714            vec![(&1, &"b"), (&1, &"a"),]
715                .into_iter()
716                .collect::<BTreeSet<_>>()
717        );
718
719        let range = map.get(&2).collect::<BTreeSet<_>>();
720        assert_eq!(
721            range,
722            vec![(&2, &"d"), (&2, &"c"),]
723                .into_iter()
724                .collect::<BTreeSet<_>>()
725        );
726
727        let range = map.get(&3).collect::<BTreeSet<_>>();
728        assert_eq!(
729            range,
730            vec![(&3, &"e"),].into_iter().collect::<BTreeSet<_>>()
731        );
732
733        let range = map.get(&4).collect::<BTreeSet<_>>();
734        assert_eq!(
735            range,
736            vec![(&4, &"g"), (&4, &"f"),]
737                .into_iter()
738                .collect::<BTreeSet<_>>()
739        );
740    }
741
742    #[test]
743    fn test_get_works_as_expected_at_big_amounts() {
744        let maximum_node_size = 100;
745        let map = BTreeMultiMap::<String, usize>::with_maximum_node_size(maximum_node_size);
746
747        for i in 1..2000 {
748            map.insert(format!("ValueNum{}", i), i);
749        }
750
751        for i in 1..2000 {
752            let range = map.get(&format!("ValueNum{}", i)).collect::<BTreeSet<_>>();
753            assert_eq!(
754                range,
755                vec![(&format!("ValueNum{}", i), &i),]
756                    .into_iter()
757                    .collect::<BTreeSet<_>>()
758            );
759        }
760    }
761}