1use super::{
2 Bucket, IndexMap, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values, ValuesMut,
3};
4use crate::GetDisjointMutError;
5use crate::util::{slice_eq, try_simplify_range};
6
7use alloc::boxed::Box;
8use alloc::vec::Vec;
9use core::cmp::Ordering;
10use core::fmt;
11use core::hash::{Hash, Hasher};
12use core::ops::{self, Bound, Index, IndexMut, RangeBounds};
13
14#[repr(transparent)]
22pub struct Slice<K, V> {
23 pub(crate) entries: [Bucket<K, V>],
24}
25
26#[allow(unsafe_code)]
29impl<K, V> Slice<K, V> {
30 pub(crate) const fn from_slice(entries: &[Bucket<K, V>]) -> &Self {
31 unsafe { &*(entries as *const [Bucket<K, V>] as *const Self) }
32 }
33
34 pub(super) const fn from_mut_slice(entries: &mut [Bucket<K, V>]) -> &mut Self {
35 unsafe { &mut *(entries as *mut [Bucket<K, V>] as *mut Self) }
36 }
37
38 pub(super) fn from_boxed(entries: Box<[Bucket<K, V>]>) -> Box<Self> {
39 unsafe { Box::from_raw(Box::into_raw(entries) as *mut Self) }
40 }
41
42 fn into_boxed(self: Box<Self>) -> Box<[Bucket<K, V>]> {
43 unsafe { Box::from_raw(Box::into_raw(self) as *mut [Bucket<K, V>]) }
44 }
45}
46
47impl<K, V> Slice<K, V> {
48 pub(crate) fn into_entries(self: Box<Self>) -> Vec<Bucket<K, V>> {
49 self.into_boxed().into_vec()
50 }
51
52 pub const fn new<'a>() -> &'a Self {
54 Self::from_slice(&[])
55 }
56
57 pub const fn new_mut<'a>() -> &'a mut Self {
59 Self::from_mut_slice(&mut [])
60 }
61
62 #[inline]
64 pub const fn len(&self) -> usize {
65 self.entries.len()
66 }
67
68 #[inline]
70 pub const fn is_empty(&self) -> bool {
71 self.entries.is_empty()
72 }
73
74 pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
78 self.entries.get(index).map(Bucket::refs)
79 }
80
81 pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
85 self.entries.get_mut(index).map(Bucket::ref_mut)
86 }
87
88 pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Self> {
92 let range = try_simplify_range(range, self.entries.len())?;
93 self.entries.get(range).map(Slice::from_slice)
94 }
95
96 pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Self> {
100 let range = try_simplify_range(range, self.entries.len())?;
101 self.entries.get_mut(range).map(Slice::from_mut_slice)
102 }
103
104 pub const fn first(&self) -> Option<(&K, &V)> {
106 if let [first, ..] = &self.entries {
107 Some(first.refs())
108 } else {
109 None
110 }
111 }
112
113 pub const fn first_mut(&mut self) -> Option<(&K, &mut V)> {
115 if let [first, ..] = &mut self.entries {
116 Some(first.ref_mut())
117 } else {
118 None
119 }
120 }
121
122 pub const fn last(&self) -> Option<(&K, &V)> {
124 if let [.., last] = &self.entries {
125 Some(last.refs())
126 } else {
127 None
128 }
129 }
130
131 pub const fn last_mut(&mut self) -> Option<(&K, &mut V)> {
133 if let [.., last] = &mut self.entries {
134 Some(last.ref_mut())
135 } else {
136 None
137 }
138 }
139
140 #[track_caller]
145 pub const fn split_at(&self, index: usize) -> (&Self, &Self) {
146 let (first, second) = self.entries.split_at(index);
147 (Self::from_slice(first), Self::from_slice(second))
148 }
149
150 #[track_caller]
155 pub const fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) {
156 let (first, second) = self.entries.split_at_mut(index);
157 (Self::from_mut_slice(first), Self::from_mut_slice(second))
158 }
159
160 pub const fn split_at_checked(&self, index: usize) -> Option<(&Self, &Self)> {
164 if let Some((first, second)) = self.entries.split_at_checked(index) {
165 Some((Self::from_slice(first), Self::from_slice(second)))
166 } else {
167 None
168 }
169 }
170
171 pub const fn split_at_mut_checked(&mut self, index: usize) -> Option<(&mut Self, &mut Self)> {
175 if let Some((first, second)) = self.entries.split_at_mut_checked(index) {
176 Some((Self::from_mut_slice(first), Self::from_mut_slice(second)))
177 } else {
178 None
179 }
180 }
181
182 pub const fn split_first(&self) -> Option<((&K, &V), &Self)> {
185 if let [first, rest @ ..] = &self.entries {
186 Some((first.refs(), Self::from_slice(rest)))
187 } else {
188 None
189 }
190 }
191
192 pub const fn split_first_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
195 if let [first, rest @ ..] = &mut self.entries {
196 Some((first.ref_mut(), Self::from_mut_slice(rest)))
197 } else {
198 None
199 }
200 }
201
202 pub const fn split_last(&self) -> Option<((&K, &V), &Self)> {
205 if let [rest @ .., last] = &self.entries {
206 Some((last.refs(), Self::from_slice(rest)))
207 } else {
208 None
209 }
210 }
211
212 pub const fn split_last_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
215 if let [rest @ .., last] = &mut self.entries {
216 Some((last.ref_mut(), Self::from_mut_slice(rest)))
217 } else {
218 None
219 }
220 }
221
222 pub fn iter(&self) -> Iter<'_, K, V> {
224 Iter::new(&self.entries)
225 }
226
227 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
229 IterMut::new(&mut self.entries)
230 }
231
232 pub fn keys(&self) -> Keys<'_, K, V> {
234 Keys::new(&self.entries)
235 }
236
237 pub fn into_keys(self: Box<Self>) -> IntoKeys<K, V> {
239 IntoKeys::new(self.into_entries())
240 }
241
242 pub fn values(&self) -> Values<'_, K, V> {
244 Values::new(&self.entries)
245 }
246
247 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
249 ValuesMut::new(&mut self.entries)
250 }
251
252 pub fn into_values(self: Box<Self>) -> IntoValues<K, V> {
254 IntoValues::new(self.into_entries())
255 }
256
257 pub fn binary_search_keys(&self, x: &K) -> Result<usize, usize>
266 where
267 K: Ord,
268 {
269 self.binary_search_by(|p, _| p.cmp(x))
270 }
271
272 #[inline]
279 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
280 where
281 F: FnMut(&'a K, &'a V) -> Ordering,
282 {
283 self.entries.binary_search_by(move |a| f(&a.key, &a.value))
284 }
285
286 #[inline]
293 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
294 where
295 F: FnMut(&'a K, &'a V) -> B,
296 B: Ord,
297 {
298 self.binary_search_by(|k, v| f(k, v).cmp(b))
299 }
300
301 #[inline]
303 pub fn is_sorted(&self) -> bool
304 where
305 K: PartialOrd,
306 {
307 self.entries.is_sorted_by(|a, b| a.key <= b.key)
308 }
309
310 #[inline]
312 pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool
313 where
314 F: FnMut(&'a K, &'a V, &'a K, &'a V) -> bool,
315 {
316 self.entries
317 .is_sorted_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value))
318 }
319
320 #[inline]
322 pub fn is_sorted_by_key<'a, F, T>(&'a self, mut sort_key: F) -> bool
323 where
324 F: FnMut(&'a K, &'a V) -> T,
325 T: PartialOrd,
326 {
327 self.entries
328 .is_sorted_by_key(move |a| sort_key(&a.key, &a.value))
329 }
330
331 #[must_use]
338 pub fn partition_point<P>(&self, mut pred: P) -> usize
339 where
340 P: FnMut(&K, &V) -> bool,
341 {
342 self.entries
343 .partition_point(move |a| pred(&a.key, &a.value))
344 }
345
346 pub fn get_disjoint_mut<const N: usize>(
350 &mut self,
351 indices: [usize; N],
352 ) -> Result<[(&K, &mut V); N], GetDisjointMutError> {
353 let indices = indices.map(Some);
354 let key_values = self.get_disjoint_opt_mut(indices)?;
355 Ok(key_values.map(Option::unwrap))
356 }
357
358 #[allow(unsafe_code)]
359 pub(crate) fn get_disjoint_opt_mut<const N: usize>(
360 &mut self,
361 indices: [Option<usize>; N],
362 ) -> Result<[Option<(&K, &mut V)>; N], GetDisjointMutError> {
363 let len = self.len();
365 for i in 0..N {
366 if let Some(idx) = indices[i] {
367 if idx >= len {
368 return Err(GetDisjointMutError::IndexOutOfBounds);
369 } else if indices[..i].contains(&Some(idx)) {
370 return Err(GetDisjointMutError::OverlappingIndices);
371 }
372 }
373 }
374
375 let entries_ptr = self.entries.as_mut_ptr();
376 let out = indices.map(|idx_opt| {
377 match idx_opt {
378 Some(idx) => {
379 let kv = unsafe { (*(entries_ptr.add(idx))).ref_mut() };
382 Some(kv)
383 }
384 None => None,
385 }
386 });
387
388 Ok(out)
389 }
390}
391
392impl<'a, K, V> IntoIterator for &'a Slice<K, V> {
393 type IntoIter = Iter<'a, K, V>;
394 type Item = (&'a K, &'a V);
395
396 fn into_iter(self) -> Self::IntoIter {
397 self.iter()
398 }
399}
400
401impl<'a, K, V> IntoIterator for &'a mut Slice<K, V> {
402 type IntoIter = IterMut<'a, K, V>;
403 type Item = (&'a K, &'a mut V);
404
405 fn into_iter(self) -> Self::IntoIter {
406 self.iter_mut()
407 }
408}
409
410impl<K, V> IntoIterator for Box<Slice<K, V>> {
411 type IntoIter = IntoIter<K, V>;
412 type Item = (K, V);
413
414 fn into_iter(self) -> Self::IntoIter {
415 IntoIter::new(self.into_entries())
416 }
417}
418
419impl<K, V> Default for &'_ Slice<K, V> {
420 fn default() -> Self {
421 Slice::from_slice(&[])
422 }
423}
424
425impl<K, V> Default for &'_ mut Slice<K, V> {
426 fn default() -> Self {
427 Slice::from_mut_slice(&mut [])
428 }
429}
430
431impl<K, V> Default for Box<Slice<K, V>> {
432 fn default() -> Self {
433 Slice::from_boxed(Box::default())
434 }
435}
436
437impl<K: Clone, V: Clone> Clone for Box<Slice<K, V>> {
438 fn clone(&self) -> Self {
439 Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
440 }
441}
442
443impl<K: Copy, V: Copy> From<&Slice<K, V>> for Box<Slice<K, V>> {
444 fn from(slice: &Slice<K, V>) -> Self {
445 Slice::from_boxed(Box::from(&slice.entries))
446 }
447}
448
449impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Slice<K, V> {
450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 f.debug_list().entries(self).finish()
452 }
453}
454
455impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for Slice<K, V>
456where
457 K: PartialEq<K2>,
458 V: PartialEq<V2>,
459{
460 fn eq(&self, other: &Slice<K2, V2>) -> bool {
461 slice_eq(&self.entries, &other.entries, |b1, b2| {
462 b1.key == b2.key && b1.value == b2.value
463 })
464 }
465}
466
467impl<K, V, K2, V2> PartialEq<[(K2, V2)]> for Slice<K, V>
468where
469 K: PartialEq<K2>,
470 V: PartialEq<V2>,
471{
472 fn eq(&self, other: &[(K2, V2)]) -> bool {
473 slice_eq(&self.entries, other, |b, t| b.key == t.0 && b.value == t.1)
474 }
475}
476
477impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V)]
478where
479 K: PartialEq<K2>,
480 V: PartialEq<V2>,
481{
482 fn eq(&self, other: &Slice<K2, V2>) -> bool {
483 slice_eq(self, &other.entries, |t, b| t.0 == b.key && t.1 == b.value)
484 }
485}
486
487impl<K, V, K2, V2, const N: usize> PartialEq<[(K2, V2); N]> for Slice<K, V>
488where
489 K: PartialEq<K2>,
490 V: PartialEq<V2>,
491{
492 fn eq(&self, other: &[(K2, V2); N]) -> bool {
493 <Self as PartialEq<[_]>>::eq(self, other)
494 }
495}
496
497impl<K, V, const N: usize, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V); N]
498where
499 K: PartialEq<K2>,
500 V: PartialEq<V2>,
501{
502 fn eq(&self, other: &Slice<K2, V2>) -> bool {
503 <[_] as PartialEq<_>>::eq(self, other)
504 }
505}
506
507impl<K: Eq, V: Eq> Eq for Slice<K, V> {}
508
509impl<K: PartialOrd, V: PartialOrd> PartialOrd for Slice<K, V> {
510 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
511 self.iter().partial_cmp(other)
512 }
513}
514
515impl<K: Ord, V: Ord> Ord for Slice<K, V> {
516 fn cmp(&self, other: &Self) -> Ordering {
517 self.iter().cmp(other)
518 }
519}
520
521impl<K: Hash, V: Hash> Hash for Slice<K, V> {
522 fn hash<H: Hasher>(&self, state: &mut H) {
523 self.len().hash(state);
524 for (key, value) in self {
525 key.hash(state);
526 value.hash(state);
527 }
528 }
529}
530
531impl<K, V> Index<usize> for Slice<K, V> {
532 type Output = V;
533
534 fn index(&self, index: usize) -> &V {
535 &self.entries[index].value
536 }
537}
538
539impl<K, V> IndexMut<usize> for Slice<K, V> {
540 fn index_mut(&mut self, index: usize) -> &mut V {
541 &mut self.entries[index].value
542 }
543}
544
545macro_rules! impl_index {
549 ($($range:ty),*) => {$(
550 impl<K, V, S> Index<$range> for IndexMap<K, V, S> {
551 type Output = Slice<K, V>;
552
553 fn index(&self, range: $range) -> &Self::Output {
554 Slice::from_slice(&self.as_entries()[range])
555 }
556 }
557
558 impl<K, V, S> IndexMut<$range> for IndexMap<K, V, S> {
559 fn index_mut(&mut self, range: $range) -> &mut Self::Output {
560 Slice::from_mut_slice(&mut self.as_entries_mut()[range])
561 }
562 }
563
564 impl<K, V> Index<$range> for Slice<K, V> {
565 type Output = Slice<K, V>;
566
567 fn index(&self, range: $range) -> &Self {
568 Self::from_slice(&self.entries[range])
569 }
570 }
571
572 impl<K, V> IndexMut<$range> for Slice<K, V> {
573 fn index_mut(&mut self, range: $range) -> &mut Self {
574 Self::from_mut_slice(&mut self.entries[range])
575 }
576 }
577 )*}
578}
579impl_index!(
580 ops::Range<usize>,
581 ops::RangeFrom<usize>,
582 ops::RangeFull,
583 ops::RangeInclusive<usize>,
584 ops::RangeTo<usize>,
585 ops::RangeToInclusive<usize>,
586 (Bound<usize>, Bound<usize>)
587);
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592
593 #[test]
594 fn slice_index() {
595 fn check(
596 vec_slice: &[(i32, i32)],
597 map_slice: &Slice<i32, i32>,
598 sub_slice: &Slice<i32, i32>,
599 ) {
600 assert_eq!(map_slice as *const _, sub_slice as *const _);
601 itertools::assert_equal(
602 vec_slice.iter().copied(),
603 map_slice.iter().map(|(&k, &v)| (k, v)),
604 );
605 itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys());
606 itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values());
607 }
608
609 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
610 let map: IndexMap<i32, i32> = vec.iter().cloned().collect();
611 let slice = map.as_slice();
612
613 check(&vec[..], &map[..], &slice[..]);
615
616 for i in 0usize..10 {
617 assert_eq!(vec[i].1, map[i]);
619 assert_eq!(vec[i].1, slice[i]);
620 assert_eq!(map[&(i as i32)], map[i]);
621 assert_eq!(map[&(i as i32)], slice[i]);
622
623 check(&vec[i..], &map[i..], &slice[i..]);
625
626 check(&vec[..i], &map[..i], &slice[..i]);
628
629 check(&vec[..=i], &map[..=i], &slice[..=i]);
631
632 let bounds = (Bound::Excluded(i), Bound::Unbounded);
634 check(&vec[i + 1..], &map[bounds], &slice[bounds]);
635
636 for j in i..=10 {
637 check(&vec[i..j], &map[i..j], &slice[i..j]);
639 }
640
641 for j in i..10 {
642 check(&vec[i..=j], &map[i..=j], &slice[i..=j]);
644 }
645 }
646 }
647
648 #[test]
649 fn slice_index_mut() {
650 fn check_mut(
651 vec_slice: &[(i32, i32)],
652 map_slice: &mut Slice<i32, i32>,
653 sub_slice: &mut Slice<i32, i32>,
654 ) {
655 assert_eq!(map_slice, sub_slice);
656 itertools::assert_equal(
657 vec_slice.iter().copied(),
658 map_slice.iter_mut().map(|(&k, &mut v)| (k, v)),
659 );
660 itertools::assert_equal(
661 vec_slice.iter().map(|&(_, v)| v),
662 map_slice.values_mut().map(|&mut v| v),
663 );
664 }
665
666 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
667 let mut map: IndexMap<i32, i32> = vec.iter().cloned().collect();
668 let mut map2 = map.clone();
669 let slice = map2.as_mut_slice();
670
671 check_mut(&vec[..], &mut map[..], &mut slice[..]);
673
674 for i in 0usize..10 {
675 assert_eq!(&mut map[i], &mut slice[i]);
677
678 check_mut(&vec[i..], &mut map[i..], &mut slice[i..]);
680
681 check_mut(&vec[..i], &mut map[..i], &mut slice[..i]);
683
684 check_mut(&vec[..=i], &mut map[..=i], &mut slice[..=i]);
686
687 let bounds = (Bound::Excluded(i), Bound::Unbounded);
689 check_mut(&vec[i + 1..], &mut map[bounds], &mut slice[bounds]);
690
691 for j in i..=10 {
692 check_mut(&vec[i..j], &mut map[i..j], &mut slice[i..j]);
694 }
695
696 for j in i..10 {
697 check_mut(&vec[i..=j], &mut map[i..=j], &mut slice[i..=j]);
699 }
700 }
701 }
702
703 #[test]
704 fn slice_new() {
705 let slice: &Slice<i32, i32> = Slice::new();
706 assert!(slice.is_empty());
707 assert_eq!(slice.len(), 0);
708 }
709
710 #[test]
711 fn slice_new_mut() {
712 let slice: &mut Slice<i32, i32> = Slice::new_mut();
713 assert!(slice.is_empty());
714 assert_eq!(slice.len(), 0);
715 }
716
717 #[test]
718 fn slice_get_index_mut() {
719 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
720 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
721
722 {
723 let (key, value) = slice.get_index_mut(0).unwrap();
724 assert_eq!(*key, 0);
725 assert_eq!(*value, 0);
726
727 *value = 11;
728 }
729
730 assert_eq!(slice[0], 11);
731
732 {
733 let result = slice.get_index_mut(11);
734 assert!(result.is_none());
735 }
736 }
737
738 #[test]
739 fn slice_split_first() {
740 let slice: &mut Slice<i32, i32> = Slice::new_mut();
741 let result = slice.split_first();
742 assert!(result.is_none());
743
744 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
745 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
746
747 {
748 let (first, rest) = slice.split_first().unwrap();
749 assert_eq!(first, (&0, &0));
750 assert_eq!(rest.len(), 9);
751 }
752 assert_eq!(slice.len(), 10);
753 }
754
755 #[test]
756 fn slice_split_first_mut() {
757 let slice: &mut Slice<i32, i32> = Slice::new_mut();
758 let result = slice.split_first_mut();
759 assert!(result.is_none());
760
761 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
762 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
763
764 {
765 let (first, rest) = slice.split_first_mut().unwrap();
766 assert_eq!(first, (&0, &mut 0));
767 assert_eq!(rest.len(), 9);
768
769 *first.1 = 11;
770 }
771 assert_eq!(slice.len(), 10);
772 assert_eq!(slice[0], 11);
773 }
774
775 #[test]
776 fn slice_split_last() {
777 let slice: &mut Slice<i32, i32> = Slice::new_mut();
778 let result = slice.split_last();
779 assert!(result.is_none());
780
781 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
782 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
783
784 {
785 let (last, rest) = slice.split_last().unwrap();
786 assert_eq!(last, (&9, &81));
787 assert_eq!(rest.len(), 9);
788 }
789 assert_eq!(slice.len(), 10);
790 }
791
792 #[test]
793 fn slice_split_last_mut() {
794 let slice: &mut Slice<i32, i32> = Slice::new_mut();
795 let result = slice.split_last_mut();
796 assert!(result.is_none());
797
798 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
799 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
800
801 {
802 let (last, rest) = slice.split_last_mut().unwrap();
803 assert_eq!(last, (&9, &mut 81));
804 assert_eq!(rest.len(), 9);
805
806 *last.1 = 100;
807 }
808
809 assert_eq!(slice.len(), 10);
810 assert_eq!(slice[slice.len() - 1], 100);
811 }
812
813 #[test]
814 fn slice_get_range() {
815 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
816 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
817 let subslice = slice.get_range(3..6).unwrap();
818 assert_eq!(subslice.len(), 3);
819 assert_eq!(subslice, &[(3, 9), (4, 16), (5, 25)]);
820 }
821}