1use 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#[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#[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 #[must_use]
62 pub fn capacity(&self) -> NonZeroUsize {
63 unsafe { NonZeroUsize::new_unchecked(self.inner.capacity()) }
64 }
65
66 #[must_use]
68 pub fn hasher(&self) -> &S {
69 self.inner.hasher()
70 }
71
72 pub fn iter(&self) -> indexmap::map::Iter<'_, K, V> {
76 self.inner.iter()
77 }
78
79 pub fn iter_mut(&mut self) -> indexmap::map::IterMut<'_, K, V> {
84 self.inner.iter_mut()
85 }
86
87 pub fn nonempty_iter(&self) -> Iter<'_, K, V> {
89 Iter {
90 iter: self.inner.iter(),
91 }
92 }
93
94 pub fn nonempty_iter_mut(&mut self) -> IterMut<'_, K, V> {
96 IterMut {
97 iter: self.inner.iter_mut(),
98 }
99 }
100
101 pub fn keys(&self) -> Keys<'_, K, V> {
112 Keys {
113 inner: self.inner.keys(),
114 }
115 }
116
117 #[must_use]
125 pub fn len(&self) -> NonZeroUsize {
126 unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
127 }
128
129 #[deprecated(note = "A NEIndexMap is never empty.")]
131 #[must_use]
132 pub const fn is_empty(&self) -> bool {
133 false
134 }
135
136 pub fn values(&self) -> Values<'_, K, V> {
145 Values {
146 inner: self.inner.values(),
147 }
148 }
149
150 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
161 ValuesMut {
162 inner: self.inner.values_mut(),
163 }
164 }
165
166 #[allow(clippy::missing_panics_doc)] #[must_use]
169 pub fn first(&self) -> (&K, &V) {
170 self.inner.first().unwrap()
171 }
172
173 #[allow(clippy::missing_panics_doc)] #[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 #[must_use]
193 pub fn new(k: K, v: V) -> Self {
194 Self {
195 inner: indexmap! {k => v},
196 }
197 }
198
199 #[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 #[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 #[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 #[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 #[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 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 #[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 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
361 self.inner.insert(k, v)
362 }
363
364 pub fn shrink_to_fit(&mut self) {
366 self.inner.shrink_to_fit();
367 }
368
369 #[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 #[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 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 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
484impl<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#[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
533impl<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#[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
572pub 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#[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
621impl<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#[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
663impl<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#[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}