Skip to main content

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 const fn first(&self) -> Option<(&K, &V)> {
101        if let [first, ..] = &self.entries {
102            Some(first.refs())
103        } else {
104            None
105        }
106    }
107
108    /// Get the first key-value pair, with mutable access to the value.
109    pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
110        self.entries.first_mut().map(Bucket::ref_mut)
111    }
112
113    /// Get the last key-value pair.
114    pub const fn last(&self) -> Option<(&K, &V)> {
115        if let [.., last] = &self.entries {
116            Some(last.refs())
117        } else {
118            None
119        }
120    }
121
122    /// Get the last key-value pair, with mutable access to the value.
123    pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
124        self.entries.last_mut().map(Bucket::ref_mut)
125    }
126
127    /// Divides one slice into two at an index.
128    ///
129    /// ***Panics*** if `index > len`.
130    /// For a non-panicking alternative see [`split_at_checked`][Self::split_at_checked].
131    #[track_caller]
132    pub const fn split_at(&self, index: usize) -> (&Self, &Self) {
133        let (first, second) = self.entries.split_at(index);
134        (Self::from_slice(first), Self::from_slice(second))
135    }
136
137    /// Divides one mutable slice into two at an index.
138    ///
139    /// ***Panics*** if `index > len`.
140    /// For a non-panicking alternative see [`split_at_mut_checked`][Self::split_at_mut_checked].
141    #[track_caller]
142    pub fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) {
143        let (first, second) = self.entries.split_at_mut(index);
144        (Self::from_mut_slice(first), Self::from_mut_slice(second))
145    }
146
147    /// Divides one slice into two at an index.
148    ///
149    /// Returns `None` if `index > len`.
150    pub const fn split_at_checked(&self, index: usize) -> Option<(&Self, &Self)> {
151        if let Some((first, second)) = self.entries.split_at_checked(index) {
152            Some((Self::from_slice(first), Self::from_slice(second)))
153        } else {
154            None
155        }
156    }
157
158    /// Divides one mutable slice into two at an index.
159    ///
160    /// Returns `None` if `index > len`.
161    pub fn split_at_mut_checked(&mut self, index: usize) -> Option<(&mut Self, &mut Self)> {
162        let (first, second) = self.entries.split_at_mut_checked(index)?;
163        Some((Self::from_mut_slice(first), Self::from_mut_slice(second)))
164    }
165
166    /// Returns the first key-value pair and the rest of the slice,
167    /// or `None` if it is empty.
168    pub const fn split_first(&self) -> Option<((&K, &V), &Self)> {
169        if let [first, rest @ ..] = &self.entries {
170            Some((first.refs(), Self::from_slice(rest)))
171        } else {
172            None
173        }
174    }
175
176    /// Returns the first key-value pair and the rest of the slice,
177    /// with mutable access to the value, or `None` if it is empty.
178    pub fn split_first_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
179        if let [first, rest @ ..] = &mut self.entries {
180            Some((first.ref_mut(), Self::from_mut_slice(rest)))
181        } else {
182            None
183        }
184    }
185
186    /// Returns the last key-value pair and the rest of the slice,
187    /// or `None` if it is empty.
188    pub const fn split_last(&self) -> Option<((&K, &V), &Self)> {
189        if let [rest @ .., last] = &self.entries {
190            Some((last.refs(), Self::from_slice(rest)))
191        } else {
192            None
193        }
194    }
195
196    /// Returns the last key-value pair and the rest of the slice,
197    /// with mutable access to the value, or `None` if it is empty.
198    pub fn split_last_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
199        if let [rest @ .., last] = &mut self.entries {
200            Some((last.ref_mut(), Self::from_mut_slice(rest)))
201        } else {
202            None
203        }
204    }
205
206    /// Return an iterator over the key-value pairs of the map slice.
207    pub fn iter(&self) -> Iter<'_, K, V> {
208        Iter::from_slice(&self.entries)
209    }
210
211    /// Return an iterator over the key-value pairs of the map slice.
212    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
213        IterMut::from_mut_slice(&mut self.entries)
214    }
215
216    /// Return an iterator over the keys of the map slice.
217    pub fn keys(&self) -> Keys<'_, K, V> {
218        Keys::from_slice(&self.entries)
219    }
220
221    /// Return an owning iterator over the keys of the map slice.
222    pub fn into_keys(self: Box<Self>) -> IntoKeys<K, V> {
223        IntoKeys::new(self.into_entries())
224    }
225
226    /// Return an iterator over the values of the map slice.
227    pub fn values(&self) -> Values<'_, K, V> {
228        Values::from_slice(&self.entries)
229    }
230
231    /// Return an iterator over mutable references to the the values of the map slice.
232    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
233        ValuesMut::from_mut_slice(&mut self.entries)
234    }
235
236    /// Return an owning iterator over the values of the map slice.
237    pub fn into_values(self: Box<Self>) -> IntoValues<K, V> {
238        IntoValues::new(self.into_entries())
239    }
240
241    /// Search over a sorted map for a key.
242    ///
243    /// Returns the position where that key is present, or the position where it can be inserted to
244    /// maintain the sort. See [`slice::binary_search`] for more details.
245    ///
246    /// Computes in **O(log(n))** time, which is notably less scalable than looking the key up in
247    /// the map this is a slice from using [`RingMap::get_index_of`][super::RingMap::get_index_of],
248    /// but this can also position missing keys.
249    pub fn binary_search_keys(&self, x: &K) -> Result<usize, usize>
250    where
251        K: Ord,
252    {
253        self.binary_search_by(|p, _| p.cmp(x))
254    }
255
256    /// Search over a sorted map with a comparator function.
257    ///
258    /// Returns the position where that value is present, or the position where it can be inserted
259    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
260    ///
261    /// Computes in **O(log(n))** time.
262    #[inline]
263    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
264    where
265        F: FnMut(&'a K, &'a V) -> Ordering,
266    {
267        self.entries.binary_search_by(move |a| f(&a.key, &a.value))
268    }
269
270    /// Search over a sorted map with an extraction function.
271    ///
272    /// Returns the position where that value is present, or the position where it can be inserted
273    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
274    ///
275    /// Computes in **O(log(n))** time.
276    #[inline]
277    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
278    where
279        F: FnMut(&'a K, &'a V) -> B,
280        B: Ord,
281    {
282        self.binary_search_by(|k, v| f(k, v).cmp(b))
283    }
284
285    /// Checks if the keys of this slice are sorted.
286    #[inline]
287    pub fn is_sorted(&self) -> bool
288    where
289        K: PartialOrd,
290    {
291        self.entries.is_sorted_by(|a, b| a.key <= b.key)
292    }
293
294    /// Checks if this slice is sorted using the given comparator function.
295    #[inline]
296    pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool
297    where
298        F: FnMut(&'a K, &'a V, &'a K, &'a V) -> bool,
299    {
300        self.entries
301            .is_sorted_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value))
302    }
303
304    /// Checks if this slice is sorted using the given sort-key function.
305    #[inline]
306    pub fn is_sorted_by_key<'a, F, T>(&'a self, mut sort_key: F) -> bool
307    where
308        F: FnMut(&'a K, &'a V) -> T,
309        T: PartialOrd,
310    {
311        self.entries
312            .is_sorted_by_key(move |a| sort_key(&a.key, &a.value))
313    }
314
315    /// Returns the index of the partition point of a sorted map according to the given predicate
316    /// (the index of the first element of the second partition).
317    ///
318    /// See [`slice::partition_point`] for more details.
319    ///
320    /// Computes in **O(log(n))** time.
321    #[must_use]
322    pub fn partition_point<P>(&self, mut pred: P) -> usize
323    where
324        P: FnMut(&K, &V) -> bool,
325    {
326        self.entries
327            .partition_point(move |a| pred(&a.key, &a.value))
328    }
329
330    /// Get an array of `N` key-value pairs by `N` indices
331    ///
332    /// Valid indices are *0 <= index < self.len()* and each index needs to be unique.
333    pub fn get_disjoint_mut<const N: usize>(
334        &mut self,
335        indices: [usize; N],
336    ) -> Result<[(&K, &mut V); N], GetDisjointMutError> {
337        let indices = indices.map(Some);
338        let empty_tail = Self::new_mut();
339        let key_values = Self::get_disjoint_opt_mut(self, empty_tail, indices)?;
340        Ok(key_values.map(Option::unwrap))
341    }
342
343    #[allow(unsafe_code)]
344    pub(crate) fn get_disjoint_opt_mut<'a, const N: usize>(
345        head: &mut Self,
346        tail: &mut Self,
347        indices: [Option<usize>; N],
348    ) -> Result<[Option<(&'a K, &'a mut V)>; N], GetDisjointMutError> {
349        let mid = head.len();
350        let len = mid + tail.len();
351
352        // SAFETY: Can't allow duplicate indices as we would return several mutable refs to the same data.
353        for i in 0..N {
354            if let Some(idx) = indices[i] {
355                if idx >= len {
356                    return Err(GetDisjointMutError::IndexOutOfBounds);
357                } else if indices[..i].contains(&Some(idx)) {
358                    return Err(GetDisjointMutError::OverlappingIndices);
359                }
360            }
361        }
362
363        let head_ptr = head.entries.as_mut_ptr();
364        let tail_ptr = tail.entries.as_mut_ptr();
365        let out = indices.map(|idx_opt| {
366            match idx_opt {
367                Some(idx) => {
368                    // SAFETY: The base pointers are valid as they come from slices and the reference is always
369                    // in-bounds & unique as we've already checked the indices above.
370                    unsafe {
371                        let ptr = match idx.checked_sub(mid) {
372                            None => head_ptr.add(idx),
373                            Some(tidx) => tail_ptr.add(tidx),
374                        };
375                        Some((*ptr).ref_mut())
376                    }
377                }
378                None => None,
379            }
380        });
381
382        Ok(out)
383    }
384}
385
386impl<'a, K, V> IntoIterator for &'a Slice<K, V> {
387    type IntoIter = Iter<'a, K, V>;
388    type Item = (&'a K, &'a V);
389
390    fn into_iter(self) -> Self::IntoIter {
391        self.iter()
392    }
393}
394
395impl<'a, K, V> IntoIterator for &'a mut Slice<K, V> {
396    type IntoIter = IterMut<'a, K, V>;
397    type Item = (&'a K, &'a mut V);
398
399    fn into_iter(self) -> Self::IntoIter {
400        self.iter_mut()
401    }
402}
403
404impl<K, V> IntoIterator for Box<Slice<K, V>> {
405    type IntoIter = IntoIter<K, V>;
406    type Item = (K, V);
407
408    fn into_iter(self) -> Self::IntoIter {
409        IntoIter::new(self.into_entries())
410    }
411}
412
413impl<K, V> Default for &'_ Slice<K, V> {
414    fn default() -> Self {
415        Slice::from_slice(&[])
416    }
417}
418
419impl<K, V> Default for &'_ mut Slice<K, V> {
420    fn default() -> Self {
421        Slice::from_mut_slice(&mut [])
422    }
423}
424
425impl<K, V> Default for Box<Slice<K, V>> {
426    fn default() -> Self {
427        Slice::from_boxed(Box::default())
428    }
429}
430
431impl<K: Clone, V: Clone> Clone for Box<Slice<K, V>> {
432    fn clone(&self) -> Self {
433        Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
434    }
435}
436
437impl<K: Copy, V: Copy> From<&Slice<K, V>> for Box<Slice<K, V>> {
438    fn from(slice: &Slice<K, V>) -> Self {
439        Slice::from_boxed(Box::from(&slice.entries))
440    }
441}
442
443impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Slice<K, V> {
444    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445        f.debug_list().entries(self).finish()
446    }
447}
448
449impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for Slice<K, V>
450where
451    K: PartialEq<K2>,
452    V: PartialEq<V2>,
453{
454    fn eq(&self, other: &Slice<K2, V2>) -> bool {
455        slice_eq(&self.entries, &other.entries, |b1, b2| {
456            b1.key == b2.key && b1.value == b2.value
457        })
458    }
459}
460
461impl<K, V, K2, V2> PartialEq<[(K2, V2)]> for Slice<K, V>
462where
463    K: PartialEq<K2>,
464    V: PartialEq<V2>,
465{
466    fn eq(&self, other: &[(K2, V2)]) -> bool {
467        slice_eq(&self.entries, other, |b, t| b.key == t.0 && b.value == t.1)
468    }
469}
470
471impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V)]
472where
473    K: PartialEq<K2>,
474    V: PartialEq<V2>,
475{
476    fn eq(&self, other: &Slice<K2, V2>) -> bool {
477        slice_eq(self, &other.entries, |t, b| t.0 == b.key && t.1 == b.value)
478    }
479}
480
481impl<K, V, K2, V2, const N: usize> PartialEq<[(K2, V2); N]> for Slice<K, V>
482where
483    K: PartialEq<K2>,
484    V: PartialEq<V2>,
485{
486    fn eq(&self, other: &[(K2, V2); N]) -> bool {
487        <Self as PartialEq<[_]>>::eq(self, other)
488    }
489}
490
491impl<K, V, const N: usize, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V); N]
492where
493    K: PartialEq<K2>,
494    V: PartialEq<V2>,
495{
496    fn eq(&self, other: &Slice<K2, V2>) -> bool {
497        <[_] as PartialEq<_>>::eq(self, other)
498    }
499}
500
501impl<K: Eq, V: Eq> Eq for Slice<K, V> {}
502
503impl<K: PartialOrd, V: PartialOrd> PartialOrd for Slice<K, V> {
504    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
505        self.iter().partial_cmp(other)
506    }
507}
508
509impl<K: Ord, V: Ord> Ord for Slice<K, V> {
510    fn cmp(&self, other: &Self) -> Ordering {
511        self.iter().cmp(other)
512    }
513}
514
515impl<K: Hash, V: Hash> Hash for Slice<K, V> {
516    fn hash<H: Hasher>(&self, state: &mut H) {
517        self.len().hash(state);
518        for (key, value) in self {
519            key.hash(state);
520            value.hash(state);
521        }
522    }
523}
524
525impl<K, V> Index<usize> for Slice<K, V> {
526    type Output = V;
527
528    fn index(&self, index: usize) -> &V {
529        &self.entries[index].value
530    }
531}
532
533impl<K, V> IndexMut<usize> for Slice<K, V> {
534    fn index_mut(&mut self, index: usize) -> &mut V {
535        &mut self.entries[index].value
536    }
537}
538
539// We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts
540// both upstream with `Index<usize>` and downstream with `Index<&Q>`.
541// Instead, we repeat the implementations for all the core range types.
542macro_rules! impl_index {
543    ($($range:ty),*) => {$(
544        impl<K, V> Index<$range> for Slice<K, V> {
545            type Output = Slice<K, V>;
546
547            fn index(&self, range: $range) -> &Self {
548                Self::from_slice(&self.entries[range])
549            }
550        }
551
552        impl<K, V> IndexMut<$range> for Slice<K, V> {
553            fn index_mut(&mut self, range: $range) -> &mut Self {
554                Self::from_mut_slice(&mut self.entries[range])
555            }
556        }
557    )*}
558}
559impl_index!(
560    ops::Range<usize>,
561    ops::RangeFrom<usize>,
562    ops::RangeFull,
563    ops::RangeInclusive<usize>,
564    ops::RangeTo<usize>,
565    ops::RangeToInclusive<usize>,
566    (Bound<usize>, Bound<usize>)
567);
568
569#[cfg(test)]
570mod tests {
571    use super::*;
572    use crate::RingMap;
573    use alloc::vec::Vec;
574
575    #[test]
576    fn slice_index() {
577        fn check(vec_slice: &[(i32, i32)], map_slice: &Slice<i32, i32>) {
578            itertools::assert_equal(
579                vec_slice.iter().copied(),
580                map_slice.iter().map(|(&k, &v)| (k, v)),
581            );
582            itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys());
583            itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values());
584        }
585
586        let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
587        let map: RingMap<i32, i32> = vec.iter().cloned().collect();
588        let (slice, tail) = map.as_slices();
589        assert!(tail.is_empty());
590
591        // RangeFull
592        check(&vec[..], &slice[..]);
593
594        for i in 0usize..10 {
595            // Index
596            assert_eq!(vec[i].1, map[i]);
597            assert_eq!(vec[i].1, slice[i]);
598            assert_eq!(map[&(i as i32)], map[i]);
599            assert_eq!(map[&(i as i32)], slice[i]);
600
601            // RangeFrom
602            check(&vec[i..], &slice[i..]);
603
604            // RangeTo
605            check(&vec[..i], &slice[..i]);
606
607            // RangeToInclusive
608            check(&vec[..=i], &slice[..=i]);
609
610            // (Bound<usize>, Bound<usize>)
611            let bounds = (Bound::Excluded(i), Bound::Unbounded);
612            check(&vec[i + 1..], &slice[bounds]);
613
614            for j in i..=10 {
615                // Range
616                check(&vec[i..j], &slice[i..j]);
617            }
618
619            for j in i..10 {
620                // RangeInclusive
621                check(&vec[i..=j], &slice[i..=j]);
622            }
623        }
624    }
625
626    fn as_mut_slice<K, V>(map: &mut RingMap<K, V>) -> &mut Slice<K, V> {
627        let (slice, tail) = map.as_mut_slices();
628        assert!(tail.is_empty());
629        slice
630    }
631
632    #[test]
633    fn slice_index_mut() {
634        fn check_mut(vec_slice: &[(i32, i32)], map_slice: &mut Slice<i32, i32>) {
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: RingMap<i32, i32> = vec.iter().cloned().collect();
647        let mut map2 = map.clone();
648        let slice = as_mut_slice(&mut map2);
649
650        // RangeFull
651        check_mut(&vec[..], &mut slice[..]);
652
653        for i in 0usize..10 {
654            // IndexMut
655            assert_eq!(&mut map[i], &mut slice[i]);
656
657            // RangeFrom
658            check_mut(&vec[i..], &mut slice[i..]);
659
660            // RangeTo
661            check_mut(&vec[..i], &mut slice[..i]);
662
663            // RangeToInclusive
664            check_mut(&vec[..=i], &mut slice[..=i]);
665
666            // (Bound<usize>, Bound<usize>)
667            let bounds = (Bound::Excluded(i), Bound::Unbounded);
668            check_mut(&vec[i + 1..], &mut slice[bounds]);
669
670            for j in i..=10 {
671                // Range
672                check_mut(&vec[i..j], &mut slice[i..j]);
673            }
674
675            for j in i..10 {
676                // RangeInclusive
677                check_mut(&vec[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: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
699        let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
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: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
724        let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
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: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
741        let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
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: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
761        let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
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: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
778        let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
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: RingMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
795        let slice: &mut Slice<i32, i32> = as_mut_slice(&mut map);
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}