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.is_sorted_by_key(|k, _| k)
269 }
270
271 #[inline]
273 pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool
274 where
275 F: FnMut(&'a K, &'a V, &'a K, &'a V) -> bool,
276 {
277 let mut iter = self.entries.iter();
280 match iter.next() {
281 Some(mut prev) => iter.all(move |next| {
282 let sorted = cmp(&prev.key, &prev.value, &next.key, &next.value);
283 prev = next;
284 sorted
285 }),
286 None => true,
287 }
288 }
289
290 #[inline]
292 pub fn is_sorted_by_key<'a, F, T>(&'a self, mut sort_key: F) -> bool
293 where
294 F: FnMut(&'a K, &'a V) -> T,
295 T: PartialOrd,
296 {
297 let mut iter = self.entries.iter().map(move |a| sort_key(&a.key, &a.value));
300 match iter.next() {
301 Some(mut prev) => iter.all(move |next| {
302 let sorted = prev <= next;
303 prev = next;
304 sorted
305 }),
306 None => true,
307 }
308 }
309
310 #[must_use]
317 pub fn partition_point<P>(&self, mut pred: P) -> usize
318 where
319 P: FnMut(&K, &V) -> bool,
320 {
321 self.entries
322 .partition_point(move |a| pred(&a.key, &a.value))
323 }
324
325 pub fn get_disjoint_mut<const N: usize>(
329 &mut self,
330 indices: [usize; N],
331 ) -> Result<[(&K, &mut V); N], GetDisjointMutError> {
332 let indices = indices.map(Some);
333 let key_values = self.get_disjoint_opt_mut(indices)?;
334 Ok(key_values.map(Option::unwrap))
335 }
336
337 #[allow(unsafe_code)]
338 pub(crate) fn get_disjoint_opt_mut<const N: usize>(
339 &mut self,
340 indices: [Option<usize>; N],
341 ) -> Result<[Option<(&K, &mut V)>; N], GetDisjointMutError> {
342 let len = self.len();
344 for i in 0..N {
345 if let Some(idx) = indices[i] {
346 if idx >= len {
347 return Err(GetDisjointMutError::IndexOutOfBounds);
348 } else if indices[..i].contains(&Some(idx)) {
349 return Err(GetDisjointMutError::OverlappingIndices);
350 }
351 }
352 }
353
354 let entries_ptr = self.entries.as_mut_ptr();
355 let out = indices.map(|idx_opt| {
356 match idx_opt {
357 Some(idx) => {
358 let kv = unsafe { (*(entries_ptr.add(idx))).ref_mut() };
361 Some(kv)
362 }
363 None => None,
364 }
365 });
366
367 Ok(out)
368 }
369}
370
371impl<'a, K, V> IntoIterator for &'a Slice<K, V> {
372 type IntoIter = Iter<'a, K, V>;
373 type Item = (&'a K, &'a V);
374
375 fn into_iter(self) -> Self::IntoIter {
376 self.iter()
377 }
378}
379
380impl<'a, K, V> IntoIterator for &'a mut Slice<K, V> {
381 type IntoIter = IterMut<'a, K, V>;
382 type Item = (&'a K, &'a mut V);
383
384 fn into_iter(self) -> Self::IntoIter {
385 self.iter_mut()
386 }
387}
388
389impl<K, V> IntoIterator for Box<Slice<K, V>> {
390 type IntoIter = IntoIter<K, V>;
391 type Item = (K, V);
392
393 fn into_iter(self) -> Self::IntoIter {
394 IntoIter::new(self.into_entries())
395 }
396}
397
398impl<K, V> Default for &'_ Slice<K, V> {
399 fn default() -> Self {
400 Slice::from_slice(&[])
401 }
402}
403
404impl<K, V> Default for &'_ mut Slice<K, V> {
405 fn default() -> Self {
406 Slice::from_mut_slice(&mut [])
407 }
408}
409
410impl<K, V> Default for Box<Slice<K, V>> {
411 fn default() -> Self {
412 Slice::from_boxed(Box::default())
413 }
414}
415
416impl<K: Clone, V: Clone> Clone for Box<Slice<K, V>> {
417 fn clone(&self) -> Self {
418 Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
419 }
420}
421
422impl<K: Copy, V: Copy> From<&Slice<K, V>> for Box<Slice<K, V>> {
423 fn from(slice: &Slice<K, V>) -> Self {
424 Slice::from_boxed(Box::from(&slice.entries))
425 }
426}
427
428impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Slice<K, V> {
429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430 f.debug_list().entries(self).finish()
431 }
432}
433
434impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for Slice<K, V>
435where
436 K: PartialEq<K2>,
437 V: PartialEq<V2>,
438{
439 fn eq(&self, other: &Slice<K2, V2>) -> bool {
440 slice_eq(&self.entries, &other.entries, |b1, b2| {
441 b1.key == b2.key && b1.value == b2.value
442 })
443 }
444}
445
446impl<K, V, K2, V2> PartialEq<[(K2, V2)]> for Slice<K, V>
447where
448 K: PartialEq<K2>,
449 V: PartialEq<V2>,
450{
451 fn eq(&self, other: &[(K2, V2)]) -> bool {
452 slice_eq(&self.entries, other, |b, t| b.key == t.0 && b.value == t.1)
453 }
454}
455
456impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V)]
457where
458 K: PartialEq<K2>,
459 V: PartialEq<V2>,
460{
461 fn eq(&self, other: &Slice<K2, V2>) -> bool {
462 slice_eq(self, &other.entries, |t, b| t.0 == b.key && t.1 == b.value)
463 }
464}
465
466impl<K, V, K2, V2, const N: usize> PartialEq<[(K2, V2); N]> for Slice<K, V>
467where
468 K: PartialEq<K2>,
469 V: PartialEq<V2>,
470{
471 fn eq(&self, other: &[(K2, V2); N]) -> bool {
472 <Self as PartialEq<[_]>>::eq(self, other)
473 }
474}
475
476impl<K, V, const N: usize, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V); N]
477where
478 K: PartialEq<K2>,
479 V: PartialEq<V2>,
480{
481 fn eq(&self, other: &Slice<K2, V2>) -> bool {
482 <[_] as PartialEq<_>>::eq(self, other)
483 }
484}
485
486impl<K: Eq, V: Eq> Eq for Slice<K, V> {}
487
488impl<K: PartialOrd, V: PartialOrd> PartialOrd for Slice<K, V> {
489 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
490 self.iter().partial_cmp(other)
491 }
492}
493
494impl<K: Ord, V: Ord> Ord for Slice<K, V> {
495 fn cmp(&self, other: &Self) -> Ordering {
496 self.iter().cmp(other)
497 }
498}
499
500impl<K: Hash, V: Hash> Hash for Slice<K, V> {
501 fn hash<H: Hasher>(&self, state: &mut H) {
502 self.len().hash(state);
503 for (key, value) in self {
504 key.hash(state);
505 value.hash(state);
506 }
507 }
508}
509
510impl<K, V> Index<usize> for Slice<K, V> {
511 type Output = V;
512
513 fn index(&self, index: usize) -> &V {
514 &self.entries[index].value
515 }
516}
517
518impl<K, V> IndexMut<usize> for Slice<K, V> {
519 fn index_mut(&mut self, index: usize) -> &mut V {
520 &mut self.entries[index].value
521 }
522}
523
524macro_rules! impl_index {
528 ($($range:ty),*) => {$(
529 impl<K, V, S> Index<$range> for IndexMap<K, V, S> {
530 type Output = Slice<K, V>;
531
532 fn index(&self, range: $range) -> &Self::Output {
533 Slice::from_slice(&self.as_entries()[range])
534 }
535 }
536
537 impl<K, V, S> IndexMut<$range> for IndexMap<K, V, S> {
538 fn index_mut(&mut self, range: $range) -> &mut Self::Output {
539 Slice::from_mut_slice(&mut self.as_entries_mut()[range])
540 }
541 }
542
543 impl<K, V> Index<$range> for Slice<K, V> {
544 type Output = Slice<K, V>;
545
546 fn index(&self, range: $range) -> &Self {
547 Self::from_slice(&self.entries[range])
548 }
549 }
550
551 impl<K, V> IndexMut<$range> for Slice<K, V> {
552 fn index_mut(&mut self, range: $range) -> &mut Self {
553 Self::from_mut_slice(&mut self.entries[range])
554 }
555 }
556 )*}
557}
558impl_index!(
559 ops::Range<usize>,
560 ops::RangeFrom<usize>,
561 ops::RangeFull,
562 ops::RangeInclusive<usize>,
563 ops::RangeTo<usize>,
564 ops::RangeToInclusive<usize>,
565 (Bound<usize>, Bound<usize>)
566);
567
568#[cfg(test)]
569mod tests {
570 use super::*;
571
572 #[test]
573 fn slice_index() {
574 fn check(
575 vec_slice: &[(i32, i32)],
576 map_slice: &Slice<i32, i32>,
577 sub_slice: &Slice<i32, i32>,
578 ) {
579 assert_eq!(map_slice as *const _, sub_slice as *const _);
580 itertools::assert_equal(
581 vec_slice.iter().copied(),
582 map_slice.iter().map(|(&k, &v)| (k, v)),
583 );
584 itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys());
585 itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values());
586 }
587
588 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
589 let map: IndexMap<i32, i32> = vec.iter().cloned().collect();
590 let slice = map.as_slice();
591
592 check(&vec[..], &map[..], &slice[..]);
594
595 for i in 0usize..10 {
596 assert_eq!(vec[i].1, map[i]);
598 assert_eq!(vec[i].1, slice[i]);
599 assert_eq!(map[&(i as i32)], map[i]);
600 assert_eq!(map[&(i as i32)], slice[i]);
601
602 check(&vec[i..], &map[i..], &slice[i..]);
604
605 check(&vec[..i], &map[..i], &slice[..i]);
607
608 check(&vec[..=i], &map[..=i], &slice[..=i]);
610
611 let bounds = (Bound::Excluded(i), Bound::Unbounded);
613 check(&vec[i + 1..], &map[bounds], &slice[bounds]);
614
615 for j in i..=10 {
616 check(&vec[i..j], &map[i..j], &slice[i..j]);
618 }
619
620 for j in i..10 {
621 check(&vec[i..=j], &map[i..=j], &slice[i..=j]);
623 }
624 }
625 }
626
627 #[test]
628 fn slice_index_mut() {
629 fn check_mut(
630 vec_slice: &[(i32, i32)],
631 map_slice: &mut Slice<i32, i32>,
632 sub_slice: &mut Slice<i32, i32>,
633 ) {
634 assert_eq!(map_slice, sub_slice);
635 itertools::assert_equal(
636 vec_slice.iter().copied(),
637 map_slice.iter_mut().map(|(&k, &mut v)| (k, v)),
638 );
639 itertools::assert_equal(
640 vec_slice.iter().map(|&(_, v)| v),
641 map_slice.values_mut().map(|&mut v| v),
642 );
643 }
644
645 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
646 let mut map: IndexMap<i32, i32> = vec.iter().cloned().collect();
647 let mut map2 = map.clone();
648 let slice = map2.as_mut_slice();
649
650 check_mut(&vec[..], &mut map[..], &mut slice[..]);
652
653 for i in 0usize..10 {
654 assert_eq!(&mut map[i], &mut slice[i]);
656
657 check_mut(&vec[i..], &mut map[i..], &mut slice[i..]);
659
660 check_mut(&vec[..i], &mut map[..i], &mut slice[..i]);
662
663 check_mut(&vec[..=i], &mut map[..=i], &mut slice[..=i]);
665
666 let bounds = (Bound::Excluded(i), Bound::Unbounded);
668 check_mut(&vec[i + 1..], &mut map[bounds], &mut slice[bounds]);
669
670 for j in i..=10 {
671 check_mut(&vec[i..j], &mut map[i..j], &mut slice[i..j]);
673 }
674
675 for j in i..10 {
676 check_mut(&vec[i..=j], &mut map[i..=j], &mut slice[i..=j]);
678 }
679 }
680 }
681
682 #[test]
683 fn slice_new() {
684 let slice: &Slice<i32, i32> = Slice::new();
685 assert!(slice.is_empty());
686 assert_eq!(slice.len(), 0);
687 }
688
689 #[test]
690 fn slice_new_mut() {
691 let slice: &mut Slice<i32, i32> = Slice::new_mut();
692 assert!(slice.is_empty());
693 assert_eq!(slice.len(), 0);
694 }
695
696 #[test]
697 fn slice_get_index_mut() {
698 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
699 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
700
701 {
702 let (key, value) = slice.get_index_mut(0).unwrap();
703 assert_eq!(*key, 0);
704 assert_eq!(*value, 0);
705
706 *value = 11;
707 }
708
709 assert_eq!(slice[0], 11);
710
711 {
712 let result = slice.get_index_mut(11);
713 assert!(result.is_none());
714 }
715 }
716
717 #[test]
718 fn slice_split_first() {
719 let slice: &mut Slice<i32, i32> = Slice::new_mut();
720 let result = slice.split_first();
721 assert!(result.is_none());
722
723 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
724 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
725
726 {
727 let (first, rest) = slice.split_first().unwrap();
728 assert_eq!(first, (&0, &0));
729 assert_eq!(rest.len(), 9);
730 }
731 assert_eq!(slice.len(), 10);
732 }
733
734 #[test]
735 fn slice_split_first_mut() {
736 let slice: &mut Slice<i32, i32> = Slice::new_mut();
737 let result = slice.split_first_mut();
738 assert!(result.is_none());
739
740 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
741 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
742
743 {
744 let (first, rest) = slice.split_first_mut().unwrap();
745 assert_eq!(first, (&0, &mut 0));
746 assert_eq!(rest.len(), 9);
747
748 *first.1 = 11;
749 }
750 assert_eq!(slice.len(), 10);
751 assert_eq!(slice[0], 11);
752 }
753
754 #[test]
755 fn slice_split_last() {
756 let slice: &mut Slice<i32, i32> = Slice::new_mut();
757 let result = slice.split_last();
758 assert!(result.is_none());
759
760 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
761 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
762
763 {
764 let (last, rest) = slice.split_last().unwrap();
765 assert_eq!(last, (&9, &81));
766 assert_eq!(rest.len(), 9);
767 }
768 assert_eq!(slice.len(), 10);
769 }
770
771 #[test]
772 fn slice_split_last_mut() {
773 let slice: &mut Slice<i32, i32> = Slice::new_mut();
774 let result = slice.split_last_mut();
775 assert!(result.is_none());
776
777 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
778 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
779
780 {
781 let (last, rest) = slice.split_last_mut().unwrap();
782 assert_eq!(last, (&9, &mut 81));
783 assert_eq!(rest.len(), 9);
784
785 *last.1 = 100;
786 }
787
788 assert_eq!(slice.len(), 10);
789 assert_eq!(slice[slice.len() - 1], 100);
790 }
791
792 #[test]
793 fn slice_get_range() {
794 let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
795 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
796 let subslice = slice.get_range(3..6).unwrap();
797 assert_eq!(subslice.len(), 3);
798 assert_eq!(subslice, &[(3, 9), (4, 16), (5, 25)]);
799 }
800}