nonempty_collections/
index_map.rs

1//! [`NEIndexMap`] is a non-empty variant of [`IndexMap`].
2//!
3//! Unlike `HashMap` and [`crate::NEMap`], these feature a predictable iteration
4//! order.
5
6use std::fmt;
7use std::fmt::Debug;
8use std::fmt::Formatter;
9use std::hash::BuildHasher;
10use std::hash::Hash;
11use std::num::NonZeroUsize;
12
13use indexmap::indexmap;
14use indexmap::Equivalent;
15use indexmap::IndexMap;
16
17use crate::FromNonEmptyIterator;
18use crate::IntoNonEmptyIterator;
19use crate::NonEmptyIterator;
20
21/// Short-hand for constructing [`NEIndexMap`] values.
22///
23/// ```
24/// use nonempty_collections::ne_indexmap;
25///
26/// let m = ne_indexmap! {"elves" => 3000, "orcs" => 10000};
27/// assert_eq!(2, m.len().get());
28/// ```
29#[macro_export]
30macro_rules! ne_indexmap {
31    ($hk:expr => $hv:expr, $( $xk:expr => $xv:expr,)+) => { $crate::ne_indexmap!{$hk => $hv, $($xk => $xv),+} };
32    ($hk:expr => $hv:expr, $( $xk:expr => $xv:expr ),*) => {{
33        const CAP: core::num::NonZeroUsize = core::num::NonZeroUsize::MIN.saturating_add(<[()]>::len(&[$({ stringify!($xk); }),*]));
34        let mut map = $crate::index_map::NEIndexMap::with_capacity(CAP, $hk, $hv);
35        $( map.insert($xk, $xv); )*
36        map
37    }};
38    ($hk:expr => $hv:expr) => {
39        $crate::index_map::NEIndexMap::new($hk, $hv)
40    }
41}
42
43/// A non-empty, growable [`IndexMap`].
44///
45/// Unlike `HashMap` and [`crate::NEMap`], these feature a predictable iteration
46/// order.
47///
48/// ```
49/// use nonempty_collections::*;
50///
51/// let m = ne_indexmap! {"Netherlands" => 18, "Canada" => 40};
52/// assert_eq!(2, m.len().get());
53/// ```
54#[derive(Clone)]
55pub struct NEIndexMap<K, V, S = std::collections::hash_map::RandomState> {
56    inner: IndexMap<K, V, S>,
57}
58
59impl<K, V, S> NEIndexMap<K, V, S> {
60    /// Returns the number of elements the map can hold without reallocating.
61    #[must_use]
62    pub fn capacity(&self) -> NonZeroUsize {
63        unsafe { NonZeroUsize::new_unchecked(self.inner.capacity()) }
64    }
65
66    /// Returns a reference to the map's `BuildHasher`.
67    #[must_use]
68    pub fn hasher(&self) -> &S {
69        self.inner.hasher()
70    }
71
72    /// Returns a regular iterator over the values in this non-empty index map.
73    ///
74    /// For a `NonEmptyIterator` see `Self::nonempty_iter()`.
75    pub fn iter(&self) -> indexmap::map::Iter<'_, K, V> {
76        self.inner.iter()
77    }
78
79    /// An iterator visiting all elements in their order.
80    pub fn nonempty_iter(&self) -> Iter<'_, K, V> {
81        Iter {
82            iter: self.inner.iter(),
83        }
84    }
85
86    /// An iterator visiting all elements in their order.
87    pub fn nonempty_iter_mut(&mut self) -> IterMut<'_, K, V> {
88        IterMut {
89            iter: self.inner.iter_mut(),
90        }
91    }
92
93    /// An iterator visiting all keys in arbitrary order. The iterator element
94    /// type is `&'a K`.
95    ///
96    /// ```
97    /// use nonempty_collections::*;
98    ///
99    /// let m = ne_indexmap! {"Duke" => "Leto", "Doctor" => "Yueh", "Planetologist" => "Kynes"};
100    /// let v = m.keys().collect::<NEVec<_>>();
101    /// assert_eq!(nev![&"Duke", &"Doctor", &"Planetologist"], v);
102    /// ```
103    pub fn keys(&self) -> Keys<'_, K, V> {
104        Keys {
105            inner: self.inner.keys(),
106        }
107    }
108
109    /// Returns the number of elements in the map. Always 1 or more.
110    /// ```
111    /// use nonempty_collections::*;
112    ///
113    /// let m = ne_indexmap! {"a" => 1, "b" => 2};
114    /// assert_eq!(2, m.len().get());
115    /// ```
116    #[must_use]
117    pub fn len(&self) -> NonZeroUsize {
118        unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
119    }
120
121    /// A `NEIndexMap` is never empty.
122    #[deprecated(note = "A NEIndexMap is never empty.")]
123    #[must_use]
124    pub const fn is_empty(&self) -> bool {
125        false
126    }
127
128    /// An iterator visiting all values in order.
129    ///
130    /// ```
131    /// use nonempty_collections::*;
132    ///
133    /// let m = ne_indexmap!["Caladan" => "Atreides", "Giedi Prime" => "Harkonnen", "Kaitain" => "Corrino"];
134    /// assert_eq!(vec![&"Atreides", &"Harkonnen", &"Corrino"], m.values().collect::<Vec<_>>());
135    /// ```
136    pub fn values(&self) -> Values<'_, K, V> {
137        Values {
138            inner: self.inner.values(),
139        }
140    }
141
142    /// Return an iterator visiting all mutable values in order.
143    ///
144    /// ```
145    /// use nonempty_collections::*;
146    ///
147    /// let mut m = ne_indexmap![0 => "Fremen".to_string(), 1 => "Crysknife".to_string(), 2 => "Water of Life".to_string()];
148    /// m.values_mut().into_iter().for_each(|v| v.truncate(3));
149    ///
150    /// assert_eq!(vec![&mut "Fre".to_string(), &mut "Cry".to_string(),&mut "Wat".to_string()], m.values_mut().collect::<Vec<_>>());
151    /// ```
152    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
153        ValuesMut {
154            inner: self.inner.values_mut(),
155        }
156    }
157
158    /// Get the first element. Never fails.
159    #[allow(clippy::missing_panics_doc)] // the invariant of NEIndexMap is that its non-empty
160    #[must_use]
161    pub fn first(&self) -> (&K, &V) {
162        self.inner.first().unwrap()
163    }
164
165    /// Get the last element. Never fails.
166    #[allow(clippy::missing_panics_doc)] // the invariant of NEIndexMap is that its non-empty
167    #[must_use]
168    pub fn last(&self) -> (&K, &V) {
169        self.inner.last().unwrap()
170    }
171}
172
173impl<K: Debug, V: Debug, S> Debug for NEIndexMap<K, V, S> {
174    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
175        f.debug_map().entries(self.nonempty_iter()).finish()
176    }
177}
178
179impl<K, V> NEIndexMap<K, V>
180where
181    K: Eq + Hash,
182{
183    /// Creates a new `NEIndexMap` with a single element.
184    #[must_use]
185    pub fn new(k: K, v: V) -> Self {
186        Self {
187            inner: indexmap! {k => v},
188        }
189    }
190
191    /// Creates a new `NEIndexMap` with a single element and specified
192    /// heap capacity.
193    #[must_use]
194    pub fn with_capacity(capacity: NonZeroUsize, k: K, v: V) -> NEIndexMap<K, V> {
195        let mut inner = IndexMap::with_capacity(capacity.get());
196        inner.insert(k, v);
197        Self { inner }
198    }
199}
200
201impl<K, V, S> NEIndexMap<K, V, S>
202where
203    K: Eq + Hash,
204    S: BuildHasher,
205{
206    /// Attempt a conversion from [`IndexMap`], consuming the given `IndexMap`.
207    /// Will return `None` if the `IndexMap` is empty.
208    ///
209    /// ```
210    /// use indexmap::*;
211    /// use nonempty_collections::*;
212    ///
213    /// assert_eq!(
214    ///     Some(ne_indexmap! {"a" => 1, "b" => 2}),
215    ///     NEIndexMap::try_from_map(indexmap! {"a" => 1, "b" => 2})
216    /// );
217    /// let m: IndexMap<(), ()> = indexmap! {};
218    /// assert_eq!(None, NEIndexMap::try_from_map(m));
219    /// ```
220    #[must_use]
221    pub fn try_from_map(map: IndexMap<K, V, S>) -> Option<Self> {
222        if map.is_empty() {
223            None
224        } else {
225            Some(Self { inner: map })
226        }
227    }
228
229    /// Returns true if the map contains a value.
230    ///
231    /// ```
232    /// use nonempty_collections::*;
233    ///
234    /// let m = ne_indexmap! {"Paul" => ()};
235    /// assert!(m.contains_key("Paul"));
236    /// assert!(!m.contains_key("Atreides"));
237    /// ```
238    #[must_use]
239    pub fn contains_key<Q>(&self, k: &Q) -> bool
240    where
241        Q: Hash + Equivalent<K> + ?Sized,
242    {
243        self.inner.contains_key(k)
244    }
245
246    /// Return a reference to the value stored for `key`, if it is present,
247    /// else `None`.
248    ///
249    /// ```
250    /// use nonempty_collections::*;
251    ///
252    /// let m = ne_indexmap! {"Arrakis" => 3};
253    /// assert_eq!(Some(&3), m.get("Arrakis"));
254    /// assert_eq!(None, m.get("Caladan"));
255    /// ```
256    #[must_use]
257    pub fn get<Q>(&self, k: &Q) -> Option<&V>
258    where
259        Q: Hash + Equivalent<K> + ?Sized,
260    {
261        self.inner.get(k)
262    }
263
264    /// Return references to the key-value pair stored for `key`,
265    /// if it is present, else `None`.
266    ///
267    /// ```
268    /// use nonempty_collections::*;
269    ///
270    /// let m = ne_indexmap! {"Year" => 1963, "Pages" => 896};
271    /// assert_eq!(Some((&"Year", &1963)), m.get_key_value(&"Year"));
272    /// assert_eq!(Some((&"Pages", &896)), m.get_key_value(&"Pages"));
273    /// assert_eq!(None, m.get_key_value(&"Title"));
274    /// ```
275    #[must_use]
276    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
277    where
278        Q: Hash + Equivalent<K> + ?Sized,
279    {
280        self.inner.get_key_value(key)
281    }
282
283    /// Return a mutable reference to the value stored for `key`, if it is
284    /// present, else `None`.
285    ///
286    /// ```
287    /// use nonempty_collections::*;
288    ///
289    /// let mut m = ne_indexmap! {"Mentat" => 3, "Bene Gesserit" => 14};
290    /// let v = m.get_mut(&"Mentat");
291    /// assert_eq!(Some(&mut 3), v);
292    /// *v.unwrap() += 1;
293    /// assert_eq!(Some(&mut 4), m.get_mut(&"Mentat"));
294    ///
295    /// let v = m.get_mut(&"Bene Gesserit");
296    /// assert_eq!(Some(&mut 14), v);
297    /// *v.unwrap() -= 1;
298    /// assert_eq!(Some(&mut 13), m.get_mut(&"Bene Gesserit"));
299    ///
300    /// assert_eq!(None, m.get_mut(&"Sandworm"));
301    /// ```
302    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
303    where
304        Q: Hash + Equivalent<K> + ?Sized,
305    {
306        self.inner.get_mut(key)
307    }
308
309    /// Return item index, if it exists in the map.
310    ///
311    /// ```
312    /// use nonempty_collections::*;
313    /// let m = ne_indexmap! {"Title" => "Dune", "Author" => "Frank Herbert", "Language" => "English"};
314    ///
315    /// assert_eq!(Some(0), m.get_index_of(&"Title"));
316    /// assert_eq!(Some(1), m.get_index_of(&"Author"));
317    /// assert_eq!(None, m.get_index_of(&"Genre"));
318    /// ````
319    #[must_use]
320    pub fn get_index_of<Q>(&self, key: &Q) -> Option<usize>
321    where
322        Q: Hash + Equivalent<K> + ?Sized,
323    {
324        self.inner.get_index_of(key)
325    }
326
327    /// Insert a key-value pair into the map.
328    ///
329    /// If an equivalent key already exists in the map: the key remains and
330    /// retains in its place in the order, its corresponding value is updated
331    /// with `value`, and the older value is returned inside `Some(_)`.
332    ///
333    /// If no equivalent key existed in the map: the new key-value pair is
334    /// inserted, last in order, and `None` is returned.
335    /// ```
336    /// use nonempty_collections::*;
337    ///
338    /// let mut m = ne_indexmap! {"Duke" => "Leto", "Doctor" => "Yueh"};
339    /// assert_eq!(None, m.insert("Lady", "Jessica"));
340    /// assert_eq!(
341    ///     vec!["Duke", "Doctor", "Lady"],
342    ///     m.keys().copied().collect::<Vec<_>>()
343    /// );
344    ///
345    /// // Spoiler alert: there is a different duke at some point
346    /// assert_eq!(Some("Leto"), m.insert("Duke", "Paul"));
347    /// assert_eq!(
348    ///     vec!["Paul", "Yueh", "Jessica"],
349    ///     m.values().copied().collect::<Vec<_>>()
350    /// );
351    /// ```
352    pub fn insert(&mut self, k: K, v: V) -> Option<V> {
353        self.inner.insert(k, v)
354    }
355
356    /// Shrink the capacity of the map as much as possible.
357    pub fn shrink_to_fit(&mut self) {
358        self.inner.shrink_to_fit();
359    }
360
361    /// Creates a new `NEIndexMap` with a single element and specified
362    /// heap capacity and hasher.
363    #[must_use]
364    pub fn with_capacity_and_hasher(
365        capacity: NonZeroUsize,
366        hasher: S,
367        k: K,
368        v: V,
369    ) -> NEIndexMap<K, V, S> {
370        let mut inner = IndexMap::with_capacity_and_hasher(capacity.get(), hasher);
371        inner.insert(k, v);
372        Self { inner }
373    }
374
375    /// See [`IndexMap::with_hasher`].
376    #[must_use]
377    pub fn with_hasher(hasher: S, k: K, v: V) -> NEIndexMap<K, V, S> {
378        let mut inner = IndexMap::with_hasher(hasher);
379        inner.insert(k, v);
380        Self { inner }
381    }
382
383    /// Swaps the position of two key-value pairs in the map.
384    ///
385    /// # Panics
386    /// If `a` or `b` are out of bounds.
387    pub fn swap_indices(&mut self, a: usize, b: usize) {
388        self.inner.swap_indices(a, b);
389    }
390}
391
392impl<K, V, S> PartialEq for NEIndexMap<K, V, S>
393where
394    K: Eq + Hash,
395    V: Eq,
396    S: BuildHasher,
397{
398    fn eq(&self, other: &Self) -> bool {
399        self.inner.eq(&other.inner)
400    }
401}
402
403impl<K, V, S> Eq for NEIndexMap<K, V, S>
404where
405    K: Eq + Hash,
406    V: Eq,
407    S: BuildHasher,
408{
409}
410
411impl<K, V, S> From<NEIndexMap<K, V, S>> for IndexMap<K, V, S>
412where
413    K: Eq + Hash,
414    S: BuildHasher,
415{
416    /// ```
417    /// use indexmap::IndexMap;
418    /// use nonempty_collections::*;
419    ///
420    /// let m: IndexMap<&str, usize> = ne_indexmap! {"population" => 1000}.into();
421    /// assert!(m.contains_key("population"));
422    /// ```
423    fn from(m: NEIndexMap<K, V, S>) -> Self {
424        m.inner
425    }
426}
427
428impl<K, V, S> IntoNonEmptyIterator for NEIndexMap<K, V, S> {
429    type IntoNEIter = IntoIter<K, V>;
430
431    fn into_nonempty_iter(self) -> Self::IntoNEIter {
432        IntoIter {
433            iter: self.inner.into_iter(),
434        }
435    }
436}
437
438impl<'a, K, V, S> IntoNonEmptyIterator for &'a NEIndexMap<K, V, S> {
439    type IntoNEIter = Iter<'a, K, V>;
440
441    fn into_nonempty_iter(self) -> Self::IntoNEIter {
442        self.nonempty_iter()
443    }
444}
445
446impl<K, V, S> IntoIterator for NEIndexMap<K, V, S> {
447    type Item = (K, V);
448
449    type IntoIter = indexmap::map::IntoIter<K, V>;
450
451    fn into_iter(self) -> Self::IntoIter {
452        self.inner.into_iter()
453    }
454}
455
456impl<'a, K, V, S> IntoIterator for &'a NEIndexMap<K, V, S> {
457    type Item = (&'a K, &'a V);
458
459    type IntoIter = indexmap::map::Iter<'a, K, V>;
460
461    fn into_iter(self) -> Self::IntoIter {
462        self.iter()
463    }
464}
465
466/// ```
467/// use nonempty_collections::*;
468///
469/// let v = nev![('a', 1), ('b', 2), ('c', 3), ('a', 4)];
470/// let m0 = v.into_nonempty_iter().collect::<NEIndexMap<_, _>>();
471/// let m1 = ne_indexmap! {'a' => 4, 'b' => 2, 'c' => 3};
472/// assert_eq!(m0, m1);
473/// ```
474impl<K, V, S> FromNonEmptyIterator<(K, V)> for NEIndexMap<K, V, S>
475where
476    K: Eq + Hash,
477    S: BuildHasher + Default,
478{
479    fn from_nonempty_iter<I>(iter: I) -> Self
480    where
481        I: IntoNonEmptyIterator<Item = (K, V)>,
482    {
483        Self {
484            inner: iter.into_nonempty_iter().into_iter().collect(),
485        }
486    }
487}
488
489impl<K, V> std::ops::Index<usize> for NEIndexMap<K, V> {
490    type Output = V;
491
492    fn index(&self, index: usize) -> &V {
493        self.inner.index(index)
494    }
495}
496
497/// A non-empty iterator over the entries of an [`NEIndexMap`].
498#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
499pub struct Iter<'a, K: 'a, V: 'a> {
500    iter: indexmap::map::Iter<'a, K, V>,
501}
502
503impl<K, V> NonEmptyIterator for Iter<'_, K, V> {}
504
505impl<'a, K, V> IntoIterator for Iter<'a, K, V> {
506    type Item = (&'a K, &'a V);
507
508    type IntoIter = indexmap::map::Iter<'a, K, V>;
509
510    fn into_iter(self) -> Self::IntoIter {
511        self.iter
512    }
513}
514
515// FIXME: Remove in favor of `#[derive(Clone)]` (see https://github.com/rust-lang/rust/issues/26925 for more info)
516impl<K, V> Clone for Iter<'_, K, V> {
517    fn clone(&self) -> Self {
518        Iter {
519            iter: self.iter.clone(),
520        }
521    }
522}
523
524impl<K: Debug, V: Debug> Debug for Iter<'_, K, V> {
525    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
526        f.debug_list().entries(self.clone()).finish()
527    }
528}
529
530/// A mutable non-empty iterator over the entries of an [`NEIndexMap`].
531#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
532pub struct IterMut<'a, K: 'a, V: 'a> {
533    iter: indexmap::map::IterMut<'a, K, V>,
534}
535
536impl<K, V> NonEmptyIterator for IterMut<'_, K, V> {}
537
538impl<'a, K, V> IntoIterator for IterMut<'a, K, V> {
539    type Item = (&'a K, &'a mut V);
540
541    type IntoIter = indexmap::map::IterMut<'a, K, V>;
542
543    fn into_iter(self) -> Self::IntoIter {
544        self.iter
545    }
546}
547
548impl<K: Debug, V: Debug> Debug for IterMut<'_, K, V> {
549    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
550        self.iter.fmt(f)
551    }
552}
553
554/// A non-empty iterator over the entries of an [`NEIndexMap`].
555pub struct IntoIter<K, V> {
556    iter: indexmap::map::IntoIter<K, V>,
557}
558
559impl<K, V> NonEmptyIterator for IntoIter<K, V> {}
560
561impl<K, V> IntoIterator for IntoIter<K, V> {
562    type Item = (K, V);
563
564    type IntoIter = indexmap::map::IntoIter<K, V>;
565
566    fn into_iter(self) -> Self::IntoIter {
567        self.iter
568    }
569}
570
571impl<K: Debug, V: Debug> Debug for IntoIter<K, V> {
572    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
573        self.iter.fmt(f)
574    }
575}
576
577/// A non-empty iterator over the keys of an [`NEIndexMap`].
578///
579/// ```
580/// use nonempty_collections::*;
581///
582/// let m = ne_indexmap! {"elves" => 3000, "orcs" => 10000};
583/// let v = m.keys().copied().collect::<NEVec<_>>();
584/// assert_eq!(nev!["elves", "orcs"], v);
585/// ```
586#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
587pub struct Keys<'a, K: 'a, V: 'a> {
588    inner: indexmap::map::Keys<'a, K, V>,
589}
590
591impl<K, V> NonEmptyIterator for Keys<'_, K, V> {}
592
593impl<'a, K, V> IntoIterator for Keys<'a, K, V> {
594    type Item = &'a K;
595
596    type IntoIter = indexmap::map::Keys<'a, K, V>;
597
598    fn into_iter(self) -> Self::IntoIter {
599        self.inner
600    }
601}
602
603// FIXME: Remove in favor of `#[derive(Clone)]` (see https://github.com/rust-lang/rust/issues/26925 for more info)
604impl<K, V> Clone for Keys<'_, K, V> {
605    fn clone(&self) -> Self {
606        Keys {
607            inner: self.inner.clone(),
608        }
609    }
610}
611
612impl<K: Debug, V: Debug> Debug for Keys<'_, K, V> {
613    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
614        f.debug_list().entries(self.clone()).finish()
615    }
616}
617
618/// A non-empty iterator over the values of an [`NEIndexMap`].
619///
620/// ```
621/// use nonempty_collections::*;
622///
623/// let m = ne_indexmap! {"elves" => 3000, "orcs" => 10000};
624/// let mut v = m.values().copied().collect::<NEVec<_>>();
625/// v.sort();
626/// assert_eq!(nev![3000, 10000], v);
627/// ```
628#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
629pub struct Values<'a, K: 'a, V: 'a> {
630    inner: indexmap::map::Values<'a, K, V>,
631}
632
633impl<K, V> NonEmptyIterator for Values<'_, K, V> {}
634
635impl<'a, K, V> IntoIterator for Values<'a, K, V> {
636    type Item = &'a V;
637
638    type IntoIter = indexmap::map::Values<'a, K, V>;
639
640    fn into_iter(self) -> Self::IntoIter {
641        self.inner
642    }
643}
644
645// FIXME: Remove in favor of `#[derive(Clone)]` (see https://github.com/rust-lang/rust/issues/26925 for more info)
646impl<K, V> Clone for Values<'_, K, V> {
647    fn clone(&self) -> Self {
648        Values {
649            inner: self.inner.clone(),
650        }
651    }
652}
653
654impl<K: Debug, V: Debug> Debug for Values<'_, K, V> {
655    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
656        f.debug_list().entries(self.clone()).finish()
657    }
658}
659
660/// A non-empty iterator over the mutable values of an [`NEIndexMap`].
661#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
662pub struct ValuesMut<'a, K: 'a, V: 'a> {
663    inner: indexmap::map::ValuesMut<'a, K, V>,
664}
665
666impl<K, V> NonEmptyIterator for ValuesMut<'_, K, V> {}
667
668impl<'a, K, V> IntoIterator for ValuesMut<'a, K, V> {
669    type Item = &'a mut V;
670
671    type IntoIter = indexmap::map::ValuesMut<'a, K, V>;
672
673    fn into_iter(self) -> Self::IntoIter {
674        self.inner
675    }
676}
677
678impl<K: Debug, V: Debug> Debug for ValuesMut<'_, K, V> {
679    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
680        self.inner.fmt(f)
681    }
682}
683
684#[cfg(test)]
685mod test {
686    use super::*;
687
688    #[test]
689    fn test_swap_indices() {
690        let mut map = ne_indexmap! { 0 => (), 1 => () };
691        assert_eq!(vec![0, 1], map.keys().copied().collect::<Vec<_>>());
692        map.swap_indices(0, 1);
693        assert_eq!(vec![1, 0], map.keys().copied().collect::<Vec<_>>());
694        map.swap_indices(1, 0);
695        assert_eq!(vec![0, 1], map.keys().copied().collect::<Vec<_>>());
696
697        let mut map = ne_indexmap! { 0 => (), 1 => (), 2 => () };
698        assert_eq!(vec![0, 1, 2], map.keys().copied().collect::<Vec<_>>());
699        map.swap_indices(0, 1);
700        assert_eq!(vec![1, 0, 2], map.keys().copied().collect::<Vec<_>>());
701        map.swap_indices(1, 0);
702        assert_eq!(vec![0, 1, 2], map.keys().copied().collect::<Vec<_>>());
703        map.swap_indices(0, 2);
704        assert_eq!(vec![2, 1, 0], map.keys().copied().collect::<Vec<_>>());
705        map.swap_indices(1, 2);
706        assert_eq!(vec![2, 0, 1], map.keys().copied().collect::<Vec<_>>());
707
708        let mut map = ne_indexmap! { 0 => (), 1 => (), 2 => (), 3 => (), 4 => (), 5 => () };
709        assert_eq!(
710            vec![0, 1, 2, 3, 4, 5],
711            map.keys().copied().collect::<Vec<_>>()
712        );
713        map.swap_indices(1, 2);
714        assert_eq!(
715            vec![0, 2, 1, 3, 4, 5],
716            map.keys().copied().collect::<Vec<_>>()
717        );
718        map.swap_indices(0, 3);
719        assert_eq!(
720            vec![3, 2, 1, 0, 4, 5],
721            map.keys().copied().collect::<Vec<_>>()
722        );
723    }
724
725    #[test]
726    fn debug_impl() {
727        let expected = format!("{:?}", indexmap! {0 => 10, 1 => 11, 2 => 12});
728        let actual = format!("{:?}", ne_indexmap! {0 => 10, 1 => 11, 2 => 12});
729        assert_eq!(expected, actual);
730    }
731}