Debian Codegraph @

debian/rust-vendor/indexmap/src/map/slice.rs

raw
1 use super::{
2 Bucket, IndexMap, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values, ValuesMut,
3 };
4 use crate::GetDisjointMutError;
5 use crate::util::{slice_eq, try_simplify_range};
6
7 use alloc::boxed::Box;
8 use alloc::vec::Vec;
9 use core::cmp::Ordering;
10 use core::fmt;
11 use core::hash::{Hash, Hasher};
12 use 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)]
22 pub 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)]
29 impl<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
47 impl<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 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 // TODO(MSRV 1.86): use the standard library's `slice::get_disjoint_mut`
354 let entries = super::disjoint::get_disjoint_mut(&mut self.entries, indices)?;
355 Ok(entries.map(Bucket::ref_mut))
356 }
357 }
358
359 impl<'a, K, V> IntoIterator for &'a Slice<K, V> {
360 type IntoIter = Iter<'a, K, V>;
361 type Item = (&'a K, &'a V);
362
363 fn into_iter(self) -> Self::IntoIter {
364 self.iter()
365 }
366 }
367
368 impl<'a, K, V> IntoIterator for &'a mut Slice<K, V> {
369 type IntoIter = IterMut<'a, K, V>;
370 type Item = (&'a K, &'a mut V);
371
372 fn into_iter(self) -> Self::IntoIter {
373 self.iter_mut()
374 }
375 }
376
377 impl<K, V> IntoIterator for Box<Slice<K, V>> {
378 type IntoIter = IntoIter<K, V>;
379 type Item = (K, V);
380
381 fn into_iter(self) -> Self::IntoIter {
382 IntoIter::new(self.into_entries())
383 }
384 }
385
386 impl<K, V> Default for &'_ Slice<K, V> {
387 fn default() -> Self {
388 Slice::from_slice(&[])
389 }
390 }
391
392 impl<K, V> Default for &'_ mut Slice<K, V> {
393 fn default() -> Self {
394 Slice::from_mut_slice(&mut [])
395 }
396 }
397
398 impl<K, V> Default for Box<Slice<K, V>> {
399 fn default() -> Self {
400 Slice::from_boxed(Box::default())
401 }
402 }
403
404 impl<K: Clone, V: Clone> Clone for Box<Slice<K, V>> {
405 fn clone(&self) -> Self {
406 Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
407 }
408 }
409
410 impl<K: Copy, V: Copy> From<&Slice<K, V>> for Box<Slice<K, V>> {
411 fn from(slice: &Slice<K, V>) -> Self {
412 Slice::from_boxed(Box::from(&slice.entries))
413 }
414 }
415
416 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Slice<K, V> {
417 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418 f.debug_list().entries(self).finish()
419 }
420 }
421
422 impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for Slice<K, V>
423 where
424 K: PartialEq<K2>,
425 V: PartialEq<V2>,
426 {
427 fn eq(&self, other: &Slice<K2, V2>) -> bool {
428 slice_eq(&self.entries, &other.entries, |b1, b2| {
429 b1.key == b2.key && b1.value == b2.value
430 })
431 }
432 }
433
434 impl<K, V, K2, V2> PartialEq<[(K2, V2)]> for Slice<K, V>
435 where
436 K: PartialEq<K2>,
437 V: PartialEq<V2>,
438 {
439 fn eq(&self, other: &[(K2, V2)]) -> bool {
440 slice_eq(&self.entries, other, |b, t| b.key == t.0 && b.value == t.1)
441 }
442 }
443
444 impl<K, V, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V)]
445 where
446 K: PartialEq<K2>,
447 V: PartialEq<V2>,
448 {
449 fn eq(&self, other: &Slice<K2, V2>) -> bool {
450 slice_eq(self, &other.entries, |t, b| t.0 == b.key && t.1 == b.value)
451 }
452 }
453
454 impl<K, V, K2, V2, const N: usize> PartialEq<[(K2, V2); N]> for Slice<K, V>
455 where
456 K: PartialEq<K2>,
457 V: PartialEq<V2>,
458 {
459 fn eq(&self, other: &[(K2, V2); N]) -> bool {
460 <Self as PartialEq<[_]>>::eq(self, other)
461 }
462 }
463
464 impl<K, V, const N: usize, K2, V2> PartialEq<Slice<K2, V2>> for [(K, V); N]
465 where
466 K: PartialEq<K2>,
467 V: PartialEq<V2>,
468 {
469 fn eq(&self, other: &Slice<K2, V2>) -> bool {
470 <[_] as PartialEq<_>>::eq(self, other)
471 }
472 }
473
474 impl<K: Eq, V: Eq> Eq for Slice<K, V> {}
475
476 impl<K: PartialOrd, V: PartialOrd> PartialOrd for Slice<K, V> {
477 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
478 self.iter().partial_cmp(other)
479 }
480 }
481
482 impl<K: Ord, V: Ord> Ord for Slice<K, V> {
483 fn cmp(&self, other: &Self) -> Ordering {
484 self.iter().cmp(other)
485 }
486 }
487
488 impl<K: Hash, V: Hash> Hash for Slice<K, V> {
489 fn hash<H: Hasher>(&self, state: &mut H) {
490 self.len().hash(state);
491 for (key, value) in self {
492 key.hash(state);
493 value.hash(state);
494 }
495 }
496 }
497
498 impl<K, V> Index<usize> for Slice<K, V> {
499 type Output = V;
500
501 fn index(&self, index: usize) -> &V {
502 &self.entries[index].value
503 }
504 }
505
506 impl<K, V> IndexMut<usize> for Slice<K, V> {
507 fn index_mut(&mut self, index: usize) -> &mut V {
508 &mut self.entries[index].value
509 }
510 }
511
512 // We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts
513 // both upstream with `Index<usize>` and downstream with `Index<&Q>`.
514 // Instead, we repeat the implementations for all the core range types.
515 macro_rules! impl_index {
516 ($($range:ty),*) => {$(
517 impl<K, V, S> Index<$range> for IndexMap<K, V, S> {
518 type Output = Slice<K, V>;
519
520 fn index(&self, range: $range) -> &Self::Output {
521 Slice::from_slice(&self.as_entries()[range])
522 }
523 }
524
525 impl<K, V, S> IndexMut<$range> for IndexMap<K, V, S> {
526 fn index_mut(&mut self, range: $range) -> &mut Self::Output {
527 Slice::from_mut_slice(&mut self.as_entries_mut()[range])
528 }
529 }
530
531 impl<K, V> Index<$range> for Slice<K, V> {
532 type Output = Slice<K, V>;
533
534 fn index(&self, range: $range) -> &Self {
535 Self::from_slice(&self.entries[range])
536 }
537 }
538
539 impl<K, V> IndexMut<$range> for Slice<K, V> {
540 fn index_mut(&mut self, range: $range) -> &mut Self {
541 Self::from_mut_slice(&mut self.entries[range])
542 }
543 }
544 )*}
545 }
546 impl_index!(
547 ops::Range<usize>,
548 ops::RangeFrom<usize>,
549 ops::RangeFull,
550 ops::RangeInclusive<usize>,
551 ops::RangeTo<usize>,
552 ops::RangeToInclusive<usize>,
553 (Bound<usize>, Bound<usize>)
554 );
555
556 #[cfg(test)]
557 mod tests {
558 use super::*;
559
560 #[test]
561 fn slice_index() {
562 fn check(
563 vec_slice: &[(i32, i32)],
564 map_slice: &Slice<i32, i32>,
565 sub_slice: &Slice<i32, i32>,
566 ) {
567 assert_eq!(map_slice as *const _, sub_slice as *const _);
568 itertools::assert_equal(
569 vec_slice.iter().copied(),
570 map_slice.iter().map(|(&k, &v)| (k, v)),
571 );
572 itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys());
573 itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values());
574 }
575
576 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
577 let map: IndexMap<i32, i32> = vec.iter().cloned().collect();
578 let slice = map.as_slice();
579
580 // RangeFull
581 #[expect(clippy::redundant_slicing)]
582 check(&vec[..], &map[..], &slice[..]);
583
584 for i in 0usize..10 {
585 // Index
586 assert_eq!(vec[i].1, map[i]);
587 assert_eq!(vec[i].1, slice[i]);
588 assert_eq!(map[&(i as i32)], map[i]);
589 assert_eq!(map[&(i as i32)], slice[i]);
590
591 // RangeFrom
592 check(&vec[i..], &map[i..], &slice[i..]);
593
594 // RangeTo
595 check(&vec[..i], &map[..i], &slice[..i]);
596
597 // RangeToInclusive
598 check(&vec[..=i], &map[..=i], &slice[..=i]);
599
600 // (Bound<usize>, Bound<usize>)
601 let bounds = (Bound::Excluded(i), Bound::Unbounded);
602 check(&vec[i + 1..], &map[bounds], &slice[bounds]);
603
604 for j in i..=10 {
605 // Range
606 check(&vec[i..j], &map[i..j], &slice[i..j]);
607 }
608
609 for j in i..10 {
610 // RangeInclusive
611 check(&vec[i..=j], &map[i..=j], &slice[i..=j]);
612 }
613 }
614 }
615
616 #[test]
617 fn slice_index_mut() {
618 fn check_mut(
619 vec_slice: &[(i32, i32)],
620 map_slice: &mut Slice<i32, i32>,
621 sub_slice: &mut Slice<i32, i32>,
622 ) {
623 assert_eq!(map_slice, sub_slice);
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: IndexMap<i32, i32> = vec.iter().cloned().collect();
636 let mut map2 = map.clone();
637 let slice = map2.as_mut_slice();
638
639 // RangeFull
640 check_mut(&vec[..], &mut map[..], &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 map[i..], &mut slice[i..]);
648
649 // RangeTo
650 check_mut(&vec[..i], &mut map[..i], &mut slice[..i]);
651
652 // RangeToInclusive
653 check_mut(&vec[..=i], &mut map[..=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 map[bounds], &mut slice[bounds]);
658
659 for j in i..=10 {
660 // Range
661 check_mut(&vec[i..j], &mut map[i..j], &mut slice[i..j]);
662 }
663
664 for j in i..10 {
665 // RangeInclusive
666 check_mut(&vec[i..=j], &mut map[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: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
688 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
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: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
713 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
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: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
730 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
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: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
750 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
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: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
767 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
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: IndexMap<i32, i32> = (0..10).map(|i| (i, i * i)).collect();
784 let slice: &mut Slice<i32, i32> = map.as_mut_slice();
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 }