1 | use super::{Bucket, Entries, IndexSet, IntoIter, Iter}; |
2 | use crate::util::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: PartialEq> PartialEq for Slice<T> { |
226 | fn eq(&self, other: &Self) -> bool { |
227 | self.len() == other.len() && self.iter().eq(other) |
228 | } |
229 | } |
230 | |
231 | impl<T: Eq> Eq for Slice<T> {} |
232 | |
233 | impl<T: PartialOrd> PartialOrd for Slice<T> { |
234 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
235 | self.iter().partial_cmp(other) |
236 | } |
237 | } |
238 | |
239 | impl<T: Ord> Ord for Slice<T> { |
240 | fn cmp(&self, other: &Self) -> Ordering { |
241 | self.iter().cmp(other) |
242 | } |
243 | } |
244 | |
245 | impl<T: Hash> Hash for Slice<T> { |
246 | fn hash<H: Hasher>(&self, state: &mut H) { |
247 | self.len().hash(state); |
248 | for value: &T in self { |
249 | value.hash(state); |
250 | } |
251 | } |
252 | } |
253 | |
254 | impl<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 | |
262 | // We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts with `Index<usize>`. |
263 | // Instead, we repeat the implementations for all the core range types. |
264 | macro_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 | } |
283 | impl_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)] |
294 | mod tests { |
295 | use super::*; |
296 | use alloc::vec::Vec; |
297 | |
298 | #[test ] |
299 | fn slice_index() { |
300 | fn check(vec_slice: &[i32], set_slice: &Slice<i32>, sub_slice: &Slice<i32>) { |
301 | assert_eq!(set_slice as *const _, sub_slice as *const _); |
302 | itertools::assert_equal(vec_slice, set_slice); |
303 | } |
304 | |
305 | let vec: Vec<i32> = (0..10).map(|i| i * i).collect(); |
306 | let set: IndexSet<i32> = vec.iter().cloned().collect(); |
307 | let slice = set.as_slice(); |
308 | |
309 | // RangeFull |
310 | check(&vec[..], &set[..], &slice[..]); |
311 | |
312 | for i in 0usize..10 { |
313 | // Index |
314 | assert_eq!(vec[i], set[i]); |
315 | assert_eq!(vec[i], slice[i]); |
316 | |
317 | // RangeFrom |
318 | check(&vec[i..], &set[i..], &slice[i..]); |
319 | |
320 | // RangeTo |
321 | check(&vec[..i], &set[..i], &slice[..i]); |
322 | |
323 | // RangeToInclusive |
324 | check(&vec[..=i], &set[..=i], &slice[..=i]); |
325 | |
326 | // (Bound<usize>, Bound<usize>) |
327 | let bounds = (Bound::Excluded(i), Bound::Unbounded); |
328 | check(&vec[i + 1..], &set[bounds], &slice[bounds]); |
329 | |
330 | for j in i..=10 { |
331 | // Range |
332 | check(&vec[i..j], &set[i..j], &slice[i..j]); |
333 | } |
334 | |
335 | for j in i..10 { |
336 | // RangeInclusive |
337 | check(&vec[i..=j], &set[i..=j], &slice[i..=j]); |
338 | } |
339 | } |
340 | } |
341 | } |
342 | |