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