Coverage Report

Created: 2026-01-10 06:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/indexmap-2.13.0/src/set/slice.rs
Line
Count
Source
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
    /// For a non-panicking alternative see [`split_at_checked`][Self::split_at_checked].
89
    #[track_caller]
90
0
    pub fn split_at(&self, index: usize) -> (&Self, &Self) {
91
0
        let (first, second) = self.entries.split_at(index);
92
0
        (Self::from_slice(first), Self::from_slice(second))
93
0
    }
94
95
    /// Divides one slice into two at an index.
96
    ///
97
    /// Returns `None` if `index > len`.
98
0
    pub fn split_at_checked(&self, index: usize) -> Option<(&Self, &Self)> {
99
0
        let (first, second) = self.entries.split_at_checked(index)?;
100
0
        Some((Self::from_slice(first), Self::from_slice(second)))
101
0
    }
102
103
    /// Returns the first value and the rest of the slice,
104
    /// or `None` if it is empty.
105
0
    pub fn split_first(&self) -> Option<(&T, &Self)> {
106
0
        if let [first, rest @ ..] = &self.entries {
107
0
            Some((&first.key, Self::from_slice(rest)))
108
        } else {
109
0
            None
110
        }
111
0
    }
112
113
    /// Returns the last value and the rest of the slice,
114
    /// or `None` if it is empty.
115
0
    pub fn split_last(&self) -> Option<(&T, &Self)> {
116
0
        if let [rest @ .., last] = &self.entries {
117
0
            Some((&last.key, Self::from_slice(rest)))
118
        } else {
119
0
            None
120
        }
121
0
    }
122
123
    /// Return an iterator over the values of the set slice.
124
0
    pub fn iter(&self) -> Iter<'_, T> {
125
0
        Iter::new(&self.entries)
126
0
    }
127
128
    /// Search over a sorted set for a value.
129
    ///
130
    /// Returns the position where that value is present, or the position where it can be inserted
131
    /// to maintain the sort. See [`slice::binary_search`] for more details.
132
    ///
133
    /// Computes in **O(log(n))** time, which is notably less scalable than looking the value up in
134
    /// the set this is a slice from using [`IndexSet::get_index_of`], but this can also position
135
    /// missing values.
136
0
    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
137
0
    where
138
0
        T: Ord,
139
    {
140
0
        self.binary_search_by(|p| p.cmp(x))
141
0
    }
142
143
    /// Search over a sorted set with a comparator function.
144
    ///
145
    /// Returns the position where that value is present, or the position where it can be inserted
146
    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
147
    ///
148
    /// Computes in **O(log(n))** time.
149
    #[inline]
150
0
    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
151
0
    where
152
0
        F: FnMut(&'a T) -> Ordering,
153
    {
154
0
        self.entries.binary_search_by(move |a| f(&a.key))
155
0
    }
156
157
    /// Search over a sorted set with an extraction function.
158
    ///
159
    /// Returns the position where that value is present, or the position where it can be inserted
160
    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
161
    ///
162
    /// Computes in **O(log(n))** time.
163
    #[inline]
164
0
    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
165
0
    where
166
0
        F: FnMut(&'a T) -> B,
167
0
        B: Ord,
168
    {
169
0
        self.binary_search_by(|k| f(k).cmp(b))
170
0
    }
171
172
    /// Checks if the values of this slice are sorted.
173
    #[inline]
174
0
    pub fn is_sorted(&self) -> bool
175
0
    where
176
0
        T: PartialOrd,
177
    {
178
0
        self.entries.is_sorted_by(|a, b| a.key <= b.key)
179
0
    }
180
181
    /// Checks if this slice is sorted using the given comparator function.
182
    #[inline]
183
0
    pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool
184
0
    where
185
0
        F: FnMut(&'a T, &'a T) -> bool,
186
    {
187
0
        self.entries.is_sorted_by(move |a, b| cmp(&a.key, &b.key))
188
0
    }
189
190
    /// Checks if this slice is sorted using the given sort-key function.
191
    #[inline]
192
0
    pub fn is_sorted_by_key<'a, F, K>(&'a self, mut sort_key: F) -> bool
193
0
    where
194
0
        F: FnMut(&'a T) -> K,
195
0
        K: PartialOrd,
196
    {
197
0
        self.entries.is_sorted_by_key(move |a| sort_key(&a.key))
198
0
    }
199
200
    /// Returns the index of the partition point of a sorted set according to the given predicate
201
    /// (the index of the first element of the second partition).
202
    ///
203
    /// See [`slice::partition_point`] for more details.
204
    ///
205
    /// Computes in **O(log(n))** time.
206
    #[must_use]
207
0
    pub fn partition_point<P>(&self, mut pred: P) -> usize
208
0
    where
209
0
        P: FnMut(&T) -> bool,
210
    {
211
0
        self.entries.partition_point(move |a| pred(&a.key))
212
0
    }
213
}
214
215
impl<'a, T> IntoIterator for &'a Slice<T> {
216
    type IntoIter = Iter<'a, T>;
217
    type Item = &'a T;
218
219
0
    fn into_iter(self) -> Self::IntoIter {
220
0
        self.iter()
221
0
    }
222
}
223
224
impl<T> IntoIterator for Box<Slice<T>> {
225
    type IntoIter = IntoIter<T>;
226
    type Item = T;
227
228
0
    fn into_iter(self) -> Self::IntoIter {
229
0
        IntoIter::new(self.into_entries())
230
0
    }
231
}
232
233
impl<T> Default for &'_ Slice<T> {
234
0
    fn default() -> Self {
235
0
        Slice::from_slice(&[])
236
0
    }
237
}
238
239
impl<T> Default for Box<Slice<T>> {
240
0
    fn default() -> Self {
241
0
        Slice::from_boxed(Box::default())
242
0
    }
243
}
244
245
impl<T: Clone> Clone for Box<Slice<T>> {
246
0
    fn clone(&self) -> Self {
247
0
        Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
248
0
    }
249
}
250
251
impl<T: Copy> From<&Slice<T>> for Box<Slice<T>> {
252
0
    fn from(slice: &Slice<T>) -> Self {
253
0
        Slice::from_boxed(Box::from(&slice.entries))
254
0
    }
255
}
256
257
impl<T: fmt::Debug> fmt::Debug for Slice<T> {
258
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259
0
        f.debug_list().entries(self).finish()
260
0
    }
261
}
262
263
impl<T, U> PartialEq<Slice<U>> for Slice<T>
264
where
265
    T: PartialEq<U>,
266
{
267
0
    fn eq(&self, other: &Slice<U>) -> bool {
268
0
        slice_eq(&self.entries, &other.entries, |b1, b2| b1.key == b2.key)
269
0
    }
270
}
271
272
impl<T, U> PartialEq<[U]> for Slice<T>
273
where
274
    T: PartialEq<U>,
275
{
276
0
    fn eq(&self, other: &[U]) -> bool {
277
0
        slice_eq(&self.entries, other, |b, o| b.key == *o)
278
0
    }
279
}
280
281
impl<T, U> PartialEq<Slice<U>> for [T]
282
where
283
    T: PartialEq<U>,
284
{
285
0
    fn eq(&self, other: &Slice<U>) -> bool {
286
0
        slice_eq(self, &other.entries, |o, b| *o == b.key)
287
0
    }
288
}
289
290
impl<T, U, const N: usize> PartialEq<[U; N]> for Slice<T>
291
where
292
    T: PartialEq<U>,
293
{
294
0
    fn eq(&self, other: &[U; N]) -> bool {
295
0
        <Self as PartialEq<[U]>>::eq(self, other)
296
0
    }
297
}
298
299
impl<T, const N: usize, U> PartialEq<Slice<U>> for [T; N]
300
where
301
    T: PartialEq<U>,
302
{
303
0
    fn eq(&self, other: &Slice<U>) -> bool {
304
0
        <[T] as PartialEq<Slice<U>>>::eq(self, other)
305
0
    }
306
}
307
308
impl<T: Eq> Eq for Slice<T> {}
309
310
impl<T: PartialOrd> PartialOrd for Slice<T> {
311
0
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
312
0
        self.iter().partial_cmp(other)
313
0
    }
314
}
315
316
impl<T: Ord> Ord for Slice<T> {
317
0
    fn cmp(&self, other: &Self) -> Ordering {
318
0
        self.iter().cmp(other)
319
0
    }
320
}
321
322
impl<T: Hash> Hash for Slice<T> {
323
0
    fn hash<H: Hasher>(&self, state: &mut H) {
324
0
        self.len().hash(state);
325
0
        for value in self {
326
0
            value.hash(state);
327
0
        }
328
0
    }
329
}
330
331
impl<T> Index<usize> for Slice<T> {
332
    type Output = T;
333
334
0
    fn index(&self, index: usize) -> &Self::Output {
335
0
        &self.entries[index].key
336
0
    }
337
}
338
339
// We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts with `Index<usize>`.
340
// Instead, we repeat the implementations for all the core range types.
341
macro_rules! impl_index {
342
    ($($range:ty),*) => {$(
343
        impl<T, S> Index<$range> for IndexSet<T, S> {
344
            type Output = Slice<T>;
345
346
0
            fn index(&self, range: $range) -> &Self::Output {
347
0
                Slice::from_slice(&self.as_entries()[range])
348
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
349
        }
350
351
        impl<T> Index<$range> for Slice<T> {
352
            type Output = Self;
353
354
0
            fn index(&self, range: $range) -> &Self::Output {
355
0
                Slice::from_slice(&self.entries[range])
356
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
357
        }
358
    )*}
359
}
360
impl_index!(
361
    ops::Range<usize>,
362
    ops::RangeFrom<usize>,
363
    ops::RangeFull,
364
    ops::RangeInclusive<usize>,
365
    ops::RangeTo<usize>,
366
    ops::RangeToInclusive<usize>,
367
    (Bound<usize>, Bound<usize>)
368
);
369
370
#[cfg(test)]
371
mod tests {
372
    use super::*;
373
374
    #[test]
375
    fn slice_index() {
376
        fn check(vec_slice: &[i32], set_slice: &Slice<i32>, sub_slice: &Slice<i32>) {
377
            assert_eq!(set_slice as *const _, sub_slice as *const _);
378
            itertools::assert_equal(vec_slice, set_slice);
379
        }
380
381
        let vec: Vec<i32> = (0..10).map(|i| i * i).collect();
382
        let set: IndexSet<i32> = vec.iter().cloned().collect();
383
        let slice = set.as_slice();
384
385
        // RangeFull
386
        check(&vec[..], &set[..], &slice[..]);
387
388
        for i in 0usize..10 {
389
            // Index
390
            assert_eq!(vec[i], set[i]);
391
            assert_eq!(vec[i], slice[i]);
392
393
            // RangeFrom
394
            check(&vec[i..], &set[i..], &slice[i..]);
395
396
            // RangeTo
397
            check(&vec[..i], &set[..i], &slice[..i]);
398
399
            // RangeToInclusive
400
            check(&vec[..=i], &set[..=i], &slice[..=i]);
401
402
            // (Bound<usize>, Bound<usize>)
403
            let bounds = (Bound::Excluded(i), Bound::Unbounded);
404
            check(&vec[i + 1..], &set[bounds], &slice[bounds]);
405
406
            for j in i..=10 {
407
                // Range
408
                check(&vec[i..j], &set[i..j], &slice[i..j]);
409
            }
410
411
            for j in i..10 {
412
                // RangeInclusive
413
                check(&vec[i..=j], &set[i..=j], &slice[i..=j]);
414
            }
415
        }
416
    }
417
}