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]
90 pub fn split_at(&self, index: usize) -> (&Self, &Self) {
91 let (first, second) = self.entries.split_at(index);
92 (Self::from_slice(first), Self::from_slice(second))
93 }
94
95 pub fn split_at_checked(&self, index: usize) -> Option<(&Self, &Self)> {
99 let (first, second) = self.entries.split_at_checked(index)?;
100 Some((Self::from_slice(first), Self::from_slice(second)))
101 }
102
103 pub fn split_first(&self) -> Option<(&T, &Self)> {
106 if let [first, rest @ ..] = &self.entries {
107 Some((&first.key, Self::from_slice(rest)))
108 } else {
109 None
110 }
111 }
112
113 pub fn split_last(&self) -> Option<(&T, &Self)> {
116 if let [rest @ .., last] = &self.entries {
117 Some((&last.key, Self::from_slice(rest)))
118 } else {
119 None
120 }
121 }
122
123 pub fn iter(&self) -> Iter<'_, T> {
125 Iter::new(&self.entries)
126 }
127
128 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
137 where
138 T: Ord,
139 {
140 self.binary_search_by(|p| p.cmp(x))
141 }
142
143 #[inline]
150 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
151 where
152 F: FnMut(&'a T) -> Ordering,
153 {
154 self.entries.binary_search_by(move |a| f(&a.key))
155 }
156
157 #[inline]
164 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
165 where
166 F: FnMut(&'a T) -> B,
167 B: Ord,
168 {
169 self.binary_search_by(|k| f(k).cmp(b))
170 }
171
172 #[inline]
174 pub fn is_sorted(&self) -> bool
175 where
176 T: PartialOrd,
177 {
178 self.entries.is_sorted_by(|a, b| a.key <= b.key)
179 }
180
181 #[inline]
183 pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool
184 where
185 F: FnMut(&'a T, &'a T) -> bool,
186 {
187 self.entries.is_sorted_by(move |a, b| cmp(&a.key, &b.key))
188 }
189
190 #[inline]
192 pub fn is_sorted_by_key<'a, F, K>(&'a self, mut sort_key: F) -> bool
193 where
194 F: FnMut(&'a T) -> K,
195 K: PartialOrd,
196 {
197 self.entries.is_sorted_by_key(move |a| sort_key(&a.key))
198 }
199
200 #[must_use]
207 pub fn partition_point<P>(&self, mut pred: P) -> usize
208 where
209 P: FnMut(&T) -> bool,
210 {
211 self.entries.partition_point(move |a| pred(&a.key))
212 }
213}
214
215impl<'a, T> IntoIterator for &'a Slice<T> {
216 type IntoIter = Iter<'a, T>;
217 type Item = &'a T;
218
219 fn into_iter(self) -> Self::IntoIter {
220 self.iter()
221 }
222}
223
224impl<T> IntoIterator for Box<Slice<T>> {
225 type IntoIter = IntoIter<T>;
226 type Item = T;
227
228 fn into_iter(self) -> Self::IntoIter {
229 IntoIter::new(self.into_entries())
230 }
231}
232
233impl<T> Default for &'_ Slice<T> {
234 fn default() -> Self {
235 Slice::from_slice(&[])
236 }
237}
238
239impl<T> Default for Box<Slice<T>> {
240 fn default() -> Self {
241 Slice::from_boxed(Box::default())
242 }
243}
244
245impl<T: Clone> Clone for Box<Slice<T>> {
246 fn clone(&self) -> Self {
247 Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
248 }
249}
250
251impl<T: Copy> From<&Slice<T>> for Box<Slice<T>> {
252 fn from(slice: &Slice<T>) -> Self {
253 Slice::from_boxed(Box::from(&slice.entries))
254 }
255}
256
257impl<T: fmt::Debug> fmt::Debug for Slice<T> {
258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 f.debug_list().entries(self).finish()
260 }
261}
262
263impl<T, U> PartialEq<Slice<U>> for Slice<T>
264where
265 T: PartialEq<U>,
266{
267 fn eq(&self, other: &Slice<U>) -> bool {
268 slice_eq(&self.entries, &other.entries, |b1, b2| b1.key == b2.key)
269 }
270}
271
272impl<T, U> PartialEq<[U]> for Slice<T>
273where
274 T: PartialEq<U>,
275{
276 fn eq(&self, other: &[U]) -> bool {
277 slice_eq(&self.entries, other, |b, o| b.key == *o)
278 }
279}
280
281impl<T, U> PartialEq<Slice<U>> for [T]
282where
283 T: PartialEq<U>,
284{
285 fn eq(&self, other: &Slice<U>) -> bool {
286 slice_eq(self, &other.entries, |o, b| *o == b.key)
287 }
288}
289
290impl<T, U, const N: usize> PartialEq<[U; N]> for Slice<T>
291where
292 T: PartialEq<U>,
293{
294 fn eq(&self, other: &[U; N]) -> bool {
295 <Self as PartialEq<[U]>>::eq(self, other)
296 }
297}
298
299impl<T, const N: usize, U> PartialEq<Slice<U>> for [T; N]
300where
301 T: PartialEq<U>,
302{
303 fn eq(&self, other: &Slice<U>) -> bool {
304 <[T] as PartialEq<Slice<U>>>::eq(self, other)
305 }
306}
307
308impl<T: Eq> Eq for Slice<T> {}
309
310impl<T: PartialOrd> PartialOrd for Slice<T> {
311 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
312 self.iter().partial_cmp(other)
313 }
314}
315
316impl<T: Ord> Ord for Slice<T> {
317 fn cmp(&self, other: &Self) -> Ordering {
318 self.iter().cmp(other)
319 }
320}
321
322impl<T: Hash> Hash for Slice<T> {
323 fn hash<H: Hasher>(&self, state: &mut H) {
324 self.len().hash(state);
325 for value in self {
326 value.hash(state);
327 }
328 }
329}
330
331impl<T> Index<usize> for Slice<T> {
332 type Output = T;
333
334 fn index(&self, index: usize) -> &Self::Output {
335 &self.entries[index].key
336 }
337}
338
339macro_rules! impl_index {
342 ($($range:ty),*) => {$(
343 impl<T, S> Index<$range> for IndexSet<T, S> {
344 type Output = Slice<T>;
345
346 fn index(&self, range: $range) -> &Self::Output {
347 Slice::from_slice(&self.as_entries()[range])
348 }
349 }
350
351 impl<T> Index<$range> for Slice<T> {
352 type Output = Self;
353
354 fn index(&self, range: $range) -> &Self::Output {
355 Slice::from_slice(&self.entries[range])
356 }
357 }
358 )*}
359}
360impl_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)]
371mod 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 check(&vec[..], &set[..], &slice[..]);
387
388 for i in 0usize..10 {
389 assert_eq!(vec[i], set[i]);
391 assert_eq!(vec[i], slice[i]);
392
393 check(&vec[i..], &set[i..], &slice[i..]);
395
396 check(&vec[..i], &set[..i], &slice[..i]);
398
399 check(&vec[..=i], &set[..=i], &slice[..=i]);
401
402 let bounds = (Bound::Excluded(i), Bound::Unbounded);
404 check(&vec[i + 1..], &set[bounds], &slice[bounds]);
405
406 for j in i..=10 {
407 check(&vec[i..j], &set[i..j], &slice[i..j]);
409 }
410
411 for j in i..10 {
412 check(&vec[i..=j], &set[i..=j], &slice[i..=j]);
414 }
415 }
416 }
417}