1use super::{
2 Bucket, IndexMap, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values, ValuesMut,
3};
4use crate::util::{slice_eq, try_simplify_range};
5use crate::GetDisjointMutError;
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) 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 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 fn first_mut(&mut self) -> Option<(&K, &mut V)> {
115 self.entries.first_mut().map(Bucket::ref_mut)
116 }
117
118 pub const fn last(&self) -> Option<(&K, &V)> {
120 if let [.., last] = &self.entries {
121 Some(last.refs())
122 } else {
123 None
124 }
125 }
126
127 pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
129 self.entries.last_mut().map(Bucket::ref_mut)
130 }
131
132 #[track_caller]
137 pub const fn split_at(&self, index: usize) -> (&Self, &Self) {
138 let (first, second) = self.entries.split_at(index);
139 (Self::from_slice(first), Self::from_slice(second))
140 }
141
142 #[track_caller]
147 pub fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) {
148 let (first, second) = self.entries.split_at_mut(index);
149 (Self::from_mut_slice(first), Self::from_mut_slice(second))
150 }
151
152 pub const fn split_at_checked(&self, index: usize) -> Option<(&Self, &Self)> {
156 if let Some((first, second)) = self.entries.split_at_checked(index) {
157 Some((Self::from_slice(first), Self::from_slice(second)))
158 } else {
159 None
160 }
161 }
162
163 pub fn split_at_mut_checked(&mut self, index: usize) -> Option<(&mut Self, &mut Self)> {
167 let (first, second) = self.entries.split_at_mut_checked(index)?;
168 Some((Self::from_mut_slice(first), Self::from_mut_slice(second)))
169 }
170
171 pub const fn split_first(&self) -> Option<((&K, &V), &Self)> {
174 if let [first, rest @ ..] = &self.entries {
175 Some((first.refs(), Self::from_slice(rest)))
176 } else {
177 None
178 }
179 }
180
181 pub fn split_first_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
184 if let [first, rest @ ..] = &mut self.entries {
185 Some((first.ref_mut(), Self::from_mut_slice(rest)))
186 } else {
187 None
188 }
189 }
190
191 pub const fn split_last(&self) -> Option<((&K, &V), &Self)> {
194 if let [rest @ .., last] = &self.entries {
195 Some((last.refs(), Self::from_slice(rest)))
196 } else {
197 None
198 }
199 }
200
201 pub fn split_last_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
204 if let [rest @ .., last] = &mut self.entries {
205 Some((last.ref_mut(), Self::from_mut_slice(rest)))
206 } else {
207 None
208 }
209 }
210
211 pub fn iter(&self) -> Iter<'_, K, V> {
213 Iter::new(&self.entries)
214 }
215
216 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
218 IterMut::new(&mut self.entries)
219 }
220
221 pub fn keys(&self) -> Keys<'_, K, V> {
223 Keys::new(&self.entries)
224 }
225
226 pub fn into_keys(self: Box<Self>) -> IntoKeys<K, V> {
228 IntoKeys::new(self.into_entries())
229 }
230
231 pub fn values(&self) -> Values<'_, K, V> {
233 Values::new(&self.entries)
234 }
235
236 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
238 ValuesMut::new(&mut self.entries)
239 }
240
241 pub fn into_values(self: Box<Self>) -> IntoValues<K, V> {
243 IntoValues::new(self.into_entries())
244 }
245
246 pub fn binary_search_keys(&self, x: &K) -> Result<usize, usize>
255 where
256 K: Ord,
257 {
258 self.binary_search_by(|p, _| p.cmp(x))
259 }
260
261 #[inline]
268 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
269 where
270 F: FnMut(&'a K, &'a V) -> Ordering,
271 {
272 self.entries.binary_search_by(move |a| f(&a.key, &a.value))
273 }
274
275 #[inline]
282 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
283 where
284 F: FnMut(&'a K, &'a V) -> B,
285 B: Ord,
286 {
287 self.binary_search_by(|k, v| f(k, v).cmp(b))
288 }
289
290 #[inline]
292 pub fn is_sorted(&self) -> bool
293 where
294 K: PartialOrd,
295 {
296 self.entries.is_sorted_by(|a, b| a.key <= b.key)
297 }
298
299 #[inline]
301 pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool
302 where
303 F: FnMut(&'a K, &'a V, &'a K, &'a V) -> bool,
304 {
305 self.entries
306 .is_sorted_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value))
307 }
308
309 #[inline]
311 pub fn is_sorted_by_key<'a, F, T>(&'a self, mut sort_key: F) -> bool
312 where
313 F: FnMut(&'a K, &'a V) -> T,
314 T: PartialOrd,
315 {
316 self.entries
317 .is_sorted_by_key(move |a| sort_key(&a.key, &a.value))
318 }
319
320 #[must_use]
327 pub fn partition_point<P>(&self, mut pred: P) -> usize
328 where
329 P: FnMut(&K, &V) -> bool,
330 {
331 self.entries
332 .partition_point(move |a| pred(&a.key, &a.value))
333 }
334
335 pub fn get_disjoint_mut<const N: usize>(
339 &mut self,
340 indices: [usize; N],
341 ) -> Result<[(&K, &mut V); N], GetDisjointMutError> {
342 let indices = indices.map(Some);
343 let key_values = self.get_disjoint_opt_mut(indices)?;
344 Ok(key_values.map(Option::unwrap))
345 }
346
347 #[allow(unsafe_code)]
348 pub(crate) fn get_disjoint_opt_mut<const N: usize>(
349 &mut self,
350 indices: [Option<usize>; N],
351 ) -> Result<[Option<(&K, &mut V)>; N], GetDisjointMutError> {
352 let len = self.len();
354 for i in 0..N {
355 if let Some(idx) = indices[i] {
356 if idx >= len {
357 return Err(GetDisjointMutError::IndexOutOfBounds);
358 } else if indices[..i].contains(&Some(idx)) {
359 return Err(GetDisjointMutError::OverlappingIndices);
360 }
361 }
362 }
363
364 let entries_ptr = self.entries.as_mut_ptr();
365 let out = indices.map(|idx_opt| {
366 match idx_opt {
367 Some(idx) => {
368 let kv = unsafe { (*(entries_ptr.add(idx))).ref_mut() };
371 Some(kv)
372 }
373 None => None,
374 }
375 });
376
377 Ok(out)
378 }
379}
380
381impl<'a, K, V> IntoIterator for &'a Slice<K, V> {
382 type IntoIter = Iter<'a, K, V>;
383 type Item = (&'a K, &'a V);
384
385 fn into_iter(self) -> Self::IntoIter {
386 self.iter()
387 }
388}
389
390impl<'a, K, V> IntoIterator for &'a mut Slice<K, V> {
391 type IntoIter = IterMut<'a, K, V>;
392 type Item = (&'a K, &'a mut V);
393
394 fn into_iter(self) -> Self::IntoIter {
395 self.iter_mut()
396 }
397}
398
399impl<K, V> IntoIterator for Box<Slice<K, V>> {
400 type IntoIter = IntoIter<K, V>;
401 type Item = (K, V);
402
403 fn into_iter(self) -> Self::IntoIter {
404 IntoIter::new(self.into_entries())
405 }
406}
407
408impl<K, V> Default for &'_ Slice<K, V> {
409 fn default() -> Self {
410 Slice::from_slice(&[])
411 }
412}
413
414impl<K, V> Default for &'_ mut Slice<K, V> {
415 fn default() -> Self {
416 Slice::from_mut_slice(&mut [])
417 }
418}
419
420impl<K, V> Default for Box<Slice<K, V>> {
421 fn default() -> Self {
422 Slice::from_boxed(Box::default())
423 }
424}
425
426impl<K: Clone, V: Clone> Clone for Box<Slice<K, V>> {
427 fn clone(&self) -> Self {
428 Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
429 }
430}
431
432impl<K: Copy, V: Copy> From<&Slice<K, V>> for Box<Slice<K, V>> {
433 fn from(slice: &Slice<K, V>) -> Self {
434 Slice::from_boxed(Box::from(&slice.entries))
435 }
436}
437
438impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Slice<K, V> {
439 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
440 f.debug_list().entries(self).finish()
441 }
442}
443
444impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for Slice<K, V>
445where
446 K: PartialEq<K2>,
447 V: PartialEq<V2>,
448{
449 fn eq(&self, other: &Slice<K2, V2>) -> bool {
450 slice_eq(&self.entries, &other.entries, |b1, b2| {
451 b1.key == b2.key && b1.value == b2.value
452 })
453 }
454}
455
456impl<K, V, K2, V2> PartialEq<[(K2, V2)]> for Slice<K, V>
457where
458 K: PartialEq<K2>,
459 V: PartialEq<V2>,
460{
461 fn eq(&self, other: &[(K2, V2)]) -> bool {
462 slice_eq(&self.entries, other, |b, t| b.key == t.0 && b.value == t.1)
463 }
464}
465
466impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V)]
467where
468 K: PartialEq<K2>,
469 V: PartialEq<V2>,
470{
471 fn eq(&self, other: &Slice<K2, V2>) -> bool {
472 slice_eq(self, &other.entries, |t, b| t.0 == b.key && t.1 == b.value)
473 }
474}
475
476impl<K, V, K2, V2, const N: usize> PartialEq<[(K2, V2); N]> for Slice<K, V>
477where
478 K: PartialEq<K2>,
479 V: PartialEq<V2>,
480{
481 fn eq(&self, other: &[(K2, V2); N]) -> bool {
482 <Self as PartialEq<[_]>>::eq(self, other)
483 }
484}
485
486impl<K, V, const N: usize, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V); N]
487where
488 K: PartialEq<K2>,
489 V: PartialEq<V2>,
490{
491 fn eq(&self, other: &Slice<K2, V2>) -> bool {
492 <[_] as PartialEq<_>>::eq(self, other)
493 }
494}
495
496impl<K: Eq, V: Eq> Eq for Slice<K, V> {}
497
498impl<K: PartialOrd, V: PartialOrd> PartialOrd for Slice<K, V> {
499 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
500 self.iter().partial_cmp(other)
501 }
502}
503
504impl<K: Ord, V: Ord> Ord for Slice<K, V> {
505 fn cmp(&self, other: &Self) -> Ordering {
506 self.iter().cmp(other)
507 }
508}
509
510impl<K: Hash, V: Hash> Hash for Slice<K, V> {
511 fn hash<H: Hasher>(&self, state: &mut H) {
512 self.len().hash(state);
513 for (key, value) in self {
514 key.hash(state);
515 value.hash(state);
516 }
517 }
518}
519
520impl<K, V> Index<usize> for Slice<K, V> {
521 type Output = V;
522
523 fn index(&self, index: usize) -> &V {
524 &self.entries[index].value
525 }
526}
527
528impl<K, V> IndexMut<usize> for Slice<K, V> {
529 fn index_mut(&mut self, index: usize) -> &mut V {
530 &mut self.entries[index].value
531 }
532}
533
534macro_rules! impl_index {
538 ($($range:ty),*) => {$(
539 impl<K, V, S> Index<$range> for IndexMap<K, V, S> {
540 type Output = Slice<K, V>;
541
542 fn index(&self, range: $range) -> &Self::Output {
543 Slice::from_slice(&self.as_entries()[range])
544 }
545 }
546
547 impl<K, V, S> IndexMut<$range> for IndexMap<K, V, S> {
548 fn index_mut(&mut self, range: $range) -> &mut Self::Output {
549 Slice::from_mut_slice(&mut self.as_entries_mut()[range])
550 }
551 }
552
553 impl<K, V> Index<$range> for Slice<K, V> {
554 type Output = Slice<K, V>;
555
556 fn index(&self, range: $range) -> &Self {
557 Self::from_slice(&self.entries[range])
558 }
559 }
560
561 impl<K, V> IndexMut<$range> for Slice<K, V> {
562 fn index_mut(&mut self, range: $range) -> &mut Self {
563 Self::from_mut_slice(&mut self.entries[range])
564 }
565 }
566 )*}
567}
568impl_index!(
569 ops::Range<usize>,
570 ops::RangeFrom<usize>,
571 ops::RangeFull,
572 ops::RangeInclusive<usize>,
573 ops::RangeTo<usize>,
574 ops::RangeToInclusive<usize>,
575 (Bound<usize>, Bound<usize>)
576);
577
578#[cfg(test)]
579mod tests {
580 use super::*;
581
582 #[test]
583 fn slice_index() {
584 fn check(
585 vec_slice: &[(i32, i32)],
586 map_slice: &Slice<i32, i32>,
587 sub_slice: &Slice<i32, i32>,
588 ) {
589 assert_eq!(map_slice as *const _, sub_slice as *const _);
590 itertools::assert_equal(
591 vec_slice.iter().copied(),
592 map_slice.iter().map(|(&k, &v)| (k, v)),
593 );
594 itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys());
595 itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values());
596 }
597
598 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
599 let map: IndexMap<i32, i32> = vec.iter().cloned().collect();
600 let slice = map.as_slice();
601
602 check(&vec[..], &map[..], &slice[..]);
604
605 for i in 0usize..10 {
606 assert_eq!(vec[i].1, map[i]);
608 assert_eq!(vec[i].1, slice[i]);
609 assert_eq!(map[&(i as i32)], map[i]);
610 assert_eq!(map[&(i as i32)], slice[i]);
611
612 check(&vec[i..], &map[i..], &slice[i..]);
614
615 check(&vec[..i], &map[..i], &slice[..i]);
617
618 check(&vec[..=i], &map[..=i], &slice[..=i]);
620
621 let bounds = (Bound::Excluded(i), Bound::Unbounded);
623 check(&vec[i + 1..], &map[bounds], &slice[bounds]);
624
625 for j in i..=10 {
626 check(&vec[i..j], &map[i..j], &slice[i..j]);
628 }
629
630 for j in i..10 {
631 check(&vec[i..=j], &map[i..=j], &slice[i..=j]);
633 }
634 }
635 }
636
637 #[test]
638 fn slice_index_mut() {
639 fn check_mut(
640 vec_slice: &[(i32, i32)],
641 map_slice: &mut Slice<i32, i32>,
642 sub_slice: &mut Slice<i32, i32>,
643 ) {
644 assert_eq!(map_slice, sub_slice);
645 itertools::assert_equal(
646 vec_slice.iter().copied(),
647 map_slice.iter_mut().map(|(&k, &mut v)| (k, v)),
648 );
649 itertools::assert_equal(
650 vec_slice.iter().map(|&(_, v)| v),
651 map_slice.values_mut().map(|&mut v| v),
652 );
653 }
654
655 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
656 let mut map: IndexMap<i32, i32> = vec.iter().cloned().collect();
657 let mut map2 = map.clone();
658 let slice = map2.as_mut_slice();
659
660 check_mut(&vec[..], &mut map[..], &mut slice[..]);
662
663 for i in 0usize..10 {
664 assert_eq!(&mut map[i], &mut slice[i]);
666
667 check_mut(&vec[i..], &mut map[i..], &mut slice[i..]);
669
670 check_mut(&vec[..i], &mut map[..i], &mut slice[..i]);
672
673 check_mut(&vec[..=i], &mut map[..=i], &mut slice[..=i]);
675
676 let bounds = (Bound::Excluded(i), Bound::Unbounded);
678 check_mut(&vec[i + 1..], &mut map[bounds], &mut slice[bounds]);
679
680 for j in i..=10 {
681 check_mut(&vec[i..j], &mut map[i..j], &mut slice[i..j]);
683 }
684
685 for j in i..10 {
686 check_mut(&vec[i..=j], &mut map[i..=j], &mut slice[i..=j]);
688 }
689 }
690 }
691
692 #[test]
693 fn slice_new() {
694 let slice: &Slice<i32, i32> = Slice::new();
695 assert!(slice.is_empty());
696 assert_eq!(slice.len(), 0);
697 }
698
699 #[test]
700 fn slice_new_mut() {
701 let slice: &mut Slice<i32, i32> = Slice::new_mut();
702 assert!(slice.is_empty());
703 assert_eq!(slice.len(), 0);
704 }
705
706 #[test]
707 fn slice_get_index_mut() {
708 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
709 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
710
711 {
712 let (key, value) = slice.get_index_mut(0).unwrap();
713 assert_eq!(*key, 0);
714 assert_eq!(*value, 0);
715
716 *value = 11;
717 }
718
719 assert_eq!(slice[0], 11);
720
721 {
722 let result = slice.get_index_mut(11);
723 assert!(result.is_none());
724 }
725 }
726
727 #[test]
728 fn slice_split_first() {
729 let slice: &mut Slice<i32, i32> = Slice::new_mut();
730 let result = slice.split_first();
731 assert!(result.is_none());
732
733 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
734 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
735
736 {
737 let (first, rest) = slice.split_first().unwrap();
738 assert_eq!(first, (&0, &0));
739 assert_eq!(rest.len(), 9);
740 }
741 assert_eq!(slice.len(), 10);
742 }
743
744 #[test]
745 fn slice_split_first_mut() {
746 let slice: &mut Slice<i32, i32> = Slice::new_mut();
747 let result = slice.split_first_mut();
748 assert!(result.is_none());
749
750 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
751 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
752
753 {
754 let (first, rest) = slice.split_first_mut().unwrap();
755 assert_eq!(first, (&0, &mut 0));
756 assert_eq!(rest.len(), 9);
757
758 *first.1 = 11;
759 }
760 assert_eq!(slice.len(), 10);
761 assert_eq!(slice[0], 11);
762 }
763
764 #[test]
765 fn slice_split_last() {
766 let slice: &mut Slice<i32, i32> = Slice::new_mut();
767 let result = slice.split_last();
768 assert!(result.is_none());
769
770 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
771 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
772
773 {
774 let (last, rest) = slice.split_last().unwrap();
775 assert_eq!(last, (&9, &81));
776 assert_eq!(rest.len(), 9);
777 }
778 assert_eq!(slice.len(), 10);
779 }
780
781 #[test]
782 fn slice_split_last_mut() {
783 let slice: &mut Slice<i32, i32> = Slice::new_mut();
784 let result = slice.split_last_mut();
785 assert!(result.is_none());
786
787 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
788 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
789
790 {
791 let (last, rest) = slice.split_last_mut().unwrap();
792 assert_eq!(last, (&9, &mut 81));
793 assert_eq!(rest.len(), 9);
794
795 *last.1 = 100;
796 }
797
798 assert_eq!(slice.len(), 10);
799 assert_eq!(slice[slice.len() - 1], 100);
800 }
801
802 #[test]
803 fn slice_get_range() {
804 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
805 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
806 let subslice = slice.get_range(3..6).unwrap();
807 assert_eq!(subslice.len(), 3);
808 assert_eq!(subslice, &[(3, 9), (4, 16), (5, 25)]);
809 }
810}