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