Skip to main content

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