Coverage Report

Created: 2025-08-28 06:25

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