1 | use super::{Bucket, Entries, 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 | 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 | |
40 | impl<T> Slice<T> { |
41 | pub(crate) fn into_entries(self: Box<Self>) -> Vec<Bucket<T>> { |
42 | self.into_boxed().into_vec() |
43 | } |
44 | |
45 | /// Returns an empty slice. |
46 | pub const fn new<'a>() -> &'a Self { |
47 | Self::from_slice(&[]) |
48 | } |
49 | |
50 | /// Return the number of elements in the set slice. |
51 | pub const fn len(&self) -> usize { |
52 | self.entries.len() |
53 | } |
54 | |
55 | /// Returns true if the set slice contains no elements. |
56 | pub const fn is_empty(&self) -> bool { |
57 | self.entries.is_empty() |
58 | } |
59 | |
60 | /// Get a value by index. |
61 | /// |
62 | /// Valid indices are `0 <= index < self.len()`. |
63 | pub fn get_index(&self, index: usize) -> Option<&T> { |
64 | self.entries.get(index).map(Bucket::key_ref) |
65 | } |
66 | |
67 | /// Returns a slice of values in the given range of indices. |
68 | /// |
69 | /// Valid indices are `0 <= index < self.len()`. |
70 | 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 | /// Get the first value. |
76 | pub fn first(&self) -> Option<&T> { |
77 | self.entries.first().map(Bucket::key_ref) |
78 | } |
79 | |
80 | /// Get the last value. |
81 | pub fn last(&self) -> Option<&T> { |
82 | self.entries.last().map(Bucket::key_ref) |
83 | } |
84 | |
85 | /// Divides one slice into two at an index. |
86 | /// |
87 | /// ***Panics*** if `index > len`. |
88 | 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 | /// Returns the first value and the rest of the slice, |
94 | /// or `None` if it is empty. |
95 | 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 | /// Returns the last value and the rest of the slice, |
104 | /// or `None` if it is empty. |
105 | 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 | /// Return an iterator over the values of the set slice. |
114 | pub fn iter(&self) -> Iter<'_, T> { |
115 | Iter::new(&self.entries) |
116 | } |
117 | |
118 | /// Search over a sorted set for a value. |
119 | /// |
120 | /// Returns the position where that value is present, or the position where it can be inserted |
121 | /// to maintain the sort. See [`slice::binary_search`] for more details. |
122 | /// |
123 | /// Computes in **O(log(n))** time, which is notably less scalable than looking the value up in |
124 | /// the set this is a slice from using [`IndexSet::get_index_of`], but this can also position |
125 | /// missing values. |
126 | 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 | /// Search over a sorted set with a comparator function. |
134 | /// |
135 | /// Returns the position where that value is present, or the position where it can be inserted |
136 | /// to maintain the sort. See [`slice::binary_search_by`] for more details. |
137 | /// |
138 | /// Computes in **O(log(n))** time. |
139 | #[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 | /// Search over a sorted set with an extraction function. |
148 | /// |
149 | /// Returns the position where that value is present, or the position where it can be inserted |
150 | /// to maintain the sort. See [`slice::binary_search_by_key`] for more details. |
151 | /// |
152 | /// Computes in **O(log(n))** time. |
153 | #[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 | /// Returns the index of the partition point of a sorted set according to the given predicate |
163 | /// (the index of the first element of the second partition). |
164 | /// |
165 | /// See [`slice::partition_point`] for more details. |
166 | /// |
167 | /// Computes in **O(log(n))** time. |
168 | #[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 | |
177 | impl<'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 | |
186 | impl<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 | |
195 | impl<T> Default for &'_ Slice<T> { |
196 | fn default() -> Self { |
197 | Slice::from_slice(&[]) |
198 | } |
199 | } |
200 | |
201 | impl<T> Default for Box<Slice<T>> { |
202 | fn default() -> Self { |
203 | Slice::from_boxed(entries:Box::default()) |
204 | } |
205 | } |
206 | |
207 | impl<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 | |
213 | impl<T: Copy> From<&Slice<T>> for Box<Slice<T>> { |
214 | fn from(slice: &Slice<T>) -> Self { |
215 | Slice::from_boxed(entries:Box::from(&slice.entries)) |
216 | } |
217 | } |
218 | |
219 | impl<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 | |
225 | impl<T, U> PartialEq<Slice<U>> for Slice<T> |
226 | where |
227 | T: PartialEq<U>, |
228 | { |
229 | fn eq(&self, other: &Slice<U>) -> bool { |
230 | slice_eq(&self.entries, &other.entries, |b1: &Bucket, b2: &Bucket| b1.key == b2.key) |
231 | } |
232 | } |
233 | |
234 | impl<T, U> PartialEq<[U]> for Slice<T> |
235 | where |
236 | T: PartialEq<U>, |
237 | { |
238 | fn eq(&self, other: &[U]) -> bool { |
239 | slice_eq(&self.entries, right:other, |b: &Bucket, o: &U| b.key == *o) |
240 | } |
241 | } |
242 | |
243 | impl<T, U> PartialEq<Slice<U>> for [T] |
244 | where |
245 | T: PartialEq<U>, |
246 | { |
247 | fn eq(&self, other: &Slice<U>) -> bool { |
248 | slice_eq(self, &other.entries, |o: &T, b: &Bucket| *o == b.key) |
249 | } |
250 | } |
251 | |
252 | impl<T, U, const N: usize> PartialEq<[U; N]> for Slice<T> |
253 | where |
254 | T: PartialEq<U>, |
255 | { |
256 | fn eq(&self, other: &[U; N]) -> bool { |
257 | <Self as PartialEq<[U]>>::eq(self, other) |
258 | } |
259 | } |
260 | |
261 | impl<T, const N: usize, U> PartialEq<Slice<U>> for [T; N] |
262 | where |
263 | T: PartialEq<U>, |
264 | { |
265 | fn eq(&self, other: &Slice<U>) -> bool { |
266 | <[T] as PartialEq<Slice<U>>>::eq(self, other) |
267 | } |
268 | } |
269 | |
270 | impl<T: Eq> Eq for Slice<T> {} |
271 | |
272 | impl<T: PartialOrd> PartialOrd for Slice<T> { |
273 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
274 | self.iter().partial_cmp(other) |
275 | } |
276 | } |
277 | |
278 | impl<T: Ord> Ord for Slice<T> { |
279 | fn cmp(&self, other: &Self) -> Ordering { |
280 | self.iter().cmp(other) |
281 | } |
282 | } |
283 | |
284 | impl<T: Hash> Hash for Slice<T> { |
285 | fn hash<H: Hasher>(&self, state: &mut H) { |
286 | self.len().hash(state); |
287 | for value: &T in self { |
288 | value.hash(state); |
289 | } |
290 | } |
291 | } |
292 | |
293 | impl<T> Index<usize> for Slice<T> { |
294 | type Output = T; |
295 | |
296 | fn index(&self, index: usize) -> &Self::Output { |
297 | &self.entries[index].key |
298 | } |
299 | } |
300 | |
301 | // We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts with `Index<usize>`. |
302 | // Instead, we repeat the implementations for all the core range types. |
303 | macro_rules! impl_index { |
304 | ($($range:ty),*) => {$( |
305 | impl<T, S> Index<$range> for IndexSet<T, S> { |
306 | type Output = Slice<T>; |
307 | |
308 | fn index(&self, range: $range) -> &Self::Output { |
309 | Slice::from_slice(&self.as_entries()[range]) |
310 | } |
311 | } |
312 | |
313 | impl<T> Index<$range> for Slice<T> { |
314 | type Output = Self; |
315 | |
316 | fn index(&self, range: $range) -> &Self::Output { |
317 | Slice::from_slice(&self.entries[range]) |
318 | } |
319 | } |
320 | )*} |
321 | } |
322 | impl_index!( |
323 | ops::Range<usize>, |
324 | ops::RangeFrom<usize>, |
325 | ops::RangeFull, |
326 | ops::RangeInclusive<usize>, |
327 | ops::RangeTo<usize>, |
328 | ops::RangeToInclusive<usize>, |
329 | (Bound<usize>, Bound<usize>) |
330 | ); |
331 | |
332 | #[cfg (test)] |
333 | mod tests { |
334 | use super::*; |
335 | |
336 | #[test ] |
337 | fn slice_index() { |
338 | fn check(vec_slice: &[i32], set_slice: &Slice<i32>, sub_slice: &Slice<i32>) { |
339 | assert_eq!(set_slice as *const _, sub_slice as *const _); |
340 | itertools::assert_equal(vec_slice, set_slice); |
341 | } |
342 | |
343 | let vec: Vec<i32> = (0..10).map(|i| i * i).collect(); |
344 | let set: IndexSet<i32> = vec.iter().cloned().collect(); |
345 | let slice = set.as_slice(); |
346 | |
347 | // RangeFull |
348 | check(&vec[..], &set[..], &slice[..]); |
349 | |
350 | for i in 0usize..10 { |
351 | // Index |
352 | assert_eq!(vec[i], set[i]); |
353 | assert_eq!(vec[i], slice[i]); |
354 | |
355 | // RangeFrom |
356 | check(&vec[i..], &set[i..], &slice[i..]); |
357 | |
358 | // RangeTo |
359 | check(&vec[..i], &set[..i], &slice[..i]); |
360 | |
361 | // RangeToInclusive |
362 | check(&vec[..=i], &set[..=i], &slice[..=i]); |
363 | |
364 | // (Bound<usize>, Bound<usize>) |
365 | let bounds = (Bound::Excluded(i), Bound::Unbounded); |
366 | check(&vec[i + 1..], &set[bounds], &slice[bounds]); |
367 | |
368 | for j in i..=10 { |
369 | // Range |
370 | check(&vec[i..j], &set[i..j], &slice[i..j]); |
371 | } |
372 | |
373 | for j in i..10 { |
374 | // RangeInclusive |
375 | check(&vec[i..=j], &set[i..=j], &slice[i..=j]); |
376 | } |
377 | } |
378 | } |
379 | } |
380 | |