| 1 |
use super::{Bucket, 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 const fn first(&self) -> Option<&T> { |
| 77 |
if let [first, ..] = &self.entries { |
| 78 |
Some(&first.key) |
| 79 |
} else { |
| 80 |
None |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
/// Get the last value. |
| 85 |
pub const fn last(&self) -> Option<&T> { |
| 86 |
if let [.., last] = &self.entries { |
| 87 |
Some(&last.key) |
| 88 |
} else { |
| 89 |
None |
| 90 |
} |
| 91 |
} |
| 92 |
|
| 93 |
/// Divides one slice into two at an index. |
| 94 |
/// |
| 95 |
/// ***Panics*** if `index > len`. |
| 96 |
/// For a non-panicking alternative see [`split_at_checked`][Self::split_at_checked]. |
| 97 |
#[track_caller] |
| 98 |
pub const fn split_at(&self, index: usize) -> (&Self, &Self) { |
| 99 |
let (first, second) = self.entries.split_at(index); |
| 100 |
(Self::from_slice(first), Self::from_slice(second)) |
| 101 |
} |
| 102 |
|
| 103 |
/// Divides one slice into two at an index. |
| 104 |
/// |
| 105 |
/// Returns `None` if `index > len`. |
| 106 |
pub const fn split_at_checked(&self, index: usize) -> Option<(&Self, &Self)> { |
| 107 |
if let Some((first, second)) = self.entries.split_at_checked(index) { |
| 108 |
Some((Self::from_slice(first), Self::from_slice(second))) |
| 109 |
} else { |
| 110 |
None |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
/// Returns the first value and the rest of the slice, |
| 115 |
/// or `None` if it is empty. |
| 116 |
pub const fn split_first(&self) -> Option<(&T, &Self)> { |
| 117 |
if let [first, rest @ ..] = &self.entries { |
| 118 |
Some((&first.key, Self::from_slice(rest))) |
| 119 |
} else { |
| 120 |
None |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
/// Returns the last value and the rest of the slice, |
| 125 |
/// or `None` if it is empty. |
| 126 |
pub const fn split_last(&self) -> Option<(&T, &Self)> { |
| 127 |
if let [rest @ .., last] = &self.entries { |
| 128 |
Some((&last.key, Self::from_slice(rest))) |
| 129 |
} else { |
| 130 |
None |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
/// Return an iterator over the values of the set slice. |
| 135 |
pub fn iter(&self) -> Iter<'_, T> { |
| 136 |
Iter::new(&self.entries) |
| 137 |
} |
| 138 |
|
| 139 |
/// Search over a sorted set for a value. |
| 140 |
/// |
| 141 |
/// Returns the position where that value is present, or the position where it can be inserted |
| 142 |
/// to maintain the sort. See [`slice::binary_search`] for more details. |
| 143 |
/// |
| 144 |
/// Computes in **O(log(n))** time, which is notably less scalable than looking the value up in |
| 145 |
/// the set this is a slice from using [`IndexSet::get_index_of`], but this can also position |
| 146 |
/// missing values. |
| 147 |
pub fn binary_search(&self, x: &T) -> Result<usize, usize> |
| 148 |
where |
| 149 |
T: Ord, |
| 150 |
{ |
| 151 |
self.binary_search_by(|p| p.cmp(x)) |
| 152 |
} |
| 153 |
|
| 154 |
/// Search over a sorted set with a comparator function. |
| 155 |
/// |
| 156 |
/// Returns the position where that value is present, or the position where it can be inserted |
| 157 |
/// to maintain the sort. See [`slice::binary_search_by`] for more details. |
| 158 |
/// |
| 159 |
/// Computes in **O(log(n))** time. |
| 160 |
#[inline] |
| 161 |
pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize> |
| 162 |
where |
| 163 |
F: FnMut(&'a T) -> Ordering, |
| 164 |
{ |
| 165 |
self.entries.binary_search_by(move |a| f(&a.key)) |
| 166 |
} |
| 167 |
|
| 168 |
/// Search over a sorted set with an extraction function. |
| 169 |
/// |
| 170 |
/// Returns the position where that value is present, or the position where it can be inserted |
| 171 |
/// to maintain the sort. See [`slice::binary_search_by_key`] for more details. |
| 172 |
/// |
| 173 |
/// Computes in **O(log(n))** time. |
| 174 |
#[inline] |
| 175 |
pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize> |
| 176 |
where |
| 177 |
F: FnMut(&'a T) -> B, |
| 178 |
B: Ord, |
| 179 |
{ |
| 180 |
self.binary_search_by(|k| f(k).cmp(b)) |
| 181 |
} |
| 182 |
|
| 183 |
/// Checks if the values of this slice are sorted. |
| 184 |
#[inline] |
| 185 |
pub fn is_sorted(&self) -> bool |
| 186 |
where |
| 187 |
T: PartialOrd, |
| 188 |
{ |
| 189 |
self.entries.is_sorted_by(|a, b| a.key <= b.key) |
| 190 |
} |
| 191 |
|
| 192 |
/// Checks if this slice is sorted using the given comparator function. |
| 193 |
#[inline] |
| 194 |
pub fn is_sorted_by<'a, F>(&'a self, mut cmp: F) -> bool |
| 195 |
where |
| 196 |
F: FnMut(&'a T, &'a T) -> bool, |
| 197 |
{ |
| 198 |
self.entries.is_sorted_by(move |a, b| cmp(&a.key, &b.key)) |
| 199 |
} |
| 200 |
|
| 201 |
/// Checks if this slice is sorted using the given sort-key function. |
| 202 |
#[inline] |
| 203 |
pub fn is_sorted_by_key<'a, F, K>(&'a self, mut sort_key: F) -> bool |
| 204 |
where |
| 205 |
F: FnMut(&'a T) -> K, |
| 206 |
K: PartialOrd, |
| 207 |
{ |
| 208 |
self.entries.is_sorted_by_key(move |a| sort_key(&a.key)) |
| 209 |
} |
| 210 |
|
| 211 |
/// Returns the index of the partition point of a sorted set according to the given predicate |
| 212 |
/// (the index of the first element of the second partition). |
| 213 |
/// |
| 214 |
/// See [`slice::partition_point`] for more details. |
| 215 |
/// |
| 216 |
/// Computes in **O(log(n))** time. |
| 217 |
#[must_use] |
| 218 |
pub fn partition_point<P>(&self, mut pred: P) -> usize |
| 219 |
where |
| 220 |
P: FnMut(&T) -> bool, |
| 221 |
{ |
| 222 |
self.entries.partition_point(move |a| pred(&a.key)) |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
impl<'a, T> IntoIterator for &'a Slice<T> { |
| 227 |
type IntoIter = Iter<'a, T>; |
| 228 |
type Item = &'a T; |
| 229 |
|
| 230 |
fn into_iter(self) -> Self::IntoIter { |
| 231 |
self.iter() |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
impl<T> IntoIterator for Box<Slice<T>> { |
| 236 |
type IntoIter = IntoIter<T>; |
| 237 |
type Item = T; |
| 238 |
|
| 239 |
fn into_iter(self) -> Self::IntoIter { |
| 240 |
IntoIter::new(self.into_entries()) |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
impl<T> Default for &'_ Slice<T> { |
| 245 |
fn default() -> Self { |
| 246 |
Slice::from_slice(&[]) |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
impl<T> Default for Box<Slice<T>> { |
| 251 |
fn default() -> Self { |
| 252 |
Slice::from_boxed(Box::default()) |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
impl<T: Clone> Clone for Box<Slice<T>> { |
| 257 |
fn clone(&self) -> Self { |
| 258 |
Slice::from_boxed(self.entries.to_vec().into_boxed_slice()) |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
impl<T: Copy> From<&Slice<T>> for Box<Slice<T>> { |
| 263 |
fn from(slice: &Slice<T>) -> Self { |
| 264 |
Slice::from_boxed(Box::from(&slice.entries)) |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
impl<T: fmt::Debug> fmt::Debug for Slice<T> { |
| 269 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 270 |
f.debug_list().entries(self).finish() |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
impl<T, U> PartialEq<Slice<U>> for Slice<T> |
| 275 |
where |
| 276 |
T: PartialEq<U>, |
| 277 |
{ |
| 278 |
fn eq(&self, other: &Slice<U>) -> bool { |
| 279 |
slice_eq(&self.entries, &other.entries, |b1, b2| b1.key == b2.key) |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
impl<T, U> PartialEq<[U]> for Slice<T> |
| 284 |
where |
| 285 |
T: PartialEq<U>, |
| 286 |
{ |
| 287 |
fn eq(&self, other: &[U]) -> bool { |
| 288 |
slice_eq(&self.entries, other, |b, o| b.key == *o) |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
impl<T, U> PartialEq<Slice<U>> for [T] |
| 293 |
where |
| 294 |
T: PartialEq<U>, |
| 295 |
{ |
| 296 |
fn eq(&self, other: &Slice<U>) -> bool { |
| 297 |
slice_eq(self, &other.entries, |o, b| *o == b.key) |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
impl<T, U, const N: usize> PartialEq<[U; N]> for Slice<T> |
| 302 |
where |
| 303 |
T: PartialEq<U>, |
| 304 |
{ |
| 305 |
fn eq(&self, other: &[U; N]) -> bool { |
| 306 |
<Self as PartialEq<[U]>>::eq(self, other) |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
impl<T, const N: usize, U> PartialEq<Slice<U>> for [T; N] |
| 311 |
where |
| 312 |
T: PartialEq<U>, |
| 313 |
{ |
| 314 |
fn eq(&self, other: &Slice<U>) -> bool { |
| 315 |
<[T] as PartialEq<Slice<U>>>::eq(self, other) |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
impl<T: Eq> Eq for Slice<T> {} |
| 320 |
|
| 321 |
impl<T: PartialOrd> PartialOrd for Slice<T> { |
| 322 |
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
| 323 |
self.iter().partial_cmp(other) |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
impl<T: Ord> Ord for Slice<T> { |
| 328 |
fn cmp(&self, other: &Self) -> Ordering { |
| 329 |
self.iter().cmp(other) |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
impl<T: Hash> Hash for Slice<T> { |
| 334 |
fn hash<H: Hasher>(&self, state: &mut H) { |
| 335 |
self.len().hash(state); |
| 336 |
for value in self { |
| 337 |
value.hash(state); |
| 338 |
} |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
impl<T> Index<usize> for Slice<T> { |
| 343 |
type Output = T; |
| 344 |
|
| 345 |
fn index(&self, index: usize) -> &Self::Output { |
| 346 |
&self.entries[index].key |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
// We can't have `impl<I: RangeBounds<usize>> Index<I>` because that conflicts with `Index<usize>`. |
| 351 |
// Instead, we repeat the implementations for all the core range types. |
| 352 |
macro_rules! impl_index { |
| 353 |
($($range:ty),*) => {$( |
| 354 |
impl<T, S> Index<$range> for IndexSet<T, S> { |
| 355 |
type Output = Slice<T>; |
| 356 |
|
| 357 |
fn index(&self, range: $range) -> &Self::Output { |
| 358 |
Slice::from_slice(&self.as_entries()[range]) |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
impl<T> Index<$range> for Slice<T> { |
| 363 |
type Output = Self; |
| 364 |
|
| 365 |
fn index(&self, range: $range) -> &Self::Output { |
| 366 |
Slice::from_slice(&self.entries[range]) |
| 367 |
} |
| 368 |
} |
| 369 |
)*} |
| 370 |
} |
| 371 |
impl_index!( |
| 372 |
ops::Range<usize>, |
| 373 |
ops::RangeFrom<usize>, |
| 374 |
ops::RangeFull, |
| 375 |
ops::RangeInclusive<usize>, |
| 376 |
ops::RangeTo<usize>, |
| 377 |
ops::RangeToInclusive<usize>, |
| 378 |
(Bound<usize>, Bound<usize>) |
| 379 |
); |
| 380 |
|
| 381 |
#[cfg(test)] |
| 382 |
mod tests { |
| 383 |
use super::*; |
| 384 |
|
| 385 |
#[test] |
| 386 |
fn slice_index() { |
| 387 |
fn check(vec_slice: &[i32], set_slice: &Slice<i32>, sub_slice: &Slice<i32>) { |
| 388 |
assert_eq!(set_slice as *const _, sub_slice as *const _); |
| 389 |
itertools::assert_equal(vec_slice, set_slice); |
| 390 |
} |
| 391 |
|
| 392 |
let vec: Vec<i32> = (0..10).map(|i| i * i).collect(); |
| 393 |
let set: IndexSet<i32> = vec.iter().cloned().collect(); |
| 394 |
let slice = set.as_slice(); |
| 395 |
|
| 396 |
// RangeFull |
| 397 |
#[expect(clippy::redundant_slicing)] |
| 398 |
check(&vec[..], &set[..], &slice[..]); |
| 399 |
|
| 400 |
for i in 0usize..10 { |
| 401 |
// Index |
| 402 |
assert_eq!(vec[i], set[i]); |
| 403 |
assert_eq!(vec[i], slice[i]); |
| 404 |
|
| 405 |
// RangeFrom |
| 406 |
check(&vec[i..], &set[i..], &slice[i..]); |
| 407 |
|
| 408 |
// RangeTo |
| 409 |
check(&vec[..i], &set[..i], &slice[..i]); |
| 410 |
|
| 411 |
// RangeToInclusive |
| 412 |
check(&vec[..=i], &set[..=i], &slice[..=i]); |
| 413 |
|
| 414 |
// (Bound<usize>, Bound<usize>) |
| 415 |
let bounds = (Bound::Excluded(i), Bound::Unbounded); |
| 416 |
check(&vec[i + 1..], &set[bounds], &slice[bounds]); |
| 417 |
|
| 418 |
for j in i..=10 { |
| 419 |
// Range |
| 420 |
check(&vec[i..j], &set[i..j], &slice[i..j]); |
| 421 |
} |
| 422 |
|
| 423 |
for j in i..10 { |
| 424 |
// RangeInclusive |
| 425 |
check(&vec[i..=j], &set[i..=j], &slice[i..=j]); |
| 426 |
} |
| 427 |
} |
| 428 |
} |
| 429 |
} |