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