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