1use super::{Bucket, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values, ValuesMut};
2use crate::util::{slice_eq, try_simplify_range};
3use crate::GetDisjointMutError;
4
5use alloc::boxed::Box;
6use alloc::collections::VecDeque;
7use core::cmp::Ordering;
8use core::fmt;
9use core::hash::{Hash, Hasher};
10use core::ops::{self, Bound, Index, IndexMut, RangeBounds};
11
12#[repr(transparent)]
17pub struct Slice<K, V> {
18 pub(crate) entries: [Bucket<K, V>],
19}
20
21#[allow(unsafe_code)]
24impl<K, V> Slice<K, V> {
25 pub(super) const fn from_slice(entries: &[Bucket<K, V>]) -> &Self {
26 unsafe { &*(entries as *const [Bucket<K, V>] as *const Self) }
27 }
28
29 pub(super) fn from_mut_slice(entries: &mut [Bucket<K, V>]) -> &mut Self {
30 unsafe { &mut *(entries as *mut [Bucket<K, V>] as *mut Self) }
31 }
32
33 pub(super) fn from_boxed(entries: Box<[Bucket<K, V>]>) -> Box<Self> {
34 unsafe { Box::from_raw(Box::into_raw(entries) as *mut Self) }
35 }
36
37 fn into_boxed(self: Box<Self>) -> Box<[Bucket<K, V>]> {
38 unsafe { Box::from_raw(Box::into_raw(self) as *mut [Bucket<K, V>]) }
39 }
40}
41
42impl<K, V> Slice<K, V> {
43 pub(crate) fn into_entries(self: Box<Self>) -> VecDeque<Bucket<K, V>> {
44 self.into_boxed().into_vec().into()
45 }
46
47 pub const fn new<'a>() -> &'a Self {
49 Self::from_slice(&[])
50 }
51
52 pub fn new_mut<'a>() -> &'a mut Self {
54 Self::from_mut_slice(&mut [])
55 }
56
57 #[inline]
59 pub const fn len(&self) -> usize {
60 self.entries.len()
61 }
62
63 #[inline]
65 pub const fn is_empty(&self) -> bool {
66 self.entries.is_empty()
67 }
68
69 pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
73 self.entries.get(index).map(Bucket::refs)
74 }
75
76 pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
80 self.entries.get_mut(index).map(Bucket::ref_mut)
81 }
82
83 pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Self> {
87 let range = try_simplify_range(range, self.entries.len())?;
88 self.entries.get(range).map(Slice::from_slice)
89 }
90
91 pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Self> {
95 let range = try_simplify_range(range, self.entries.len())?;
96 self.entries.get_mut(range).map(Slice::from_mut_slice)
97 }
98
99 pub fn first(&self) -> Option<(&K, &V)> {
101 self.entries.first().map(Bucket::refs)
102 }
103
104 pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
106 self.entries.first_mut().map(Bucket::ref_mut)
107 }
108
109 pub fn last(&self) -> Option<(&K, &V)> {
111 self.entries.last().map(Bucket::refs)
112 }
113
114 pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
116 self.entries.last_mut().map(Bucket::ref_mut)
117 }
118
119 #[track_caller]
124 pub fn split_at(&self, index: usize) -> (&Self, &Self) {
125 let (first, second) = self.entries.split_at(index);
126 (Self::from_slice(first), Self::from_slice(second))
127 }
128
129 #[track_caller]
134 pub fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) {
135 let (first, second) = self.entries.split_at_mut(index);
136 (Self::from_mut_slice(first), Self::from_mut_slice(second))
137 }
138
139 pub fn split_at_checked(&self, index: usize) -> Option<(&Self, &Self)> {
143 let (first, second) = self.entries.split_at_checked(index)?;
144 Some((Self::from_slice(first), Self::from_slice(second)))
145 }
146
147 pub fn split_at_mut_checked(&mut self, index: usize) -> Option<(&mut Self, &mut Self)> {
151 let (first, second) = self.entries.split_at_mut_checked(index)?;
152 Some((Self::from_mut_slice(first), Self::from_mut_slice(second)))
153 }
154
155 pub fn split_first(&self) -> Option<((&K, &V), &Self)> {
158 if let [first, rest @ ..] = &self.entries {
159 Some((first.refs(), Self::from_slice(rest)))
160 } else {
161 None
162 }
163 }
164
165 pub fn split_first_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
168 if let [first, rest @ ..] = &mut self.entries {
169 Some((first.ref_mut(), Self::from_mut_slice(rest)))
170 } else {
171 None
172 }
173 }
174
175 pub fn split_last(&self) -> Option<((&K, &V), &Self)> {
178 if let [rest @ .., last] = &self.entries {
179 Some((last.refs(), Self::from_slice(rest)))
180 } else {
181 None
182 }
183 }
184
185 pub fn split_last_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
188 if let [rest @ .., last] = &mut self.entries {
189 Some((last.ref_mut(), Self::from_mut_slice(rest)))
190 } else {
191 None
192 }
193 }
194
195 pub fn iter(&self) -> Iter<'_, K, V> {
197 Iter::from_slice(&self.entries)
198 }
199
200 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
202 IterMut::from_mut_slice(&mut self.entries)
203 }
204
205 pub fn keys(&self) -> Keys<'_, K, V> {
207 Keys::from_slice(&self.entries)
208 }
209
210 pub fn into_keys(self: Box<Self>) -> IntoKeys<K, V> {
212 IntoKeys::new(self.into_entries())
213 }
214
215 pub fn values(&self) -> Values<'_, K, V> {
217 Values::from_slice(&self.entries)
218 }
219
220 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
222 ValuesMut::from_mut_slice(&mut self.entries)
223 }
224
225 pub fn into_values(self: Box<Self>) -> IntoValues<K, V> {
227 IntoValues::new(self.into_entries())
228 }
229
230 pub fn binary_search_keys(&self, x: &K) -> Result<usize, usize>
239 where
240 K: Ord,
241 {
242 self.binary_search_by(|p, _| p.cmp(x))
243 }
244
245 #[inline]
252 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
253 where
254 F: FnMut(&'a K, &'a V) -> Ordering,
255 {
256 self.entries.binary_search_by(move |a| f(&a.key, &a.value))
257 }
258
259 #[inline]
266 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
267 where
268 F: FnMut(&'a K, &'a V) -> B,
269 B: Ord,
270 {
271 self.binary_search_by(|k, v| f(k, v).cmp(b))
272 }
273
274 #[inline]
276 pub fn is_sorted(&self) -> bool
277 where
278 K: PartialOrd,
279 {
280 self.entries.is_sorted_by(|a, b| a.key <= b.key)
281 }
282
283 #[inline]
285 pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool
286 where
287 F: FnMut(&'a K, &'a V, &'a K, &'a V) -> bool,
288 {
289 self.entries
290 .is_sorted_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value))
291 }
292
293 #[inline]
295 pub fn is_sorted_by_key<'a, F, T>(&'a self, mut sort_key: F) -> bool
296 where
297 F: FnMut(&'a K, &'a V) -> T,
298 T: PartialOrd,
299 {
300 self.entries
301 .is_sorted_by_key(move |a| sort_key(&a.key, &a.value))
302 }
303
304 #[must_use]
311 pub fn partition_point<P>(&self, mut pred: P) -> usize
312 where
313 P: FnMut(&K, &V) -> bool,
314 {
315 self.entries
316 .partition_point(move |a| pred(&a.key, &a.value))
317 }
318
319 pub fn get_disjoint_mut<const N: usize>(
323 &mut self,
324 indices: [usize; N],
325 ) -> Result<[(&K, &mut V); N], GetDisjointMutError> {
326 let indices = indices.map(Some);
327 let empty_tail = Self::new_mut();
328 let key_values = Self::get_disjoint_opt_mut(self, empty_tail, indices)?;
329 Ok(key_values.map(Option::unwrap))
330 }
331
332 #[allow(unsafe_code)]
333 pub(crate) fn get_disjoint_opt_mut<'a, const N: usize>(
334 head: &mut Self,
335 tail: &mut Self,
336 indices: [Option<usize>; N],
337 ) -> Result<[Option<(&'a K, &'a mut V)>; N], GetDisjointMutError> {
338 let mid = head.len();
339 let len = mid + tail.len();
340
341 for i in 0..N {
343 if let Some(idx) = indices[i] {
344 if idx >= len {
345 return Err(GetDisjointMutError::IndexOutOfBounds);
346 } else if indices[..i].contains(&Some(idx)) {
347 return Err(GetDisjointMutError::OverlappingIndices);
348 }
349 }
350 }
351
352 let head_ptr = head.entries.as_mut_ptr();
353 let tail_ptr = tail.entries.as_mut_ptr();
354 let out = indices.map(|idx_opt| {
355 match idx_opt {
356 Some(idx) => {
357 unsafe {
360 let ptr = match idx.checked_sub(mid) {
361 None => head_ptr.add(idx),
362 Some(tidx) => tail_ptr.add(tidx),
363 };
364 Some((*ptr).ref_mut())
365 }
366 }
367 None => None,
368 }
369 });
370
371 Ok(out)
372 }
373}
374
375impl<'a, K, V> IntoIterator for &'a Slice<K, V> {
376 type IntoIter = Iter<'a, K, V>;
377 type Item = (&'a K, &'a V);
378
379 fn into_iter(self) -> Self::IntoIter {
380 self.iter()
381 }
382}
383
384impl<'a, K, V> IntoIterator for &'a mut Slice<K, V> {
385 type IntoIter = IterMut<'a, K, V>;
386 type Item = (&'a K, &'a mut V);
387
388 fn into_iter(self) -> Self::IntoIter {
389 self.iter_mut()
390 }
391}
392
393impl<K, V> IntoIterator for Box<Slice<K, V>> {
394 type IntoIter = IntoIter<K, V>;
395 type Item = (K, V);
396
397 fn into_iter(self) -> Self::IntoIter {
398 IntoIter::new(self.into_entries())
399 }
400}
401
402impl<K, V> Default for &'_ Slice<K, V> {
403 fn default() -> Self {
404 Slice::from_slice(&[])
405 }
406}
407
408impl<K, V> Default for &'_ mut Slice<K, V> {
409 fn default() -> Self {
410 Slice::from_mut_slice(&mut [])
411 }
412}
413
414impl<K, V> Default for Box<Slice<K, V>> {
415 fn default() -> Self {
416 Slice::from_boxed(Box::default())
417 }
418}
419
420impl<K: Clone, V: Clone> Clone for Box<Slice<K, V>> {
421 fn clone(&self) -> Self {
422 Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
423 }
424}
425
426impl<K: Copy, V: Copy> From<&Slice<K, V>> for Box<Slice<K, V>> {
427 fn from(slice: &Slice<K, V>) -> Self {
428 Slice::from_boxed(Box::from(&slice.entries))
429 }
430}
431
432impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Slice<K, V> {
433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434 f.debug_list().entries(self).finish()
435 }
436}
437
438impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for Slice<K, V>
439where
440 K: PartialEq<K2>,
441 V: PartialEq<V2>,
442{
443 fn eq(&self, other: &Slice<K2, V2>) -> bool {
444 slice_eq(&self.entries, &other.entries, |b1, b2| {
445 b1.key == b2.key && b1.value == b2.value
446 })
447 }
448}
449
450impl<K, V, K2, V2> PartialEq<[(K2, V2)]> for Slice<K, V>
451where
452 K: PartialEq<K2>,
453 V: PartialEq<V2>,
454{
455 fn eq(&self, other: &[(K2, V2)]) -> bool {
456 slice_eq(&self.entries, other, |b, t| b.key == t.0 && b.value == t.1)
457 }
458}
459
460impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V)]
461where
462 K: PartialEq<K2>,
463 V: PartialEq<V2>,
464{
465 fn eq(&self, other: &Slice<K2, V2>) -> bool {
466 slice_eq(self, &other.entries, |t, b| t.0 == b.key && t.1 == b.value)
467 }
468}
469
470impl<K, V, K2, V2, const N: usize> PartialEq<[(K2, V2); N]> for Slice<K, V>
471where
472 K: PartialEq<K2>,
473 V: PartialEq<V2>,
474{
475 fn eq(&self, other: &[(K2, V2); N]) -> bool {
476 <Self as PartialEq<[_]>>::eq(self, other)
477 }
478}
479
480impl<K, V, const N: usize, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V); N]
481where
482 K: PartialEq<K2>,
483 V: PartialEq<V2>,
484{
485 fn eq(&self, other: &Slice<K2, V2>) -> bool {
486 <[_] as PartialEq<_>>::eq(self, other)
487 }
488}
489
490impl<K: Eq, V: Eq> Eq for Slice<K, V> {}
491
492impl<K: PartialOrd, V: PartialOrd> PartialOrd for Slice<K, V> {
493 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
494 self.iter().partial_cmp(other)
495 }
496}
497
498impl<K: Ord, V: Ord> Ord for Slice<K, V> {
499 fn cmp(&self, other: &Self) -> Ordering {
500 self.iter().cmp(other)
501 }
502}
503
504impl<K: Hash, V: Hash> Hash for Slice<K, V> {
505 fn hash<H: Hasher>(&self, state: &mut H) {
506 self.len().hash(state);
507 for (key, value) in self {
508 key.hash(state);
509 value.hash(state);
510 }
511 }
512}
513
514impl<K, V> Index<usize> for Slice<K, V> {
515 type Output = V;
516
517 fn index(&self, index: usize) -> &V {
518 &self.entries[index].value
519 }
520}
521
522impl<K, V> IndexMut<usize> for Slice<K, V> {
523 fn index_mut(&mut self, index: usize) -> &mut V {
524 &mut self.entries[index].value
525 }
526}
527
528macro_rules! impl_index {
532 ($($range:ty),*) => {$(
533 impl<K, V> Index<$range> for Slice<K, V> {
534 type Output = Slice<K, V>;
535
536 fn index(&self, range: $range) -> &Self {
537 Self::from_slice(&self.entries[range])
538 }
539 }
540
541 impl<K, V> IndexMut<$range> for Slice<K, V> {
542 fn index_mut(&mut self, range: $range) -> &mut Self {
543 Self::from_mut_slice(&mut self.entries[range])
544 }
545 }
546 )*}
547}
548impl_index!(
549 ops::Range<usize>,
550 ops::RangeFrom<usize>,
551 ops::RangeFull,
552 ops::RangeInclusive<usize>,
553 ops::RangeTo<usize>,
554 ops::RangeToInclusive<usize>,
555 (Bound<usize>, Bound<usize>)
556);
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561 use crate::RingMap;
562 use alloc::vec::Vec;
563
564 #[test]
565 fn slice_index() {
566 fn check(vec_slice: &[(i32, i32)], map_slice: &Slice<i32, i32>) {
567 itertools::assert_equal(
568 vec_slice.iter().copied(),
569 map_slice.iter().map(|(&k, &v)| (k, v)),
570 );
571 itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys());
572 itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values());
573 }
574
575 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
576 let map: RingMap<i32, i32> = vec.iter().cloned().collect();
577 let (slice, tail) = map.as_slices();
578 assert!(tail.is_empty());
579
580 check(&vec[..], &slice[..]);
582
583 for i in 0usize..10 {
584 assert_eq!(vec[i].1, map[i]);
586 assert_eq!(vec[i].1, slice[i]);
587 assert_eq!(map[&(i as i32)], map[i]);
588 assert_eq!(map[&(i as i32)], slice[i]);
589
590 check(&vec[i..], &slice[i..]);
592
593 check(&vec[..i], &slice[..i]);
595
596 check(&vec[..=i], &slice[..=i]);
598
599 let bounds = (Bound::Excluded(i), Bound::Unbounded);
601 check(&vec[i + 1..], &slice[bounds]);
602
603 for j in i..=10 {
604 check(&vec[i..j], &slice[i..j]);
606 }
607
608 for j in i..10 {
609 check(&vec[i..=j], &slice[i..=j]);
611 }
612 }
613 }
614
615 fn as_mut_slice<K, V>(map: &mut RingMap<K, V>) -> &mut Slice<K, V> {
616 let (slice, tail) = map.as_mut_slices();
617 assert!(tail.is_empty());
618 slice
619 }
620
621 #[test]
622 fn slice_index_mut() {
623 fn check_mut(vec_slice: &[(i32, i32)], map_slice: &mut Slice<i32, i32>) {
624 itertools::assert_equal(
625 vec_slice.iter().copied(),
626 map_slice.iter_mut().map(|(&k, &mut v)| (k, v)),
627 );
628 itertools::assert_equal(
629 vec_slice.iter().map(|&(_, v)| v),
630 map_slice.values_mut().map(|&mut v| v),
631 );
632 }
633
634 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
635 let mut map: RingMap<i32, i32> = vec.iter().cloned().collect();
636 let mut map2 = map.clone();
637 let slice = as_mut_slice(&mut map2);
638
639 check_mut(&vec[..], &mut slice[..]);
641
642 for i in 0usize..10 {
643 assert_eq!(&mut map[i], &mut slice[i]);
645
646 check_mut(&vec[i..], &mut slice[i..]);
648
649 check_mut(&vec[..i], &mut slice[..i]);
651
652 check_mut(&vec[..=i], &mut slice[..=i]);
654
655 let bounds = (Bound::Excluded(i), Bound::Unbounded);
657 check_mut(&vec[i + 1..], &mut slice[bounds]);
658
659 for j in i..=10 {
660 check_mut(&vec[i..j], &mut slice[i..j]);
662 }
663
664 for j in i..10 {
665 check_mut(&vec[i..=j], &mut slice[i..=j]);
667 }
668 }
669 }
670
671 #[test]
672 fn slice_new() {
673 let slice: &Slice<i32, i32> = Slice::new();
674 assert!(slice.is_empty());
675 assert_eq!(slice.len(), 0);
676 }
677
678 #[test]
679 fn slice_new_mut() {
680 let slice: &mut Slice<i32, i32> = Slice::new_mut();
681 assert!(slice.is_empty());
682 assert_eq!(slice.len(), 0);
683 }
684
685 #[test]
686 fn slice_get_index_mut() {
687 let mut map: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
688 let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
689
690 {
691 let (key, value) = slice.get_index_mut(0).unwrap();
692 assert_eq!(*key, 0);
693 assert_eq!(*value, 0);
694
695 *value = 11;
696 }
697
698 assert_eq!(slice[0], 11);
699
700 {
701 let result = slice.get_index_mut(11);
702 assert!(result.is_none());
703 }
704 }
705
706 #[test]
707 fn slice_split_first() {
708 let slice: &mut Slice<i32, i32> = Slice::new_mut();
709 let result = slice.split_first();
710 assert!(result.is_none());
711
712 let mut map: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
713 let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
714
715 {
716 let (first, rest) = slice.split_first().unwrap();
717 assert_eq!(first, (&0, &0));
718 assert_eq!(rest.len(), 9);
719 }
720 assert_eq!(slice.len(), 10);
721 }
722
723 #[test]
724 fn slice_split_first_mut() {
725 let slice: &mut Slice<i32, i32> = Slice::new_mut();
726 let result = slice.split_first_mut();
727 assert!(result.is_none());
728
729 let mut map: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
730 let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
731
732 {
733 let (first, rest) = slice.split_first_mut().unwrap();
734 assert_eq!(first, (&0, &mut 0));
735 assert_eq!(rest.len(), 9);
736
737 *first.1 = 11;
738 }
739 assert_eq!(slice.len(), 10);
740 assert_eq!(slice[0], 11);
741 }
742
743 #[test]
744 fn slice_split_last() {
745 let slice: &mut Slice<i32, i32> = Slice::new_mut();
746 let result = slice.split_last();
747 assert!(result.is_none());
748
749 let mut map: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
750 let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
751
752 {
753 let (last, rest) = slice.split_last().unwrap();
754 assert_eq!(last, (&9, &81));
755 assert_eq!(rest.len(), 9);
756 }
757 assert_eq!(slice.len(), 10);
758 }
759
760 #[test]
761 fn slice_split_last_mut() {
762 let slice: &mut Slice<i32, i32> = Slice::new_mut();
763 let result = slice.split_last_mut();
764 assert!(result.is_none());
765
766 let mut map: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
767 let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
768
769 {
770 let (last, rest) = slice.split_last_mut().unwrap();
771 assert_eq!(last, (&9, &mut 81));
772 assert_eq!(rest.len(), 9);
773
774 *last.1 = 100;
775 }
776
777 assert_eq!(slice.len(), 10);
778 assert_eq!(slice[slice.len() - 1], 100);
779 }
780
781 #[test]
782 fn slice_get_range() {
783 let mut map: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
784 let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
785 let subslice = slice.get_range(3..6).unwrap();
786 assert_eq!(subslice.len(), 3);
787 assert_eq!(subslice, &[(3, 9), (4, 16), (5, 25)]);
788 }
789}