1use super::{Bucket, Entries, IndexSet, IntoIter, Iter};
2use crate::util::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 pub fn split_at(&self, index: usize) -> (&Self, &Self) {
89 let (first, second) = self.entries.split_at(index);
90 (Self::from_slice(first), Self::from_slice(second))
91 }
92
93 pub fn split_first(&self) -> Option<(&T, &Self)> {
96 if let [first, rest @ ..] = &self.entries {
97 Some((&first.key, Self::from_slice(rest)))
98 } else {
99 None
100 }
101 }
102
103 pub fn split_last(&self) -> Option<(&T, &Self)> {
106 if let [rest @ .., last] = &self.entries {
107 Some((&last.key, Self::from_slice(rest)))
108 } else {
109 None
110 }
111 }
112
113 pub fn iter(&self) -> Iter<'_, T> {
115 Iter::new(&self.entries)
116 }
117
118 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
127 where
128 T: Ord,
129 {
130 self.binary_search_by(|p| p.cmp(x))
131 }
132
133 #[inline]
140 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
141 where
142 F: FnMut(&'a T) -> Ordering,
143 {
144 self.entries.binary_search_by(move |a| f(&a.key))
145 }
146
147 #[inline]
154 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
155 where
156 F: FnMut(&'a T) -> B,
157 B: Ord,
158 {
159 self.binary_search_by(|k| f(k).cmp(b))
160 }
161
162 #[must_use]
169 pub fn partition_point<P>(&self, mut pred: P) -> usize
170 where
171 P: FnMut(&T) -> bool,
172 {
173 self.entries.partition_point(move |a| pred(&a.key))
174 }
175}
176
177impl<'a, T> IntoIterator for &'a Slice<T> {
178 type IntoIter = Iter<'a, T>;
179 type Item = &'a T;
180
181 fn into_iter(self) -> Self::IntoIter {
182 self.iter()
183 }
184}
185
186impl<T> IntoIterator for Box<Slice<T>> {
187 type IntoIter = IntoIter<T>;
188 type Item = T;
189
190 fn into_iter(self) -> Self::IntoIter {
191 IntoIter::new(self.into_entries())
192 }
193}
194
195impl<T> Default for &'_ Slice<T> {
196 fn default() -> Self {
197 Slice::from_slice(&[])
198 }
199}
200
201impl<T> Default for Box<Slice<T>> {
202 fn default() -> Self {
203 Slice::from_boxed(Box::default())
204 }
205}
206
207impl<T: Clone> Clone for Box<Slice<T>> {
208 fn clone(&self) -> Self {
209 Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
210 }
211}
212
213impl<T: Copy> From<&Slice<T>> for Box<Slice<T>> {
214 fn from(slice: &Slice<T>) -> Self {
215 Slice::from_boxed(Box::from(&slice.entries))
216 }
217}
218
219impl<T: fmt::Debug> fmt::Debug for Slice<T> {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 f.debug_list().entries(self).finish()
222 }
223}
224
225impl<T: PartialEq> PartialEq for Slice<T> {
226 fn eq(&self, other: &Self) -> bool {
227 self.len() == other.len() && self.iter().eq(other)
228 }
229}
230
231impl<T: Eq> Eq for Slice<T> {}
232
233impl<T: PartialOrd> PartialOrd for Slice<T> {
234 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
235 self.iter().partial_cmp(other)
236 }
237}
238
239impl<T: Ord> Ord for Slice<T> {
240 fn cmp(&self, other: &Self) -> Ordering {
241 self.iter().cmp(other)
242 }
243}
244
245impl<T: Hash> Hash for Slice<T> {
246 fn hash<H: Hasher>(&self, state: &mut H) {
247 self.len().hash(state);
248 for value in self {
249 value.hash(state);
250 }
251 }
252}
253
254impl<T> Index<usize> for Slice<T> {
255 type Output = T;
256
257 fn index(&self, index: usize) -> &Self::Output {
258 &self.entries[index].key
259 }
260}
261
262macro_rules! impl_index {
265 ($($range:ty),*) => {$(
266 impl<T, S> Index<$range> for IndexSet<T, S> {
267 type Output = Slice<T>;
268
269 fn index(&self, range: $range) -> &Self::Output {
270 Slice::from_slice(&self.as_entries()[range])
271 }
272 }
273
274 impl<T> Index<$range> for Slice<T> {
275 type Output = Self;
276
277 fn index(&self, range: $range) -> &Self::Output {
278 Slice::from_slice(&self.entries[range])
279 }
280 }
281 )*}
282}
283impl_index!(
284 ops::Range<usize>,
285 ops::RangeFrom<usize>,
286 ops::RangeFull,
287 ops::RangeInclusive<usize>,
288 ops::RangeTo<usize>,
289 ops::RangeToInclusive<usize>,
290 (Bound<usize>, Bound<usize>)
291);
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[test]
298 fn slice_index() {
299 fn check(vec_slice: &[i32], set_slice: &Slice<i32>, sub_slice: &Slice<i32>) {
300 assert_eq!(set_slice as *const _, sub_slice as *const _);
301 itertools::assert_equal(vec_slice, set_slice);
302 }
303
304 let vec: Vec<i32> = (0..10).map(|i| i * i).collect();
305 let set: IndexSet<i32> = vec.iter().cloned().collect();
306 let slice = set.as_slice();
307
308 check(&vec[..], &set[..], &slice[..]);
310
311 for i in 0usize..10 {
312 assert_eq!(vec[i], set[i]);
314 assert_eq!(vec[i], slice[i]);
315
316 check(&vec[i..], &set[i..], &slice[i..]);
318
319 check(&vec[..i], &set[..i], &slice[..i]);
321
322 check(&vec[..=i], &set[..=i], &slice[..=i]);
324
325 let bounds = (Bound::Excluded(i), Bound::Unbounded);
327 check(&vec[i + 1..], &set[bounds], &slice[bounds]);
328
329 for j in i..=10 {
330 check(&vec[i..j], &set[i..j], &slice[i..j]);
332 }
333
334 for j in i..10 {
335 check(&vec[i..=j], &set[i..=j], &slice[i..=j]);
337 }
338 }
339 }
340}