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