1use 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#[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#[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 #[must_use]
61 pub fn capacity(&self) -> NonZeroUsize {
62 unsafe { NonZeroUsize::new_unchecked(self.inner.capacity()) }
63 }
64
65 #[must_use]
67 pub fn hasher(&self) -> &S {
68 self.inner.hasher()
69 }
70
71 pub fn iter(&self) -> indexmap::map::Iter<'_, K, V> {
75 self.inner.iter()
76 }
77
78 pub fn iter_mut(&mut self) -> indexmap::map::IterMut<'_, K, V> {
83 self.inner.iter_mut()
84 }
85
86 pub fn nonempty_iter(&self) -> Iter<'_, K, V> {
88 Iter {
89 iter: self.inner.iter(),
90 }
91 }
92
93 pub fn nonempty_iter_mut(&mut self) -> IterMut<'_, K, V> {
95 IterMut {
96 iter: self.inner.iter_mut(),
97 }
98 }
99
100 pub fn keys(&self) -> Keys<'_, K, V> {
111 Keys {
112 inner: self.inner.keys(),
113 }
114 }
115
116 #[must_use]
124 pub fn len(&self) -> NonZeroUsize {
125 unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
126 }
127
128 #[deprecated(note = "A NEIndexMap is never empty.")]
130 #[must_use]
131 pub const fn is_empty(&self) -> bool {
132 false
133 }
134
135 pub fn values(&self) -> Values<'_, K, V> {
144 Values {
145 inner: self.inner.values(),
146 }
147 }
148
149 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
160 ValuesMut {
161 inner: self.inner.values_mut(),
162 }
163 }
164
165 #[allow(clippy::missing_panics_doc)] #[must_use]
168 pub fn first(&self) -> (&K, &V) {
169 self.inner.first().unwrap()
170 }
171
172 #[allow(clippy::missing_panics_doc)] #[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 #[must_use]
192 pub fn new(k: K, v: V) -> Self {
193 Self {
194 inner: indexmap! {k => v},
195 }
196 }
197
198 #[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 #[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 #[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 #[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 #[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 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 #[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 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
360 self.inner.insert(k, v)
361 }
362
363 pub fn shrink_to_fit(&mut self) {
365 self.inner.shrink_to_fit();
366 }
367
368 #[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 #[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 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 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
495impl<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#[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
544impl<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#[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
583pub 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#[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
632impl<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#[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
674impl<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#[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 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}