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#[repr(transparent)]
19pub struct Slice<T> {
20 pub(crate) entries: [Bucket<T>],
21}
22
23#[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 pub const fn new<'a>() -> &'a Self {
47 Self::from_slice(&[])
48 }
49
50 pub const fn len(&self) -> usize {
52 self.entries.len()
53 }
54
55 pub const fn is_empty(&self) -> bool {
57 self.entries.is_empty()
58 }
59
60 pub fn get_index(&self, index: usize) -> Option<&T> {
64 self.entries.get(index).map(Bucket::key_ref)
65 }
66
67 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 pub fn first(&self) -> Option<&T> {
77 self.entries.first().map(Bucket::key_ref)
78 }
79
80 pub fn last(&self) -> Option<&T> {
82 self.entries.last().map(Bucket::key_ref)
83 }
84
85 #[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 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 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 pub fn iter(&self) -> Iter<'_, T> {
116 Iter::new(&self.entries)
117 }
118
119 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 #[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 #[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 #[must_use]
170 pub fn partition_point<P>(&self, mut pred: P) -> usize
171 where
172 P: FnMut(&T) -> bool,
173 {
174 self.entries.partition_point(move |a| pred(&a.key))
175 }
176}
177
178impl<'a, T> IntoIterator for &'a Slice<T> {
179 type IntoIter = Iter<'a, T>;
180 type Item = &'a T;
181
182 fn into_iter(self) -> Self::IntoIter {
183 self.iter()
184 }
185}
186
187impl<T> IntoIterator for Box<Slice<T>> {
188 type IntoIter = IntoIter<T>;
189 type Item = T;
190
191 fn into_iter(self) -> Self::IntoIter {
192 IntoIter::new(self.into_entries())
193 }
194}
195
196impl<T> Default for &'_ Slice<T> {
197 fn default() -> Self {
198 Slice::from_slice(&[])
199 }
200}
201
202impl<T> Default for Box<Slice<T>> {
203 fn default() -> Self {
204 Slice::from_boxed(Box::default())
205 }
206}
207
208impl<T: Clone> Clone for Box<Slice<T>> {
209 fn clone(&self) -> Self {
210 Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
211 }
212}
213
214impl<T: Copy> From<&Slice<T>> for Box<Slice<T>> {
215 fn from(slice: &Slice<T>) -> Self {
216 Slice::from_boxed(Box::from(&slice.entries))
217 }
218}
219
220impl<T: fmt::Debug> fmt::Debug for Slice<T> {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 f.debug_list().entries(self).finish()
223 }
224}
225
226impl<T, U> PartialEq<Slice<U>> for Slice<T>
227where
228 T: PartialEq<U>,
229{
230 fn eq(&self, other: &Slice<U>) -> bool {
231 slice_eq(&self.entries, &other.entries, |b1, b2| b1.key == b2.key)
232 }
233}
234
235impl<T, U> PartialEq<[U]> for Slice<T>
236where
237 T: PartialEq<U>,
238{
239 fn eq(&self, other: &[U]) -> bool {
240 slice_eq(&self.entries, other, |b, o| b.key == *o)
241 }
242}
243
244impl<T, U> PartialEq<Slice<U>> for [T]
245where
246 T: PartialEq<U>,
247{
248 fn eq(&self, other: &Slice<U>) -> bool {
249 slice_eq(self, &other.entries, |o, b| *o == b.key)
250 }
251}
252
253impl<T, U, const N: usize> PartialEq<[U; N]> for Slice<T>
254where
255 T: PartialEq<U>,
256{
257 fn eq(&self, other: &[U; N]) -> bool {
258 <Self as PartialEq<[U]>>::eq(self, other)
259 }
260}
261
262impl<T, const N: usize, U> PartialEq<Slice<U>> for [T; N]
263where
264 T: PartialEq<U>,
265{
266 fn eq(&self, other: &Slice<U>) -> bool {
267 <[T] as PartialEq<Slice<U>>>::eq(self, other)
268 }
269}
270
271impl<T: Eq> Eq for Slice<T> {}
272
273impl<T: PartialOrd> PartialOrd for Slice<T> {
274 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
275 self.iter().partial_cmp(other)
276 }
277}
278
279impl<T: Ord> Ord for Slice<T> {
280 fn cmp(&self, other: &Self) -> Ordering {
281 self.iter().cmp(other)
282 }
283}
284
285impl<T: Hash> Hash for Slice<T> {
286 fn hash<H: Hasher>(&self, state: &mut H) {
287 self.len().hash(state);
288 for value in self {
289 value.hash(state);
290 }
291 }
292}
293
294impl<T> Index<usize> for Slice<T> {
295 type Output = T;
296
297 fn index(&self, index: usize) -> &Self::Output {
298 &self.entries[index].key
299 }
300}
301
302macro_rules! impl_index {
305 ($($range:ty),*) => {$(
306 impl<T, S> Index<$range> for IndexSet<T, S> {
307 type Output = Slice<T>;
308
309 fn index(&self, range: $range) -> &Self::Output {
310 Slice::from_slice(&self.as_entries()[range])
311 }
312 }
313
314 impl<T> Index<$range> for Slice<T> {
315 type Output = Self;
316
317 fn index(&self, range: $range) -> &Self::Output {
318 Slice::from_slice(&self.entries[range])
319 }
320 }
321 )*}
322}
323impl_index!(
324 ops::Range<usize>,
325 ops::RangeFrom<usize>,
326 ops::RangeFull,
327 ops::RangeInclusive<usize>,
328 ops::RangeTo<usize>,
329 ops::RangeToInclusive<usize>,
330 (Bound<usize>, Bound<usize>)
331);
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336
337 #[test]
338 fn slice_index() {
339 fn check(vec_slice: &[i32], set_slice: &Slice<i32>, sub_slice: &Slice<i32>) {
340 assert_eq!(set_slice as *const _, sub_slice as *const _);
341 itertools::assert_equal(vec_slice, set_slice);
342 }
343
344 let vec: Vec<i32> = (0..10).map(|i| i * i).collect();
345 let set: IndexSet<i32> = vec.iter().cloned().collect();
346 let slice = set.as_slice();
347
348 check(&vec[..], &set[..], &slice[..]);
350
351 for i in 0usize..10 {
352 assert_eq!(vec[i], set[i]);
354 assert_eq!(vec[i], slice[i]);
355
356 check(&vec[i..], &set[i..], &slice[i..]);
358
359 check(&vec[..i], &set[..i], &slice[..i]);
361
362 check(&vec[..=i], &set[..=i], &slice[..=i]);
364
365 let bounds = (Bound::Excluded(i), Bound::Unbounded);
367 check(&vec[i + 1..], &set[bounds], &slice[bounds]);
368
369 for j in i..=10 {
370 check(&vec[i..j], &set[i..j], &slice[i..j]);
372 }
373
374 for j in i..10 {
375 check(&vec[i..=j], &set[i..=j], &slice[i..=j]);
377 }
378 }
379 }
380}