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 nonempty_iter(&self) -> Iter<'_, K, V> {
81 Iter {
82 iter: self.inner.iter(),
83 }
84 }
85
86 pub fn nonempty_iter_mut(&mut self) -> IterMut<'_, K, V> {
88 IterMut {
89 iter: self.inner.iter_mut(),
90 }
91 }
92
93 pub fn keys(&self) -> Keys<'_, K, V> {
104 Keys {
105 inner: self.inner.keys(),
106 }
107 }
108
109 #[must_use]
117 pub fn len(&self) -> NonZeroUsize {
118 unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
119 }
120
121 #[deprecated(note = "A NEIndexMap is never empty.")]
123 #[must_use]
124 pub const fn is_empty(&self) -> bool {
125 false
126 }
127
128 pub fn values(&self) -> Values<'_, K, V> {
137 Values {
138 inner: self.inner.values(),
139 }
140 }
141
142 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
153 ValuesMut {
154 inner: self.inner.values_mut(),
155 }
156 }
157
158 #[allow(clippy::missing_panics_doc)] #[must_use]
161 pub fn first(&self) -> (&K, &V) {
162 self.inner.first().unwrap()
163 }
164
165 #[allow(clippy::missing_panics_doc)] #[must_use]
168 pub fn last(&self) -> (&K, &V) {
169 self.inner.last().unwrap()
170 }
171}
172
173impl<K: Debug, V: Debug, S> Debug for NEIndexMap<K, V, S> {
174 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
175 f.debug_map().entries(self.nonempty_iter()).finish()
176 }
177}
178
179impl<K, V> NEIndexMap<K, V>
180where
181 K: Eq + Hash,
182{
183 #[must_use]
185 pub fn new(k: K, v: V) -> Self {
186 Self {
187 inner: indexmap! {k => v},
188 }
189 }
190
191 #[must_use]
194 pub fn with_capacity(capacity: NonZeroUsize, k: K, v: V) -> NEIndexMap<K, V> {
195 let mut inner = IndexMap::with_capacity(capacity.get());
196 inner.insert(k, v);
197 Self { inner }
198 }
199}
200
201impl<K, V, S> NEIndexMap<K, V, S>
202where
203 K: Eq + Hash,
204 S: BuildHasher,
205{
206 #[must_use]
221 pub fn try_from_map(map: IndexMap<K, V, S>) -> Option<Self> {
222 if map.is_empty() {
223 None
224 } else {
225 Some(Self { inner: map })
226 }
227 }
228
229 #[must_use]
239 pub fn contains_key<Q>(&self, k: &Q) -> bool
240 where
241 Q: Hash + Equivalent<K> + ?Sized,
242 {
243 self.inner.contains_key(k)
244 }
245
246 #[must_use]
257 pub fn get<Q>(&self, k: &Q) -> Option<&V>
258 where
259 Q: Hash + Equivalent<K> + ?Sized,
260 {
261 self.inner.get(k)
262 }
263
264 #[must_use]
276 pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
277 where
278 Q: Hash + Equivalent<K> + ?Sized,
279 {
280 self.inner.get_key_value(key)
281 }
282
283 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
303 where
304 Q: Hash + Equivalent<K> + ?Sized,
305 {
306 self.inner.get_mut(key)
307 }
308
309 #[must_use]
320 pub fn get_index_of<Q>(&self, key: &Q) -> Option<usize>
321 where
322 Q: Hash + Equivalent<K> + ?Sized,
323 {
324 self.inner.get_index_of(key)
325 }
326
327 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
353 self.inner.insert(k, v)
354 }
355
356 pub fn shrink_to_fit(&mut self) {
358 self.inner.shrink_to_fit();
359 }
360
361 #[must_use]
364 pub fn with_capacity_and_hasher(
365 capacity: NonZeroUsize,
366 hasher: S,
367 k: K,
368 v: V,
369 ) -> NEIndexMap<K, V, S> {
370 let mut inner = IndexMap::with_capacity_and_hasher(capacity.get(), hasher);
371 inner.insert(k, v);
372 Self { inner }
373 }
374
375 #[must_use]
377 pub fn with_hasher(hasher: S, k: K, v: V) -> NEIndexMap<K, V, S> {
378 let mut inner = IndexMap::with_hasher(hasher);
379 inner.insert(k, v);
380 Self { inner }
381 }
382
383 pub fn swap_indices(&mut self, a: usize, b: usize) {
388 self.inner.swap_indices(a, b);
389 }
390}
391
392impl<K, V, S> PartialEq for NEIndexMap<K, V, S>
393where
394 K: Eq + Hash,
395 V: Eq,
396 S: BuildHasher,
397{
398 fn eq(&self, other: &Self) -> bool {
399 self.inner.eq(&other.inner)
400 }
401}
402
403impl<K, V, S> Eq for NEIndexMap<K, V, S>
404where
405 K: Eq + Hash,
406 V: Eq,
407 S: BuildHasher,
408{
409}
410
411impl<K, V, S> From<NEIndexMap<K, V, S>> for IndexMap<K, V, S>
412where
413 K: Eq + Hash,
414 S: BuildHasher,
415{
416 fn from(m: NEIndexMap<K, V, S>) -> Self {
424 m.inner
425 }
426}
427
428impl<K, V, S> IntoNonEmptyIterator for NEIndexMap<K, V, S> {
429 type IntoNEIter = IntoIter<K, V>;
430
431 fn into_nonempty_iter(self) -> Self::IntoNEIter {
432 IntoIter {
433 iter: self.inner.into_iter(),
434 }
435 }
436}
437
438impl<'a, K, V, S> IntoNonEmptyIterator for &'a NEIndexMap<K, V, S> {
439 type IntoNEIter = Iter<'a, K, V>;
440
441 fn into_nonempty_iter(self) -> Self::IntoNEIter {
442 self.nonempty_iter()
443 }
444}
445
446impl<K, V, S> IntoIterator for NEIndexMap<K, V, S> {
447 type Item = (K, V);
448
449 type IntoIter = indexmap::map::IntoIter<K, V>;
450
451 fn into_iter(self) -> Self::IntoIter {
452 self.inner.into_iter()
453 }
454}
455
456impl<'a, K, V, S> IntoIterator for &'a NEIndexMap<K, V, S> {
457 type Item = (&'a K, &'a V);
458
459 type IntoIter = indexmap::map::Iter<'a, K, V>;
460
461 fn into_iter(self) -> Self::IntoIter {
462 self.iter()
463 }
464}
465
466impl<K, V, S> FromNonEmptyIterator<(K, V)> for NEIndexMap<K, V, S>
475where
476 K: Eq + Hash,
477 S: BuildHasher + Default,
478{
479 fn from_nonempty_iter<I>(iter: I) -> Self
480 where
481 I: IntoNonEmptyIterator<Item = (K, V)>,
482 {
483 Self {
484 inner: iter.into_nonempty_iter().into_iter().collect(),
485 }
486 }
487}
488
489impl<K, V> std::ops::Index<usize> for NEIndexMap<K, V> {
490 type Output = V;
491
492 fn index(&self, index: usize) -> &V {
493 self.inner.index(index)
494 }
495}
496
497#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
499pub struct Iter<'a, K: 'a, V: 'a> {
500 iter: indexmap::map::Iter<'a, K, V>,
501}
502
503impl<K, V> NonEmptyIterator for Iter<'_, K, V> {}
504
505impl<'a, K, V> IntoIterator for Iter<'a, K, V> {
506 type Item = (&'a K, &'a V);
507
508 type IntoIter = indexmap::map::Iter<'a, K, V>;
509
510 fn into_iter(self) -> Self::IntoIter {
511 self.iter
512 }
513}
514
515impl<K, V> Clone for Iter<'_, K, V> {
517 fn clone(&self) -> Self {
518 Iter {
519 iter: self.iter.clone(),
520 }
521 }
522}
523
524impl<K: Debug, V: Debug> Debug for Iter<'_, K, V> {
525 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
526 f.debug_list().entries(self.clone()).finish()
527 }
528}
529
530#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
532pub struct IterMut<'a, K: 'a, V: 'a> {
533 iter: indexmap::map::IterMut<'a, K, V>,
534}
535
536impl<K, V> NonEmptyIterator for IterMut<'_, K, V> {}
537
538impl<'a, K, V> IntoIterator for IterMut<'a, K, V> {
539 type Item = (&'a K, &'a mut V);
540
541 type IntoIter = indexmap::map::IterMut<'a, K, V>;
542
543 fn into_iter(self) -> Self::IntoIter {
544 self.iter
545 }
546}
547
548impl<K: Debug, V: Debug> Debug for IterMut<'_, K, V> {
549 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
550 self.iter.fmt(f)
551 }
552}
553
554pub struct IntoIter<K, V> {
556 iter: indexmap::map::IntoIter<K, V>,
557}
558
559impl<K, V> NonEmptyIterator for IntoIter<K, V> {}
560
561impl<K, V> IntoIterator for IntoIter<K, V> {
562 type Item = (K, V);
563
564 type IntoIter = indexmap::map::IntoIter<K, V>;
565
566 fn into_iter(self) -> Self::IntoIter {
567 self.iter
568 }
569}
570
571impl<K: Debug, V: Debug> Debug for IntoIter<K, V> {
572 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
573 self.iter.fmt(f)
574 }
575}
576
577#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
587pub struct Keys<'a, K: 'a, V: 'a> {
588 inner: indexmap::map::Keys<'a, K, V>,
589}
590
591impl<K, V> NonEmptyIterator for Keys<'_, K, V> {}
592
593impl<'a, K, V> IntoIterator for Keys<'a, K, V> {
594 type Item = &'a K;
595
596 type IntoIter = indexmap::map::Keys<'a, K, V>;
597
598 fn into_iter(self) -> Self::IntoIter {
599 self.inner
600 }
601}
602
603impl<K, V> Clone for Keys<'_, K, V> {
605 fn clone(&self) -> Self {
606 Keys {
607 inner: self.inner.clone(),
608 }
609 }
610}
611
612impl<K: Debug, V: Debug> Debug for Keys<'_, K, V> {
613 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
614 f.debug_list().entries(self.clone()).finish()
615 }
616}
617
618#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
629pub struct Values<'a, K: 'a, V: 'a> {
630 inner: indexmap::map::Values<'a, K, V>,
631}
632
633impl<K, V> NonEmptyIterator for Values<'_, K, V> {}
634
635impl<'a, K, V> IntoIterator for Values<'a, K, V> {
636 type Item = &'a V;
637
638 type IntoIter = indexmap::map::Values<'a, K, V>;
639
640 fn into_iter(self) -> Self::IntoIter {
641 self.inner
642 }
643}
644
645impl<K, V> Clone for Values<'_, K, V> {
647 fn clone(&self) -> Self {
648 Values {
649 inner: self.inner.clone(),
650 }
651 }
652}
653
654impl<K: Debug, V: Debug> Debug for Values<'_, K, V> {
655 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
656 f.debug_list().entries(self.clone()).finish()
657 }
658}
659
660#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
662pub struct ValuesMut<'a, K: 'a, V: 'a> {
663 inner: indexmap::map::ValuesMut<'a, K, V>,
664}
665
666impl<K, V> NonEmptyIterator for ValuesMut<'_, K, V> {}
667
668impl<'a, K, V> IntoIterator for ValuesMut<'a, K, V> {
669 type Item = &'a mut V;
670
671 type IntoIter = indexmap::map::ValuesMut<'a, K, V>;
672
673 fn into_iter(self) -> Self::IntoIter {
674 self.inner
675 }
676}
677
678impl<K: Debug, V: Debug> Debug for ValuesMut<'_, K, V> {
679 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
680 self.inner.fmt(f)
681 }
682}
683
684#[cfg(test)]
685mod test {
686 use super::*;
687
688 #[test]
689 fn test_swap_indices() {
690 let mut map = ne_indexmap! { 0 => (), 1 => () };
691 assert_eq!(vec![0, 1], map.keys().copied().collect::<Vec<_>>());
692 map.swap_indices(0, 1);
693 assert_eq!(vec![1, 0], map.keys().copied().collect::<Vec<_>>());
694 map.swap_indices(1, 0);
695 assert_eq!(vec![0, 1], map.keys().copied().collect::<Vec<_>>());
696
697 let mut map = ne_indexmap! { 0 => (), 1 => (), 2 => () };
698 assert_eq!(vec![0, 1, 2], map.keys().copied().collect::<Vec<_>>());
699 map.swap_indices(0, 1);
700 assert_eq!(vec![1, 0, 2], map.keys().copied().collect::<Vec<_>>());
701 map.swap_indices(1, 0);
702 assert_eq!(vec![0, 1, 2], map.keys().copied().collect::<Vec<_>>());
703 map.swap_indices(0, 2);
704 assert_eq!(vec![2, 1, 0], map.keys().copied().collect::<Vec<_>>());
705 map.swap_indices(1, 2);
706 assert_eq!(vec![2, 0, 1], map.keys().copied().collect::<Vec<_>>());
707
708 let mut map = ne_indexmap! { 0 => (), 1 => (), 2 => (), 3 => (), 4 => (), 5 => () };
709 assert_eq!(
710 vec![0, 1, 2, 3, 4, 5],
711 map.keys().copied().collect::<Vec<_>>()
712 );
713 map.swap_indices(1, 2);
714 assert_eq!(
715 vec![0, 2, 1, 3, 4, 5],
716 map.keys().copied().collect::<Vec<_>>()
717 );
718 map.swap_indices(0, 3);
719 assert_eq!(
720 vec![3, 2, 1, 0, 4, 5],
721 map.keys().copied().collect::<Vec<_>>()
722 );
723 }
724
725 #[test]
726 fn debug_impl() {
727 let expected = format!("{:?}", indexmap! {0 => 10, 1 => 11, 2 => 12});
728 let actual = format!("{:?}", ne_indexmap! {0 => 10, 1 => 11, 2 => 12});
729 assert_eq!(expected, actual);
730 }
731}