indexmap/map/
slice.rs

1use super::{
2    Bucket, Entries, IndexMap, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values,
3    ValuesMut,
4};
5use crate::util::try_simplify_range;
6
7use alloc::boxed::Box;
8use alloc::vec::Vec;
9use core::cmp::Ordering;
10use core::fmt;
11use core::hash::{Hash, Hasher};
12use core::ops::{self, Bound, Index, IndexMut, RangeBounds};
13
14/// A dynamically-sized slice of key-value pairs in an [`IndexMap`].
15///
16/// This supports indexed operations much like a `[(K, V)]` slice,
17/// but not any hashed operations on the map keys.
18///
19/// Unlike `IndexMap`, `Slice` does consider the order for [`PartialEq`]
20/// and [`Eq`], and it also implements [`PartialOrd`], [`Ord`], and [`Hash`].
21#[repr(transparent)]
22pub struct Slice<K, V> {
23    pub(crate) entries: [Bucket<K, V>],
24}
25
26// SAFETY: `Slice<K, V>` is a transparent wrapper around `[Bucket<K, V>]`,
27// and reference lifetimes are bound together in function signatures.
28#[allow(unsafe_code)]
29impl<K, V> Slice<K, V> {
30    pub(super) 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) fn from_mut_slice(entries: &mut [Bucket<K, V>]) -> &mut Self {
35        unsafe { &mut *(entries as *mut [Bucket<K, V>] as *mut Self) }
36    }
37
38    pub(super) fn from_boxed(entries: Box<[Bucket<K, V>]>) -> Box<Self> {
39        unsafe { Box::from_raw(Box::into_raw(entries) as *mut Self) }
40    }
41
42    fn into_boxed(self: Box<Self>) -> Box<[Bucket<K, V>]> {
43        unsafe { Box::from_raw(Box::into_raw(self) as *mut [Bucket<K, V>]) }
44    }
45}
46
47impl<K, V> Slice<K, V> {
48    pub(crate) fn into_entries(self: Box<Self>) -> Vec<Bucket<K, V>> {
49        self.into_boxed().into_vec()
50    }
51
52    /// Returns an empty slice.
53    pub const fn new<'a>() -> &'a Self {
54        Self::from_slice(&[])
55    }
56
57    /// Returns an empty mutable slice.
58    pub 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 fn first(&self) -> Option<(&K, &V)> {
106        self.entries.first().map(Bucket::refs)
107    }
108
109    /// Get the first key-value pair, with mutable access to the value.
110    pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
111        self.entries.first_mut().map(Bucket::ref_mut)
112    }
113
114    /// Get the last key-value pair.
115    pub fn last(&self) -> Option<(&K, &V)> {
116        self.entries.last().map(Bucket::refs)
117    }
118
119    /// Get the last key-value pair, with mutable access to the value.
120    pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
121        self.entries.last_mut().map(Bucket::ref_mut)
122    }
123
124    /// Divides one slice into two at an index.
125    ///
126    /// ***Panics*** if `index > len`.
127    pub fn split_at(&self, index: usize) -> (&Self, &Self) {
128        let (first, second) = self.entries.split_at(index);
129        (Self::from_slice(first), Self::from_slice(second))
130    }
131
132    /// Divides one mutable slice into two at an index.
133    ///
134    /// ***Panics*** if `index > len`.
135    pub fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) {
136        let (first, second) = self.entries.split_at_mut(index);
137        (Self::from_mut_slice(first), Self::from_mut_slice(second))
138    }
139
140    /// Returns the first key-value pair and the rest of the slice,
141    /// or `None` if it is empty.
142    pub fn split_first(&self) -> Option<((&K, &V), &Self)> {
143        if let [first, rest @ ..] = &self.entries {
144            Some((first.refs(), Self::from_slice(rest)))
145        } else {
146            None
147        }
148    }
149
150    /// Returns the first key-value pair and the rest of the slice,
151    /// with mutable access to the value, or `None` if it is empty.
152    pub fn split_first_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
153        if let [first, rest @ ..] = &mut self.entries {
154            Some((first.ref_mut(), Self::from_mut_slice(rest)))
155        } else {
156            None
157        }
158    }
159
160    /// Returns the last key-value pair and the rest of the slice,
161    /// or `None` if it is empty.
162    pub fn split_last(&self) -> Option<((&K, &V), &Self)> {
163        if let [rest @ .., last] = &self.entries {
164            Some((last.refs(), Self::from_slice(rest)))
165        } else {
166            None
167        }
168    }
169
170    /// Returns the last key-value pair and the rest of the slice,
171    /// with mutable access to the value, or `None` if it is empty.
172    pub fn split_last_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
173        if let [rest @ .., last] = &mut self.entries {
174            Some((last.ref_mut(), Self::from_mut_slice(rest)))
175        } else {
176            None
177        }
178    }
179
180    /// Return an iterator over the key-value pairs of the map slice.
181    pub fn iter(&self) -> Iter<'_, K, V> {
182        Iter::new(&self.entries)
183    }
184
185    /// Return an iterator over the key-value pairs of the map slice.
186    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
187        IterMut::new(&mut self.entries)
188    }
189
190    /// Return an iterator over the keys of the map slice.
191    pub fn keys(&self) -> Keys<'_, K, V> {
192        Keys::new(&self.entries)
193    }
194
195    /// Return an owning iterator over the keys of the map slice.
196    pub fn into_keys(self: Box<Self>) -> IntoKeys<K, V> {
197        IntoKeys::new(self.into_entries())
198    }
199
200    /// Return an iterator over the values of the map slice.
201    pub fn values(&self) -> Values<'_, K, V> {
202        Values::new(&self.entries)
203    }
204
205    /// Return an iterator over mutable references to the the values of the map slice.
206    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
207        ValuesMut::new(&mut self.entries)
208    }
209
210    /// Return an owning iterator over the values of the map slice.
211    pub fn into_values(self: Box<Self>) -> IntoValues<K, V> {
212        IntoValues::new(self.into_entries())
213    }
214
215    /// Search over a sorted map for a key.
216    ///
217    /// Returns the position where that key is present, or the position where it can be inserted to
218    /// maintain the sort. See [`slice::binary_search`] for more details.
219    ///
220    /// Computes in **O(log(n))** time, which is notably less scalable than looking the key up in
221    /// the map this is a slice from using [`IndexMap::get_index_of`], but this can also position
222    /// missing keys.
223    pub fn binary_search_keys(&self, x: &K) -> Result<usize, usize>
224    where
225        K: Ord,
226    {
227        self.binary_search_by(|p, _| p.cmp(x))
228    }
229
230    /// Search over a sorted map with a comparator function.
231    ///
232    /// Returns the position where that value is present, or the position where it can be inserted
233    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
234    ///
235    /// Computes in **O(log(n))** time.
236    #[inline]
237    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
238    where
239        F: FnMut(&'a K, &'a V) -> Ordering,
240    {
241        self.entries.binary_search_by(move |a| f(&a.key, &a.value))
242    }
243
244    /// Search over a sorted map with an extraction function.
245    ///
246    /// Returns the position where that value is present, or the position where it can be inserted
247    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
248    ///
249    /// Computes in **O(log(n))** time.
250    #[inline]
251    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
252    where
253        F: FnMut(&'a K, &'a V) -> B,
254        B: Ord,
255    {
256        self.binary_search_by(|k, v| f(k, v).cmp(b))
257    }
258
259    /// Returns the index of the partition point of a sorted map according to the given predicate
260    /// (the index of the first element of the second partition).
261    ///
262    /// See [`slice::partition_point`] for more details.
263    ///
264    /// Computes in **O(log(n))** time.
265    #[must_use]
266    pub fn partition_point<P>(&self, mut pred: P) -> usize
267    where
268        P: FnMut(&K, &V) -> bool,
269    {
270        self.entries
271            .partition_point(move |a| pred(&a.key, &a.value))
272    }
273}
274
275impl<'a, K, V> IntoIterator for &'a Slice<K, V> {
276    type IntoIter = Iter<'a, K, V>;
277    type Item = (&'a K, &'a V);
278
279    fn into_iter(self) -> Self::IntoIter {
280        self.iter()
281    }
282}
283
284impl<'a, K, V> IntoIterator for &'a mut Slice<K, V> {
285    type IntoIter = IterMut<'a, K, V>;
286    type Item = (&'a K, &'a mut V);
287
288    fn into_iter(self) -> Self::IntoIter {
289        self.iter_mut()
290    }
291}
292
293impl<K, V> IntoIterator for Box<Slice<K, V>> {
294    type IntoIter = IntoIter<K, V>;
295    type Item = (K, V);
296
297    fn into_iter(self) -> Self::IntoIter {
298        IntoIter::new(self.into_entries())
299    }
300}
301
302impl<K, V> Default for &'_ Slice<K, V> {
303    fn default() -> Self {
304        Slice::from_slice(&[])
305    }
306}
307
308impl<K, V> Default for &'_ mut Slice<K, V> {
309    fn default() -> Self {
310        Slice::from_mut_slice(&mut [])
311    }
312}
313
314impl<K, V> Default for Box<Slice<K, V>> {
315    fn default() -> Self {
316        Slice::from_boxed(Box::default())
317    }
318}
319
320impl<K: Clone, V: Clone> Clone for Box<Slice<K, V>> {
321    fn clone(&self) -> Self {
322        Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
323    }
324}
325
326impl<K: Copy, V: Copy> From<&Slice<K, V>> for Box<Slice<K, V>> {
327    fn from(slice: &Slice<K, V>) -> Self {
328        Slice::from_boxed(Box::from(&slice.entries))
329    }
330}
331
332impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Slice<K, V> {
333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334        f.debug_list().entries(self).finish()
335    }
336}
337
338impl<K: PartialEq, V: PartialEq> PartialEq for Slice<K, V> {
339    fn eq(&self, other: &Self) -> bool {
340        self.len() == other.len() && self.iter().eq(other)
341    }
342}
343
344impl<K: Eq, V: Eq> Eq for Slice<K, V> {}
345
346impl<K: PartialOrd, V: PartialOrd> PartialOrd for Slice<K, V> {
347    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
348        self.iter().partial_cmp(other)
349    }
350}
351
352impl<K: Ord, V: Ord> Ord for Slice<K, V> {
353    fn cmp(&self, other: &Self) -> Ordering {
354        self.iter().cmp(other)
355    }
356}
357
358impl<K: Hash, V: Hash> Hash for Slice<K, V> {
359    fn hash<H: Hasher>(&self, state: &mut H) {
360        self.len().hash(state);
361        for (key, value) in self {
362            key.hash(state);
363            value.hash(state);
364        }
365    }
366}
367
368impl<K, V> Index<usize> for Slice<K, V> {
369    type Output = V;
370
371    fn index(&self, index: usize) -> &V {
372        &self.entries[index].value
373    }
374}
375
376impl<K, V> IndexMut<usize> for Slice<K, V> {
377    fn index_mut(&mut self, index: usize) -> &mut V {
378        &mut self.entries[index].value
379    }
380}
381
382// We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts
383// both upstream with `Index<usize>` and downstream with `Index<&Q>`.
384// Instead, we repeat the implementations for all the core range types.
385macro_rules! impl_index {
386    ($($range:ty),*) => {$(
387        impl<K, V, S> Index<$range> for IndexMap<K, V, S> {
388            type Output = Slice<K, V>;
389
390            fn index(&self, range: $range) -> &Self::Output {
391                Slice::from_slice(&self.as_entries()[range])
392            }
393        }
394
395        impl<K, V, S> IndexMut<$range> for IndexMap<K, V, S> {
396            fn index_mut(&mut self, range: $range) -> &mut Self::Output {
397                Slice::from_mut_slice(&mut self.as_entries_mut()[range])
398            }
399        }
400
401        impl<K, V> Index<$range> for Slice<K, V> {
402            type Output = Slice<K, V>;
403
404            fn index(&self, range: $range) -> &Self {
405                Self::from_slice(&self.entries[range])
406            }
407        }
408
409        impl<K, V> IndexMut<$range> for Slice<K, V> {
410            fn index_mut(&mut self, range: $range) -> &mut Self {
411                Self::from_mut_slice(&mut self.entries[range])
412            }
413        }
414    )*}
415}
416impl_index!(
417    ops::Range<usize>,
418    ops::RangeFrom<usize>,
419    ops::RangeFull,
420    ops::RangeInclusive<usize>,
421    ops::RangeTo<usize>,
422    ops::RangeToInclusive<usize>,
423    (Bound<usize>, Bound<usize>)
424);
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429
430    #[test]
431    fn slice_index() {
432        fn check(
433            vec_slice: &[(i32, i32)],
434            map_slice: &Slice<i32, i32>,
435            sub_slice: &Slice<i32, i32>,
436        ) {
437            assert_eq!(map_slice as *const _, sub_slice as *const _);
438            itertools::assert_equal(
439                vec_slice.iter().copied(),
440                map_slice.iter().map(|(&k, &v)| (k, v)),
441            );
442            itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys());
443            itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values());
444        }
445
446        let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
447        let map: IndexMap<i32, i32> = vec.iter().cloned().collect();
448        let slice = map.as_slice();
449
450        // RangeFull
451        check(&vec[..], &map[..], &slice[..]);
452
453        for i in 0usize..10 {
454            // Index
455            assert_eq!(vec[i].1, map[i]);
456            assert_eq!(vec[i].1, slice[i]);
457            assert_eq!(map[&(i as i32)], map[i]);
458            assert_eq!(map[&(i as i32)], slice[i]);
459
460            // RangeFrom
461            check(&vec[i..], &map[i..], &slice[i..]);
462
463            // RangeTo
464            check(&vec[..i], &map[..i], &slice[..i]);
465
466            // RangeToInclusive
467            check(&vec[..=i], &map[..=i], &slice[..=i]);
468
469            // (Bound<usize>, Bound<usize>)
470            let bounds = (Bound::Excluded(i), Bound::Unbounded);
471            check(&vec[i + 1..], &map[bounds], &slice[bounds]);
472
473            for j in i..=10 {
474                // Range
475                check(&vec[i..j], &map[i..j], &slice[i..j]);
476            }
477
478            for j in i..10 {
479                // RangeInclusive
480                check(&vec[i..=j], &map[i..=j], &slice[i..=j]);
481            }
482        }
483    }
484
485    #[test]
486    fn slice_index_mut() {
487        fn check_mut(
488            vec_slice: &[(i32, i32)],
489            map_slice: &mut Slice<i32, i32>,
490            sub_slice: &mut Slice<i32, i32>,
491        ) {
492            assert_eq!(map_slice, sub_slice);
493            itertools::assert_equal(
494                vec_slice.iter().copied(),
495                map_slice.iter_mut().map(|(&k, &mut v)| (k, v)),
496            );
497            itertools::assert_equal(
498                vec_slice.iter().map(|&(_, v)| v),
499                map_slice.values_mut().map(|&mut v| v),
500            );
501        }
502
503        let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
504        let mut map: IndexMap<i32, i32> = vec.iter().cloned().collect();
505        let mut map2 = map.clone();
506        let slice = map2.as_mut_slice();
507
508        // RangeFull
509        check_mut(&vec[..], &mut map[..], &mut slice[..]);
510
511        for i in 0usize..10 {
512            // IndexMut
513            assert_eq!(&mut map[i], &mut slice[i]);
514
515            // RangeFrom
516            check_mut(&vec[i..], &mut map[i..], &mut slice[i..]);
517
518            // RangeTo
519            check_mut(&vec[..i], &mut map[..i], &mut slice[..i]);
520
521            // RangeToInclusive
522            check_mut(&vec[..=i], &mut map[..=i], &mut slice[..=i]);
523
524            // (Bound<usize>, Bound<usize>)
525            let bounds = (Bound::Excluded(i), Bound::Unbounded);
526            check_mut(&vec[i + 1..], &mut map[bounds], &mut slice[bounds]);
527
528            for j in i..=10 {
529                // Range
530                check_mut(&vec[i..j], &mut map[i..j], &mut slice[i..j]);
531            }
532
533            for j in i..10 {
534                // RangeInclusive
535                check_mut(&vec[i..=j], &mut map[i..=j], &mut slice[i..=j]);
536            }
537        }
538    }
539}