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#[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#[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#[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 #[must_use]
84 pub fn capacity(&self) -> NonZeroUsize {
85 unsafe { NonZeroUsize::new_unchecked(self.inner.capacity()) }
86 }
87
88 #[must_use]
90 pub fn hasher(&self) -> &S {
91 self.inner.hasher()
92 }
93
94 pub fn iter(&self) -> indexmap::map::Iter<'_, K, V> {
98 self.inner.iter()
99 }
100
101 pub fn iter_mut(&mut self) -> indexmap::map::IterMut<'_, K, V> {
106 self.inner.iter_mut()
107 }
108
109 pub fn nonempty_iter(&self) -> Iter<'_, K, V> {
111 Iter {
112 iter: self.inner.iter(),
113 }
114 }
115
116 pub fn nonempty_iter_mut(&mut self) -> IterMut<'_, K, V> {
118 IterMut {
119 iter: self.inner.iter_mut(),
120 }
121 }
122
123 pub fn keys(&self) -> Keys<'_, K, V> {
134 Keys {
135 inner: self.inner.keys(),
136 }
137 }
138
139 #[must_use]
147 pub fn len(&self) -> NonZeroUsize {
148 unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
149 }
150
151 #[deprecated(note = "A NEIndexMap is never empty.")]
153 #[must_use]
154 pub const fn is_empty(&self) -> bool {
155 false
156 }
157
158 pub fn values(&self) -> Values<'_, K, V> {
167 Values {
168 inner: self.inner.values(),
169 }
170 }
171
172 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
183 ValuesMut {
184 inner: self.inner.values_mut(),
185 }
186 }
187
188 #[allow(clippy::missing_panics_doc)] #[must_use]
191 pub fn first(&self) -> (&K, &V) {
192 self.inner.first().unwrap()
193 }
194
195 #[allow(clippy::missing_panics_doc)] #[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 #[must_use]
215 pub fn new(k: K, v: V) -> Self {
216 Self {
217 inner: indexmap! {k => v},
218 }
219 }
220
221 #[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 #[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 #[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 #[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 #[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 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 #[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 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
383 self.inner.insert(k, v)
384 }
385
386 pub fn shrink_to_fit(&mut self) {
388 self.inner.shrink_to_fit();
389 }
390
391 #[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 #[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 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 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
518impl<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#[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
567impl<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#[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
606pub 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#[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
655impl<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#[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
697impl<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#[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 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}