indexmap/set/
slice.rs

1use super::{Bucket, IndexSet, IntoIter, Iter};
2use crate::util::{slice_eq, try_simplify_range};
3
4use alloc::boxed::Box;
5use alloc::vec::Vec;
6use core::cmp::Ordering;
7use core::fmt;
8use core::hash::{Hash, Hasher};
9use core::ops::{self, Bound, Index, RangeBounds};
10
11/// A dynamically-sized slice of values in an [`IndexSet`].
12///
13/// This supports indexed operations much like a `[T]` slice,
14/// but not any hashed operations on the values.
15///
16/// Unlike `IndexSet`, `Slice` does consider the order for [`PartialEq`]
17/// and [`Eq`], and it also implements [`PartialOrd`], [`Ord`], and [`Hash`].
18#[repr(transparent)]
19pub struct Slice<T> {
20    pub(crate) entries: [Bucket<T>],
21}
22
23// SAFETY: `Slice<T>` is a transparent wrapper around `[Bucket<T>]`,
24// and reference lifetimes are bound together in function signatures.
25#[allow(unsafe_code)]
26impl<T> Slice<T> {
27    pub(super) const fn from_slice(entries: &[Bucket<T>]) -> &Self {
28        unsafe { &*(entries as *const [Bucket<T>] as *const Self) }
29    }
30
31    pub(super) fn from_boxed(entries: Box<[Bucket<T>]>) -> Box<Self> {
32        unsafe { Box::from_raw(Box::into_raw(entries) as *mut Self) }
33    }
34
35    fn into_boxed(self: Box<Self>) -> Box<[Bucket<T>]> {
36        unsafe { Box::from_raw(Box::into_raw(self) as *mut [Bucket<T>]) }
37    }
38}
39
40impl<T> Slice<T> {
41    pub(crate) fn into_entries(self: Box<Self>) -> Vec<Bucket<T>> {
42        self.into_boxed().into_vec()
43    }
44
45    /// Returns an empty slice.
46    pub const fn new<'a>() -> &'a Self {
47        Self::from_slice(&[])
48    }
49
50    /// Return the number of elements in the set slice.
51    pub const fn len(&self) -> usize {
52        self.entries.len()
53    }
54
55    /// Returns true if the set slice contains no elements.
56    pub const fn is_empty(&self) -> bool {
57        self.entries.is_empty()
58    }
59
60    /// Get a value by index.
61    ///
62    /// Valid indices are `0 <= index < self.len()`.
63    pub fn get_index(&self, index: usize) -> Option<&T> {
64        self.entries.get(index).map(Bucket::key_ref)
65    }
66
67    /// Returns a slice of values in the given range of indices.
68    ///
69    /// Valid indices are `0 <= index < self.len()`.
70    pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Self> {
71        let range = try_simplify_range(range, self.entries.len())?;
72        self.entries.get(range).map(Self::from_slice)
73    }
74
75    /// Get the first value.
76    pub fn first(&self) -> Option<&T> {
77        self.entries.first().map(Bucket::key_ref)
78    }
79
80    /// Get the last value.
81    pub fn last(&self) -> Option<&T> {
82        self.entries.last().map(Bucket::key_ref)
83    }
84
85    /// Divides one slice into two at an index.
86    ///
87    /// ***Panics*** if `index > len`.
88    #[track_caller]
89    pub fn split_at(&self, index: usize) -> (&Self, &Self) {
90        let (first, second) = self.entries.split_at(index);
91        (Self::from_slice(first), Self::from_slice(second))
92    }
93
94    /// Returns the first value and the rest of the slice,
95    /// or `None` if it is empty.
96    pub fn split_first(&self) -> Option<(&T, &Self)> {
97        if let [first, rest @ ..] = &self.entries {
98            Some((&first.key, Self::from_slice(rest)))
99        } else {
100            None
101        }
102    }
103
104    /// Returns the last value and the rest of the slice,
105    /// or `None` if it is empty.
106    pub fn split_last(&self) -> Option<(&T, &Self)> {
107        if let [rest @ .., last] = &self.entries {
108            Some((&last.key, Self::from_slice(rest)))
109        } else {
110            None
111        }
112    }
113
114    /// Return an iterator over the values of the set slice.
115    pub fn iter(&self) -> Iter<'_, T> {
116        Iter::new(&self.entries)
117    }
118
119    /// Search over a sorted set for a value.
120    ///
121    /// Returns the position where that value is present, or the position where it can be inserted
122    /// to maintain the sort. See [`slice::binary_search`] for more details.
123    ///
124    /// Computes in **O(log(n))** time, which is notably less scalable than looking the value up in
125    /// the set this is a slice from using [`IndexSet::get_index_of`], but this can also position
126    /// missing values.
127    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
128    where
129        T: Ord,
130    {
131        self.binary_search_by(|p| p.cmp(x))
132    }
133
134    /// Search over a sorted set with a comparator function.
135    ///
136    /// Returns the position where that value is present, or the position where it can be inserted
137    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
138    ///
139    /// Computes in **O(log(n))** time.
140    #[inline]
141    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
142    where
143        F: FnMut(&'a T) -> Ordering,
144    {
145        self.entries.binary_search_by(move |a| f(&a.key))
146    }
147
148    /// Search over a sorted set with an extraction function.
149    ///
150    /// Returns the position where that value is present, or the position where it can be inserted
151    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
152    ///
153    /// Computes in **O(log(n))** time.
154    #[inline]
155    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
156    where
157        F: FnMut(&'a T) -> B,
158        B: Ord,
159    {
160        self.binary_search_by(|k| f(k).cmp(b))
161    }
162
163    /// Checks if the values of this slice are sorted.
164    #[inline]
165    pub fn is_sorted(&self) -> bool
166    where
167        T: PartialOrd,
168    {
169        self.entries.is_sorted_by(|a, b| a.key <= b.key)
170    }
171
172    /// Checks if this slice is sorted using the given comparator function.
173    #[inline]
174    pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool
175    where
176        F: FnMut(&'a T, &'a T) -> bool,
177    {
178        self.entries.is_sorted_by(move |a, b| cmp(&a.key, &b.key))
179    }
180
181    /// Checks if this slice is sorted using the given sort-key function.
182    #[inline]
183    pub fn is_sorted_by_key<'a, F, K>(&'a self, mut sort_key: F) -> bool
184    where
185        F: FnMut(&'a T) -> K,
186        K: PartialOrd,
187    {
188        self.entries.is_sorted_by_key(move |a| sort_key(&a.key))
189    }
190
191    /// Returns the index of the partition point of a sorted set according to the given predicate
192    /// (the index of the first element of the second partition).
193    ///
194    /// See [`slice::partition_point`] for more details.
195    ///
196    /// Computes in **O(log(n))** time.
197    #[must_use]
198    pub fn partition_point<P>(&self, mut pred: P) -> usize
199    where
200        P: FnMut(&T) -> bool,
201    {
202        self.entries.partition_point(move |a| pred(&a.key))
203    }
204}
205
206impl<'a, T> IntoIterator for &'a Slice<T> {
207    type IntoIter = Iter<'a, T>;
208    type Item = &'a T;
209
210    fn into_iter(self) -> Self::IntoIter {
211        self.iter()
212    }
213}
214
215impl<T> IntoIterator for Box<Slice<T>> {
216    type IntoIter = IntoIter<T>;
217    type Item = T;
218
219    fn into_iter(self) -> Self::IntoIter {
220        IntoIter::new(self.into_entries())
221    }
222}
223
224impl<T> Default for &'_ Slice<T> {
225    fn default() -> Self {
226        Slice::from_slice(&[])
227    }
228}
229
230impl<T> Default for Box<Slice<T>> {
231    fn default() -> Self {
232        Slice::from_boxed(Box::default())
233    }
234}
235
236impl<T: Clone> Clone for Box<Slice<T>> {
237    fn clone(&self) -> Self {
238        Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
239    }
240}
241
242impl<T: Copy> From<&Slice<T>> for Box<Slice<T>> {
243    fn from(slice: &Slice<T>) -> Self {
244        Slice::from_boxed(Box::from(&slice.entries))
245    }
246}
247
248impl<T: fmt::Debug> fmt::Debug for Slice<T> {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_list().entries(self).finish()
251    }
252}
253
254impl<T, U> PartialEq<Slice<U>> for Slice<T>
255where
256    T: PartialEq<U>,
257{
258    fn eq(&self, other: &Slice<U>) -> bool {
259        slice_eq(&self.entries, &other.entries, |b1, b2| b1.key == b2.key)
260    }
261}
262
263impl<T, U> PartialEq<[U]> for Slice<T>
264where
265    T: PartialEq<U>,
266{
267    fn eq(&self, other: &[U]) -> bool {
268        slice_eq(&self.entries, other, |b, o| b.key == *o)
269    }
270}
271
272impl<T, U> PartialEq<Slice<U>> for [T]
273where
274    T: PartialEq<U>,
275{
276    fn eq(&self, other: &Slice<U>) -> bool {
277        slice_eq(self, &other.entries, |o, b| *o == b.key)
278    }
279}
280
281impl<T, U, const N: usize> PartialEq<[U; N]> for Slice<T>
282where
283    T: PartialEq<U>,
284{
285    fn eq(&self, other: &[U; N]) -> bool {
286        <Self as PartialEq<[U]>>::eq(self, other)
287    }
288}
289
290impl<T, const N: usize, U> PartialEq<Slice<U>> for [T; N]
291where
292    T: PartialEq<U>,
293{
294    fn eq(&self, other: &Slice<U>) -> bool {
295        <[T] as PartialEq<Slice<U>>>::eq(self, other)
296    }
297}
298
299impl<T: Eq> Eq for Slice<T> {}
300
301impl<T: PartialOrd> PartialOrd for Slice<T> {
302    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
303        self.iter().partial_cmp(other)
304    }
305}
306
307impl<T: Ord> Ord for Slice<T> {
308    fn cmp(&self, other: &Self) -> Ordering {
309        self.iter().cmp(other)
310    }
311}
312
313impl<T: Hash> Hash for Slice<T> {
314    fn hash<H: Hasher>(&self, state: &mut H) {
315        self.len().hash(state);
316        for value in self {
317            value.hash(state);
318        }
319    }
320}
321
322impl<T> Index<usize> for Slice<T> {
323    type Output = T;
324
325    fn index(&self, index: usize) -> &Self::Output {
326        &self.entries[index].key
327    }
328}
329
330// We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts with `Index<usize>`.
331// Instead, we repeat the implementations for all the core range types.
332macro_rules! impl_index {
333    ($($range:ty),*) => {$(
334        impl<T, S> Index<$range> for IndexSet<T, S> {
335            type Output = Slice<T>;
336
337            fn index(&self, range: $range) -> &Self::Output {
338                Slice::from_slice(&self.as_entries()[range])
339            }
340        }
341
342        impl<T> Index<$range> for Slice<T> {
343            type Output = Self;
344
345            fn index(&self, range: $range) -> &Self::Output {
346                Slice::from_slice(&self.entries[range])
347            }
348        }
349    )*}
350}
351impl_index!(
352    ops::Range<usize>,
353    ops::RangeFrom<usize>,
354    ops::RangeFull,
355    ops::RangeInclusive<usize>,
356    ops::RangeTo<usize>,
357    ops::RangeToInclusive<usize>,
358    (Bound<usize>, Bound<usize>)
359);
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    #[test]
366    fn slice_index() {
367        fn check(vec_slice: &[i32], set_slice: &Slice<i32>, sub_slice: &Slice<i32>) {
368            assert_eq!(set_slice as *const _, sub_slice as *const _);
369            itertools::assert_equal(vec_slice, set_slice);
370        }
371
372        let vec: Vec<i32> = (0..10).map(|i| i * i).collect();
373        let set: IndexSet<i32> = vec.iter().cloned().collect();
374        let slice = set.as_slice();
375
376        // RangeFull
377        check(&vec[..], &set[..], &slice[..]);
378
379        for i in 0usize..10 {
380            // Index
381            assert_eq!(vec[i], set[i]);
382            assert_eq!(vec[i], slice[i]);
383
384            // RangeFrom
385            check(&vec[i..], &set[i..], &slice[i..]);
386
387            // RangeTo
388            check(&vec[..i], &set[..i], &slice[..i]);
389
390            // RangeToInclusive
391            check(&vec[..=i], &set[..=i], &slice[..=i]);
392
393            // (Bound<usize>, Bound<usize>)
394            let bounds = (Bound::Excluded(i), Bound::Unbounded);
395            check(&vec[i + 1..], &set[bounds], &slice[bounds]);
396
397            for j in i..=10 {
398                // Range
399                check(&vec[i..j], &set[i..j], &slice[i..j]);
400            }
401
402            for j in i..10 {
403                // RangeInclusive
404                check(&vec[i..=j], &set[i..=j], &slice[i..=j]);
405            }
406        }
407    }
408}