ringmap/map/
slice.rs

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/// A dynamically-sized slice of key-value pairs in a [`RingMap`][super::RingMap].
13///
14/// This supports indexed operations much like a `[(K, V)]` slice,
15/// but not any hashed operations on the map keys.
16#[repr(transparent)]
17pub struct Slice<K, V> {
18    pub(crate) entries: [Bucket<K, V>],
19}
20
21// SAFETY: `Slice<K, V>` is a transparent wrapper around `[Bucket<K, V>]`,
22// and reference lifetimes are bound together in function signatures.
23#[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    /// Returns an empty slice.
48    pub const fn new<'a>() -> &'a Self {
49        Self::from_slice(&[])
50    }
51
52    /// Returns an empty mutable slice.
53    pub fn new_mut<'a>() -> &'a mut Self {
54        Self::from_mut_slice(&mut [])
55    }
56
57    /// Return the number of key-value pairs in the map slice.
58    #[inline]
59    pub const fn len(&self) -> usize {
60        self.entries.len()
61    }
62
63    /// Returns true if the map slice contains no elements.
64    #[inline]
65    pub const fn is_empty(&self) -> bool {
66        self.entries.is_empty()
67    }
68
69    /// Get a key-value pair by index.
70    ///
71    /// Valid indices are `0 <= index < self.len()`.
72    pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
73        self.entries.get(index).map(Bucket::refs)
74    }
75
76    /// Get a key-value pair by index, with mutable access to the value.
77    ///
78    /// Valid indices are `0 <= index < self.len()`.
79    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    /// Returns a slice of key-value pairs in the given range of indices.
84    ///
85    /// Valid indices are `0 <= index < self.len()`.
86    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    /// Returns a mutable slice of key-value pairs in the given range of indices.
92    ///
93    /// Valid indices are `0 <= index < self.len()`.
94    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    /// Get the first key-value pair.
100    pub fn first(&self) -> Option<(&K, &V)> {
101        self.entries.first().map(Bucket::refs)
102    }
103
104    /// Get the first key-value pair, with mutable access to the value.
105    pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
106        self.entries.first_mut().map(Bucket::ref_mut)
107    }
108
109    /// Get the last key-value pair.
110    pub fn last(&self) -> Option<(&K, &V)> {
111        self.entries.last().map(Bucket::refs)
112    }
113
114    /// Get the last key-value pair, with mutable access to the value.
115    pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
116        self.entries.last_mut().map(Bucket::ref_mut)
117    }
118
119    /// Divides one slice into two at an index.
120    ///
121    /// ***Panics*** if `index > len`.
122    /// For a non-panicking alternative see [`split_at_checked`][Self::split_at_checked].
123    #[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    /// Divides one mutable slice into two at an index.
130    ///
131    /// ***Panics*** if `index > len`.
132    /// For a non-panicking alternative see [`split_at_mut_checked`][Self::split_at_mut_checked].
133    #[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    /// Divides one slice into two at an index.
140    ///
141    /// Returns `None` if `index > len`.
142    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    /// Divides one mutable slice into two at an index.
148    ///
149    /// Returns `None` if `index > len`.
150    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    /// Returns the first key-value pair and the rest of the slice,
156    /// or `None` if it is empty.
157    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    /// Returns the first key-value pair and the rest of the slice,
166    /// with mutable access to the value, or `None` if it is empty.
167    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    /// Returns the last key-value pair and the rest of the slice,
176    /// or `None` if it is empty.
177    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    /// Returns the last key-value pair and the rest of the slice,
186    /// with mutable access to the value, or `None` if it is empty.
187    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    /// Return an iterator over the key-value pairs of the map slice.
196    pub fn iter(&self) -> Iter<'_, K, V> {
197        Iter::from_slice(&self.entries)
198    }
199
200    /// Return an iterator over the key-value pairs of the map slice.
201    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
202        IterMut::from_mut_slice(&mut self.entries)
203    }
204
205    /// Return an iterator over the keys of the map slice.
206    pub fn keys(&self) -> Keys<'_, K, V> {
207        Keys::from_slice(&self.entries)
208    }
209
210    /// Return an owning iterator over the keys of the map slice.
211    pub fn into_keys(self: Box<Self>) -> IntoKeys<K, V> {
212        IntoKeys::new(self.into_entries())
213    }
214
215    /// Return an iterator over the values of the map slice.
216    pub fn values(&self) -> Values<'_, K, V> {
217        Values::from_slice(&self.entries)
218    }
219
220    /// Return an iterator over mutable references to the the values of the map slice.
221    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
222        ValuesMut::from_mut_slice(&mut self.entries)
223    }
224
225    /// Return an owning iterator over the values of the map slice.
226    pub fn into_values(self: Box<Self>) -> IntoValues<K, V> {
227        IntoValues::new(self.into_entries())
228    }
229
230    /// Search over a sorted map for a key.
231    ///
232    /// Returns the position where that key is present, or the position where it can be inserted to
233    /// maintain the sort. See [`slice::binary_search`] for more details.
234    ///
235    /// Computes in **O(log(n))** time, which is notably less scalable than looking the key up in
236    /// the map this is a slice from using [`RingMap::get_index_of`][super::RingMap::get_index_of],
237    /// but this can also position missing keys.
238    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    /// Search over a sorted map with a comparator function.
246    ///
247    /// Returns the position where that value is present, or the position where it can be inserted
248    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
249    ///
250    /// Computes in **O(log(n))** time.
251    #[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    /// Search over a sorted map with an extraction function.
260    ///
261    /// Returns the position where that value is present, or the position where it can be inserted
262    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
263    ///
264    /// Computes in **O(log(n))** time.
265    #[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    /// Checks if the keys of this slice are sorted.
275    #[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    /// Checks if this slice is sorted using the given comparator function.
284    #[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    /// Checks if this slice is sorted using the given sort-key function.
294    #[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    /// Returns the index of the partition point of a sorted map according to the given predicate
305    /// (the index of the first element of the second partition).
306    ///
307    /// See [`slice::partition_point`] for more details.
308    ///
309    /// Computes in **O(log(n))** time.
310    #[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    /// Get an array of `N` key-value pairs by `N` indices
320    ///
321    /// Valid indices are *0 <= index < self.len()* and each index needs to be unique.
322    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        // SAFETY: Can't allow duplicate indices as we would return several mutable refs to the same data.
342        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                    // SAFETY: The base pointers are valid as they come from slices and the reference is always
358                    // in-bounds & unique as we've already checked the indices above.
359                    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
528// We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts
529// both upstream with `Index<usize>` and downstream with `Index<&Q>`.
530// Instead, we repeat the implementations for all the core range types.
531macro_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        // RangeFull
581        check(&vec[..], &slice[..]);
582
583        for i in 0usize..10 {
584            // Index
585            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            // RangeFrom
591            check(&vec[i..], &slice[i..]);
592
593            // RangeTo
594            check(&vec[..i], &slice[..i]);
595
596            // RangeToInclusive
597            check(&vec[..=i], &slice[..=i]);
598
599            // (Bound<usize>, Bound<usize>)
600            let bounds = (Bound::Excluded(i), Bound::Unbounded);
601            check(&vec[i + 1..], &slice[bounds]);
602
603            for j in i..=10 {
604                // Range
605                check(&vec[i..j], &slice[i..j]);
606            }
607
608            for j in i..10 {
609                // RangeInclusive
610                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        // RangeFull
640        check_mut(&vec[..], &mut slice[..]);
641
642        for i in 0usize..10 {
643            // IndexMut
644            assert_eq!(&mut map[i], &mut slice[i]);
645
646            // RangeFrom
647            check_mut(&vec[i..], &mut slice[i..]);
648
649            // RangeTo
650            check_mut(&vec[..i], &mut slice[..i]);
651
652            // RangeToInclusive
653            check_mut(&vec[..=i], &mut slice[..=i]);
654
655            // (Bound<usize>, Bound<usize>)
656            let bounds = (Bound::Excluded(i), Bound::Unbounded);
657            check_mut(&vec[i + 1..], &mut slice[bounds]);
658
659            for j in i..=10 {
660                // Range
661                check_mut(&vec[i..j], &mut slice[i..j]);
662            }
663
664            for j in i..10 {
665                // RangeInclusive
666                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}