indexmap/map/
slice.rs

1use super::{
2    Bucket, IndexMap, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values, ValuesMut,
3};
4use crate::GetDisjointMutError;
5use crate::util::{slice_eq, try_simplify_range};
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/// A dynamically-sized slice of key-value pairs in an [`IndexMap`].
15///
16/// This supports indexed operations much like a `[(K, V)]` slice,
17/// but not any hashed operations on the map keys.
18///
19/// Unlike `IndexMap`, `Slice` does consider the order for [`PartialEq`]
20/// and [`Eq`], and it also implements [`PartialOrd`], [`Ord`], and [`Hash`].
21#[repr(transparent)]
22pub struct Slice<K, V> {
23    pub(crate) entries: [Bucket<K, V>],
24}
25
26// SAFETY: `Slice<K, V>` is a transparent wrapper around `[Bucket<K, V>]`,
27// and reference lifetimes are bound together in function signatures.
28#[allow(unsafe_code)]
29impl<K, V> Slice<K, V> {
30    pub(crate) 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) const 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    /// Returns an empty slice.
53    pub const fn new<'a>() -> &'a Self {
54        Self::from_slice(&[])
55    }
56
57    /// Returns an empty mutable slice.
58    pub const fn new_mut<'a>() -> &'a mut Self {
59        Self::from_mut_slice(&mut [])
60    }
61
62    /// Return the number of key-value pairs in the map slice.
63    #[inline]
64    pub const fn len(&self) -> usize {
65        self.entries.len()
66    }
67
68    /// Returns true if the map slice contains no elements.
69    #[inline]
70    pub const fn is_empty(&self) -> bool {
71        self.entries.is_empty()
72    }
73
74    /// Get a key-value pair by index.
75    ///
76    /// Valid indices are `0 <= index < self.len()`.
77    pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
78        self.entries.get(index).map(Bucket::refs)
79    }
80
81    /// Get a key-value pair by index, with mutable access to the value.
82    ///
83    /// Valid indices are `0 <= index < self.len()`.
84    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    /// Returns a slice of key-value pairs in the given range of indices.
89    ///
90    /// Valid indices are `0 <= index < self.len()`.
91    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    /// Returns a mutable slice of key-value pairs in the given range of indices.
97    ///
98    /// Valid indices are `0 <= index < self.len()`.
99    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    /// Get the first key-value pair.
105    pub const fn first(&self) -> Option<(&K, &V)> {
106        if let [first, ..] = &self.entries {
107            Some(first.refs())
108        } else {
109            None
110        }
111    }
112
113    /// Get the first key-value pair, with mutable access to the value.
114    pub const fn first_mut(&mut self) -> Option<(&K, &mut V)> {
115        if let [first, ..] = &mut self.entries {
116            Some(first.ref_mut())
117        } else {
118            None
119        }
120    }
121
122    /// Get the last key-value pair.
123    pub const fn last(&self) -> Option<(&K, &V)> {
124        if let [.., last] = &self.entries {
125            Some(last.refs())
126        } else {
127            None
128        }
129    }
130
131    /// Get the last key-value pair, with mutable access to the value.
132    pub const fn last_mut(&mut self) -> Option<(&K, &mut V)> {
133        if let [.., last] = &mut self.entries {
134            Some(last.ref_mut())
135        } else {
136            None
137        }
138    }
139
140    /// Divides one slice into two at an index.
141    ///
142    /// ***Panics*** if `index > len`.
143    /// For a non-panicking alternative see [`split_at_checked`][Self::split_at_checked].
144    #[track_caller]
145    pub const fn split_at(&self, index: usize) -> (&Self, &Self) {
146        let (first, second) = self.entries.split_at(index);
147        (Self::from_slice(first), Self::from_slice(second))
148    }
149
150    /// Divides one mutable slice into two at an index.
151    ///
152    /// ***Panics*** if `index > len`.
153    /// For a non-panicking alternative see [`split_at_mut_checked`][Self::split_at_mut_checked].
154    #[track_caller]
155    pub const fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) {
156        let (first, second) = self.entries.split_at_mut(index);
157        (Self::from_mut_slice(first), Self::from_mut_slice(second))
158    }
159
160    /// Divides one slice into two at an index.
161    ///
162    /// Returns `None` if `index > len`.
163    pub const fn split_at_checked(&self, index: usize) -> Option<(&Self, &Self)> {
164        if let Some((first, second)) = self.entries.split_at_checked(index) {
165            Some((Self::from_slice(first), Self::from_slice(second)))
166        } else {
167            None
168        }
169    }
170
171    /// Divides one mutable slice into two at an index.
172    ///
173    /// Returns `None` if `index > len`.
174    pub const fn split_at_mut_checked(&mut self, index: usize) -> Option<(&mut Self, &mut Self)> {
175        if let Some((first, second)) = self.entries.split_at_mut_checked(index) {
176            Some((Self::from_mut_slice(first), Self::from_mut_slice(second)))
177        } else {
178            None
179        }
180    }
181
182    /// Returns the first key-value pair and the rest of the slice,
183    /// or `None` if it is empty.
184    pub const fn split_first(&self) -> Option<((&K, &V), &Self)> {
185        if let [first, rest @ ..] = &self.entries {
186            Some((first.refs(), Self::from_slice(rest)))
187        } else {
188            None
189        }
190    }
191
192    /// Returns the first key-value pair and the rest of the slice,
193    /// with mutable access to the value, or `None` if it is empty.
194    pub const fn split_first_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
195        if let [first, rest @ ..] = &mut self.entries {
196            Some((first.ref_mut(), Self::from_mut_slice(rest)))
197        } else {
198            None
199        }
200    }
201
202    /// Returns the last key-value pair and the rest of the slice,
203    /// or `None` if it is empty.
204    pub const fn split_last(&self) -> Option<((&K, &V), &Self)> {
205        if let [rest @ .., last] = &self.entries {
206            Some((last.refs(), Self::from_slice(rest)))
207        } else {
208            None
209        }
210    }
211
212    /// Returns the last key-value pair and the rest of the slice,
213    /// with mutable access to the value, or `None` if it is empty.
214    pub const fn split_last_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
215        if let [rest @ .., last] = &mut self.entries {
216            Some((last.ref_mut(), Self::from_mut_slice(rest)))
217        } else {
218            None
219        }
220    }
221
222    /// Return an iterator over the key-value pairs of the map slice.
223    pub fn iter(&self) -> Iter<'_, K, V> {
224        Iter::new(&self.entries)
225    }
226
227    /// Return an iterator over the key-value pairs of the map slice.
228    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
229        IterMut::new(&mut self.entries)
230    }
231
232    /// Return an iterator over the keys of the map slice.
233    pub fn keys(&self) -> Keys<'_, K, V> {
234        Keys::new(&self.entries)
235    }
236
237    /// Return an owning iterator over the keys of the map slice.
238    pub fn into_keys(self: Box<Self>) -> IntoKeys<K, V> {
239        IntoKeys::new(self.into_entries())
240    }
241
242    /// Return an iterator over the values of the map slice.
243    pub fn values(&self) -> Values<'_, K, V> {
244        Values::new(&self.entries)
245    }
246
247    /// Return an iterator over mutable references to the the values of the map slice.
248    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
249        ValuesMut::new(&mut self.entries)
250    }
251
252    /// Return an owning iterator over the values of the map slice.
253    pub fn into_values(self: Box<Self>) -> IntoValues<K, V> {
254        IntoValues::new(self.into_entries())
255    }
256
257    /// Search over a sorted map for a key.
258    ///
259    /// Returns the position where that key is present, or the position where it can be inserted to
260    /// maintain the sort. See [`slice::binary_search`] for more details.
261    ///
262    /// Computes in **O(log(n))** time, which is notably less scalable than looking the key up in
263    /// the map this is a slice from using [`IndexMap::get_index_of`], but this can also position
264    /// missing keys.
265    pub fn binary_search_keys(&self, x: &K) -> Result<usize, usize>
266    where
267        K: Ord,
268    {
269        self.binary_search_by(|p, _| p.cmp(x))
270    }
271
272    /// Search over a sorted map with a comparator function.
273    ///
274    /// Returns the position where that value is present, or the position where it can be inserted
275    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
276    ///
277    /// Computes in **O(log(n))** time.
278    #[inline]
279    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
280    where
281        F: FnMut(&'a K, &'a V) -> Ordering,
282    {
283        self.entries.binary_search_by(move |a| f(&a.key, &a.value))
284    }
285
286    /// Search over a sorted map with an extraction function.
287    ///
288    /// Returns the position where that value is present, or the position where it can be inserted
289    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
290    ///
291    /// Computes in **O(log(n))** time.
292    #[inline]
293    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
294    where
295        F: FnMut(&'a K, &'a V) -> B,
296        B: Ord,
297    {
298        self.binary_search_by(|k, v| f(k, v).cmp(b))
299    }
300
301    /// Checks if the keys of this slice are sorted.
302    #[inline]
303    pub fn is_sorted(&self) -> bool
304    where
305        K: PartialOrd,
306    {
307        self.entries.is_sorted_by(|a, b| a.key <= b.key)
308    }
309
310    /// Checks if this slice is sorted using the given comparator function.
311    #[inline]
312    pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool
313    where
314        F: FnMut(&'a K, &'a V, &'a K, &'a V) -> bool,
315    {
316        self.entries
317            .is_sorted_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value))
318    }
319
320    /// Checks if this slice is sorted using the given sort-key function.
321    #[inline]
322    pub fn is_sorted_by_key<'a, F, T>(&'a self, mut sort_key: F) -> bool
323    where
324        F: FnMut(&'a K, &'a V) -> T,
325        T: PartialOrd,
326    {
327        self.entries
328            .is_sorted_by_key(move |a| sort_key(&a.key, &a.value))
329    }
330
331    /// Returns the index of the partition point of a sorted map according to the given predicate
332    /// (the index of the first element of the second partition).
333    ///
334    /// See [`slice::partition_point`] for more details.
335    ///
336    /// Computes in **O(log(n))** time.
337    #[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
343            .partition_point(move |a| pred(&a.key, &a.value))
344    }
345
346    /// Get an array of `N` key-value pairs by `N` indices
347    ///
348    /// Valid indices are *0 <= index < self.len()* and each index needs to be unique.
349    pub fn get_disjoint_mut<const N: usize>(
350        &mut self,
351        indices: [usize; N],
352    ) -> Result<[(&K, &mut V); N], GetDisjointMutError> {
353        let indices = indices.map(Some);
354        let key_values = self.get_disjoint_opt_mut(indices)?;
355        Ok(key_values.map(Option::unwrap))
356    }
357
358    #[allow(unsafe_code)]
359    pub(crate) fn get_disjoint_opt_mut<const N: usize>(
360        &mut self,
361        indices: [Option<usize>; N],
362    ) -> Result<[Option<(&K, &mut V)>; N], GetDisjointMutError> {
363        // SAFETY: Can't allow duplicate indices as we would return several mutable refs to the same data.
364        let len = self.len();
365        for i in 0..N {
366            if let Some(idx) = indices[i] {
367                if idx >= len {
368                    return Err(GetDisjointMutError::IndexOutOfBounds);
369                } else if indices[..i].contains(&Some(idx)) {
370                    return Err(GetDisjointMutError::OverlappingIndices);
371                }
372            }
373        }
374
375        let entries_ptr = self.entries.as_mut_ptr();
376        let out = indices.map(|idx_opt| {
377            match idx_opt {
378                Some(idx) => {
379                    // SAFETY: The base pointer is valid as it comes from a slice and the reference is always
380                    // in-bounds & unique as we've already checked the indices above.
381                    let kv = unsafe { (*(entries_ptr.add(idx))).ref_mut() };
382                    Some(kv)
383                }
384                None => None,
385            }
386        });
387
388        Ok(out)
389    }
390}
391
392impl<'a, K, V> IntoIterator for &'a Slice<K, V> {
393    type IntoIter = Iter<'a, K, V>;
394    type Item = (&'a K, &'a V);
395
396    fn into_iter(self) -> Self::IntoIter {
397        self.iter()
398    }
399}
400
401impl<'a, K, V> IntoIterator for &'a mut Slice<K, V> {
402    type IntoIter = IterMut<'a, K, V>;
403    type Item = (&'a K, &'a mut V);
404
405    fn into_iter(self) -> Self::IntoIter {
406        self.iter_mut()
407    }
408}
409
410impl<K, V> IntoIterator for Box<Slice<K, V>> {
411    type IntoIter = IntoIter<K, V>;
412    type Item = (K, V);
413
414    fn into_iter(self) -> Self::IntoIter {
415        IntoIter::new(self.into_entries())
416    }
417}
418
419impl<K, V> Default for &'_ Slice<K, V> {
420    fn default() -> Self {
421        Slice::from_slice(&[])
422    }
423}
424
425impl<K, V> Default for &'_ mut Slice<K, V> {
426    fn default() -> Self {
427        Slice::from_mut_slice(&mut [])
428    }
429}
430
431impl<K, V> Default for Box<Slice<K, V>> {
432    fn default() -> Self {
433        Slice::from_boxed(Box::default())
434    }
435}
436
437impl<K: Clone, V: Clone> Clone for Box<Slice<K, V>> {
438    fn clone(&self) -> Self {
439        Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
440    }
441}
442
443impl<K: Copy, V: Copy> From<&Slice<K, V>> for Box<Slice<K, V>> {
444    fn from(slice: &Slice<K, V>) -> Self {
445        Slice::from_boxed(Box::from(&slice.entries))
446    }
447}
448
449impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Slice<K, V> {
450    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451        f.debug_list().entries(self).finish()
452    }
453}
454
455impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for Slice<K, V>
456where
457    K: PartialEq<K2>,
458    V: PartialEq<V2>,
459{
460    fn eq(&self, other: &Slice<K2, V2>) -> bool {
461        slice_eq(&self.entries, &other.entries, |b1, b2| {
462            b1.key == b2.key && b1.value == b2.value
463        })
464    }
465}
466
467impl<K, V, K2, V2> PartialEq<[(K2, V2)]> for Slice<K, V>
468where
469    K: PartialEq<K2>,
470    V: PartialEq<V2>,
471{
472    fn eq(&self, other: &[(K2, V2)]) -> bool {
473        slice_eq(&self.entries, other, |b, t| b.key == t.0 && b.value == t.1)
474    }
475}
476
477impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V)]
478where
479    K: PartialEq<K2>,
480    V: PartialEq<V2>,
481{
482    fn eq(&self, other: &Slice<K2, V2>) -> bool {
483        slice_eq(self, &other.entries, |t, b| t.0 == b.key && t.1 == b.value)
484    }
485}
486
487impl<K, V, K2, V2, const N: usize> PartialEq<[(K2, V2); N]> for Slice<K, V>
488where
489    K: PartialEq<K2>,
490    V: PartialEq<V2>,
491{
492    fn eq(&self, other: &[(K2, V2); N]) -> bool {
493        <Self as PartialEq<[_]>>::eq(self, other)
494    }
495}
496
497impl<K, V, const N: usize, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V); N]
498where
499    K: PartialEq<K2>,
500    V: PartialEq<V2>,
501{
502    fn eq(&self, other: &Slice<K2, V2>) -> bool {
503        <[_] as PartialEq<_>>::eq(self, other)
504    }
505}
506
507impl<K: Eq, V: Eq> Eq for Slice<K, V> {}
508
509impl<K: PartialOrd, V: PartialOrd> PartialOrd for Slice<K, V> {
510    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
511        self.iter().partial_cmp(other)
512    }
513}
514
515impl<K: Ord, V: Ord> Ord for Slice<K, V> {
516    fn cmp(&self, other: &Self) -> Ordering {
517        self.iter().cmp(other)
518    }
519}
520
521impl<K: Hash, V: Hash> Hash for Slice<K, V> {
522    fn hash<H: Hasher>(&self, state: &mut H) {
523        self.len().hash(state);
524        for (key, value) in self {
525            key.hash(state);
526            value.hash(state);
527        }
528    }
529}
530
531impl<K, V> Index<usize> for Slice<K, V> {
532    type Output = V;
533
534    fn index(&self, index: usize) -> &V {
535        &self.entries[index].value
536    }
537}
538
539impl<K, V> IndexMut<usize> for Slice<K, V> {
540    fn index_mut(&mut self, index: usize) -> &mut V {
541        &mut self.entries[index].value
542    }
543}
544
545// We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts
546// both upstream with `Index<usize>` and downstream with `Index<&Q>`.
547// Instead, we repeat the implementations for all the core range types.
548macro_rules! impl_index {
549    ($($range:ty),*) => {$(
550        impl<K, V, S> Index<$range> for IndexMap<K, V, S> {
551            type Output = Slice<K, V>;
552
553            fn index(&self, range: $range) -> &Self::Output {
554                Slice::from_slice(&self.as_entries()[range])
555            }
556        }
557
558        impl<K, V, S> IndexMut<$range> for IndexMap<K, V, S> {
559            fn index_mut(&mut self, range: $range) -> &mut Self::Output {
560                Slice::from_mut_slice(&mut self.as_entries_mut()[range])
561            }
562        }
563
564        impl<K, V> Index<$range> for Slice<K, V> {
565            type Output = Slice<K, V>;
566
567            fn index(&self, range: $range) -> &Self {
568                Self::from_slice(&self.entries[range])
569            }
570        }
571
572        impl<K, V> IndexMut<$range> for Slice<K, V> {
573            fn index_mut(&mut self, range: $range) -> &mut Self {
574                Self::from_mut_slice(&mut self.entries[range])
575            }
576        }
577    )*}
578}
579impl_index!(
580    ops::Range<usize>,
581    ops::RangeFrom<usize>,
582    ops::RangeFull,
583    ops::RangeInclusive<usize>,
584    ops::RangeTo<usize>,
585    ops::RangeToInclusive<usize>,
586    (Bound<usize>, Bound<usize>)
587);
588
589#[cfg(test)]
590mod tests {
591    use super::*;
592
593    #[test]
594    fn slice_index() {
595        fn check(
596            vec_slice: &[(i32, i32)],
597            map_slice: &Slice<i32, i32>,
598            sub_slice: &Slice<i32, i32>,
599        ) {
600            assert_eq!(map_slice as *const _, sub_slice as *const _);
601            itertools::assert_equal(
602                vec_slice.iter().copied(),
603                map_slice.iter().map(|(&k, &v)| (k, v)),
604            );
605            itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys());
606            itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values());
607        }
608
609        let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
610        let map: IndexMap<i32, i32> = vec.iter().cloned().collect();
611        let slice = map.as_slice();
612
613        // RangeFull
614        check(&vec[..], &map[..], &slice[..]);
615
616        for i in 0usize..10 {
617            // Index
618            assert_eq!(vec[i].1, map[i]);
619            assert_eq!(vec[i].1, slice[i]);
620            assert_eq!(map[&(i as i32)], map[i]);
621            assert_eq!(map[&(i as i32)], slice[i]);
622
623            // RangeFrom
624            check(&vec[i..], &map[i..], &slice[i..]);
625
626            // RangeTo
627            check(&vec[..i], &map[..i], &slice[..i]);
628
629            // RangeToInclusive
630            check(&vec[..=i], &map[..=i], &slice[..=i]);
631
632            // (Bound<usize>, Bound<usize>)
633            let bounds = (Bound::Excluded(i), Bound::Unbounded);
634            check(&vec[i + 1..], &map[bounds], &slice[bounds]);
635
636            for j in i..=10 {
637                // Range
638                check(&vec[i..j], &map[i..j], &slice[i..j]);
639            }
640
641            for j in i..10 {
642                // RangeInclusive
643                check(&vec[i..=j], &map[i..=j], &slice[i..=j]);
644            }
645        }
646    }
647
648    #[test]
649    fn slice_index_mut() {
650        fn check_mut(
651            vec_slice: &[(i32, i32)],
652            map_slice: &mut Slice<i32, i32>,
653            sub_slice: &mut Slice<i32, i32>,
654        ) {
655            assert_eq!(map_slice, sub_slice);
656            itertools::assert_equal(
657                vec_slice.iter().copied(),
658                map_slice.iter_mut().map(|(&k, &mut v)| (k, v)),
659            );
660            itertools::assert_equal(
661                vec_slice.iter().map(|&(_, v)| v),
662                map_slice.values_mut().map(|&mut v| v),
663            );
664        }
665
666        let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
667        let mut map: IndexMap<i32, i32> = vec.iter().cloned().collect();
668        let mut map2 = map.clone();
669        let slice = map2.as_mut_slice();
670
671        // RangeFull
672        check_mut(&vec[..], &mut map[..], &mut slice[..]);
673
674        for i in 0usize..10 {
675            // IndexMut
676            assert_eq!(&mut map[i], &mut slice[i]);
677
678            // RangeFrom
679            check_mut(&vec[i..], &mut map[i..], &mut slice[i..]);
680
681            // RangeTo
682            check_mut(&vec[..i], &mut map[..i], &mut slice[..i]);
683
684            // RangeToInclusive
685            check_mut(&vec[..=i], &mut map[..=i], &mut slice[..=i]);
686
687            // (Bound<usize>, Bound<usize>)
688            let bounds = (Bound::Excluded(i), Bound::Unbounded);
689            check_mut(&vec[i + 1..], &mut map[bounds], &mut slice[bounds]);
690
691            for j in i..=10 {
692                // Range
693                check_mut(&vec[i..j], &mut map[i..j], &mut slice[i..j]);
694            }
695
696            for j in i..10 {
697                // RangeInclusive
698                check_mut(&vec[i..=j], &mut map[i..=j], &mut slice[i..=j]);
699            }
700        }
701    }
702
703    #[test]
704    fn slice_new() {
705        let slice: &Slice<i32, i32> = Slice::new();
706        assert!(slice.is_empty());
707        assert_eq!(slice.len(), 0);
708    }
709
710    #[test]
711    fn slice_new_mut() {
712        let slice: &mut Slice<i32, i32> = Slice::new_mut();
713        assert!(slice.is_empty());
714        assert_eq!(slice.len(), 0);
715    }
716
717    #[test]
718    fn slice_get_index_mut() {
719        let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
720        let slice: &mut Slice<i32, i32> = map.as_mut_slice();
721
722        {
723            let (key, value) = slice.get_index_mut(0).unwrap();
724            assert_eq!(*key, 0);
725            assert_eq!(*value, 0);
726
727            *value = 11;
728        }
729
730        assert_eq!(slice[0], 11);
731
732        {
733            let result = slice.get_index_mut(11);
734            assert!(result.is_none());
735        }
736    }
737
738    #[test]
739    fn slice_split_first() {
740        let slice: &mut Slice<i32, i32> = Slice::new_mut();
741        let result = slice.split_first();
742        assert!(result.is_none());
743
744        let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
745        let slice: &mut Slice<i32, i32> = map.as_mut_slice();
746
747        {
748            let (first, rest) = slice.split_first().unwrap();
749            assert_eq!(first, (&0, &0));
750            assert_eq!(rest.len(), 9);
751        }
752        assert_eq!(slice.len(), 10);
753    }
754
755    #[test]
756    fn slice_split_first_mut() {
757        let slice: &mut Slice<i32, i32> = Slice::new_mut();
758        let result = slice.split_first_mut();
759        assert!(result.is_none());
760
761        let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
762        let slice: &mut Slice<i32, i32> = map.as_mut_slice();
763
764        {
765            let (first, rest) = slice.split_first_mut().unwrap();
766            assert_eq!(first, (&0, &mut 0));
767            assert_eq!(rest.len(), 9);
768
769            *first.1 = 11;
770        }
771        assert_eq!(slice.len(), 10);
772        assert_eq!(slice[0], 11);
773    }
774
775    #[test]
776    fn slice_split_last() {
777        let slice: &mut Slice<i32, i32> = Slice::new_mut();
778        let result = slice.split_last();
779        assert!(result.is_none());
780
781        let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
782        let slice: &mut Slice<i32, i32> = map.as_mut_slice();
783
784        {
785            let (last, rest) = slice.split_last().unwrap();
786            assert_eq!(last, (&9, &81));
787            assert_eq!(rest.len(), 9);
788        }
789        assert_eq!(slice.len(), 10);
790    }
791
792    #[test]
793    fn slice_split_last_mut() {
794        let slice: &mut Slice<i32, i32> = Slice::new_mut();
795        let result = slice.split_last_mut();
796        assert!(result.is_none());
797
798        let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
799        let slice: &mut Slice<i32, i32> = map.as_mut_slice();
800
801        {
802            let (last, rest) = slice.split_last_mut().unwrap();
803            assert_eq!(last, (&9, &mut 81));
804            assert_eq!(rest.len(), 9);
805
806            *last.1 = 100;
807        }
808
809        assert_eq!(slice.len(), 10);
810        assert_eq!(slice[slice.len() - 1], 100);
811    }
812
813    #[test]
814    fn slice_get_range() {
815        let mut map: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
816        let slice: &mut Slice<i32, i32> = map.as_mut_slice();
817        let subslice = slice.get_range(3..6).unwrap();
818        assert_eq!(subslice.len(), 3);
819        assert_eq!(subslice, &[(3, 9), (4, 16), (5, 25)]);
820    }
821}