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