Coverage Report

Created: 2025-08-29 06:07

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