1use super::{
2 Bucket, Entries, IndexMap, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values,
3 ValuesMut,
4};
5use crate::util::try_simplify_range;
6
7use alloc::boxed::Box;
8use alloc::vec::Vec;
9use core::cmp::Ordering;
10use core::fmt;
11use core::hash::{Hash, Hasher};
12use core::ops::{self, Bound, Index, IndexMut, RangeBounds};
13
14#[repr(transparent)]
22pub struct Slice<K, V> {
23 pub(crate) entries: [Bucket<K, V>],
24}
25
26#[allow(unsafe_code)]
29impl<K, V> Slice<K, V> {
30 pub(super) const fn from_slice(entries: &[Bucket<K, V>]) -> &Self {
31 unsafe { &*(entries as *const [Bucket<K, V>] as *const Self) }
32 }
33
34 pub(super) fn from_mut_slice(entries: &mut [Bucket<K, V>]) -> &mut Self {
35 unsafe { &mut *(entries as *mut [Bucket<K, V>] as *mut Self) }
36 }
37
38 pub(super) fn from_boxed(entries: Box<[Bucket<K, V>]>) -> Box<Self> {
39 unsafe { Box::from_raw(Box::into_raw(entries) as *mut Self) }
40 }
41
42 fn into_boxed(self: Box<Self>) -> Box<[Bucket<K, V>]> {
43 unsafe { Box::from_raw(Box::into_raw(self) as *mut [Bucket<K, V>]) }
44 }
45}
46
47impl<K, V> Slice<K, V> {
48 pub(crate) fn into_entries(self: Box<Self>) -> Vec<Bucket<K, V>> {
49 self.into_boxed().into_vec()
50 }
51
52 pub const fn new<'a>() -> &'a Self {
54 Self::from_slice(&[])
55 }
56
57 pub fn new_mut<'a>() -> &'a mut Self {
59 Self::from_mut_slice(&mut [])
60 }
61
62 #[inline]
64 pub const fn len(&self) -> usize {
65 self.entries.len()
66 }
67
68 #[inline]
70 pub const fn is_empty(&self) -> bool {
71 self.entries.is_empty()
72 }
73
74 pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
78 self.entries.get(index).map(Bucket::refs)
79 }
80
81 pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
85 self.entries.get_mut(index).map(Bucket::ref_mut)
86 }
87
88 pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Self> {
92 let range = try_simplify_range(range, self.entries.len())?;
93 self.entries.get(range).map(Slice::from_slice)
94 }
95
96 pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Self> {
100 let range = try_simplify_range(range, self.entries.len())?;
101 self.entries.get_mut(range).map(Slice::from_mut_slice)
102 }
103
104 pub fn first(&self) -> Option<(&K, &V)> {
106 self.entries.first().map(Bucket::refs)
107 }
108
109 pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
111 self.entries.first_mut().map(Bucket::ref_mut)
112 }
113
114 pub fn last(&self) -> Option<(&K, &V)> {
116 self.entries.last().map(Bucket::refs)
117 }
118
119 pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
121 self.entries.last_mut().map(Bucket::ref_mut)
122 }
123
124 pub fn split_at(&self, index: usize) -> (&Self, &Self) {
128 let (first, second) = self.entries.split_at(index);
129 (Self::from_slice(first), Self::from_slice(second))
130 }
131
132 pub fn split_at_mut(&mut self, index: usize) -> (&mut Self, &mut Self) {
136 let (first, second) = self.entries.split_at_mut(index);
137 (Self::from_mut_slice(first), Self::from_mut_slice(second))
138 }
139
140 pub fn split_first(&self) -> Option<((&K, &V), &Self)> {
143 if let [first, rest @ ..] = &self.entries {
144 Some((first.refs(), Self::from_slice(rest)))
145 } else {
146 None
147 }
148 }
149
150 pub fn split_first_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
153 if let [first, rest @ ..] = &mut self.entries {
154 Some((first.ref_mut(), Self::from_mut_slice(rest)))
155 } else {
156 None
157 }
158 }
159
160 pub fn split_last(&self) -> Option<((&K, &V), &Self)> {
163 if let [rest @ .., last] = &self.entries {
164 Some((last.refs(), Self::from_slice(rest)))
165 } else {
166 None
167 }
168 }
169
170 pub fn split_last_mut(&mut self) -> Option<((&K, &mut V), &mut Self)> {
173 if let [rest @ .., last] = &mut self.entries {
174 Some((last.ref_mut(), Self::from_mut_slice(rest)))
175 } else {
176 None
177 }
178 }
179
180 pub fn iter(&self) -> Iter<'_, K, V> {
182 Iter::new(&self.entries)
183 }
184
185 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
187 IterMut::new(&mut self.entries)
188 }
189
190 pub fn keys(&self) -> Keys<'_, K, V> {
192 Keys::new(&self.entries)
193 }
194
195 pub fn into_keys(self: Box<Self>) -> IntoKeys<K, V> {
197 IntoKeys::new(self.into_entries())
198 }
199
200 pub fn values(&self) -> Values<'_, K, V> {
202 Values::new(&self.entries)
203 }
204
205 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
207 ValuesMut::new(&mut self.entries)
208 }
209
210 pub fn into_values(self: Box<Self>) -> IntoValues<K, V> {
212 IntoValues::new(self.into_entries())
213 }
214
215 pub fn binary_search_keys(&self, x: &K) -> Result<usize, usize>
224 where
225 K: Ord,
226 {
227 self.binary_search_by(|p, _| p.cmp(x))
228 }
229
230 #[inline]
237 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
238 where
239 F: FnMut(&'a K, &'a V) -> Ordering,
240 {
241 self.entries.binary_search_by(move |a| f(&a.key, &a.value))
242 }
243
244 #[inline]
251 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
252 where
253 F: FnMut(&'a K, &'a V) -> B,
254 B: Ord,
255 {
256 self.binary_search_by(|k, v| f(k, v).cmp(b))
257 }
258
259 #[must_use]
266 pub fn partition_point<P>(&self, mut pred: P) -> usize
267 where
268 P: FnMut(&K, &V) -> bool,
269 {
270 self.entries
271 .partition_point(move |a| pred(&a.key, &a.value))
272 }
273}
274
275impl<'a, K, V> IntoIterator for &'a Slice<K, V> {
276 type IntoIter = Iter<'a, K, V>;
277 type Item = (&'a K, &'a V);
278
279 fn into_iter(self) -> Self::IntoIter {
280 self.iter()
281 }
282}
283
284impl<'a, K, V> IntoIterator for &'a mut Slice<K, V> {
285 type IntoIter = IterMut<'a, K, V>;
286 type Item = (&'a K, &'a mut V);
287
288 fn into_iter(self) -> Self::IntoIter {
289 self.iter_mut()
290 }
291}
292
293impl<K, V> IntoIterator for Box<Slice<K, V>> {
294 type IntoIter = IntoIter<K, V>;
295 type Item = (K, V);
296
297 fn into_iter(self) -> Self::IntoIter {
298 IntoIter::new(self.into_entries())
299 }
300}
301
302impl<K, V> Default for &'_ Slice<K, V> {
303 fn default() -> Self {
304 Slice::from_slice(&[])
305 }
306}
307
308impl<K, V> Default for &'_ mut Slice<K, V> {
309 fn default() -> Self {
310 Slice::from_mut_slice(&mut [])
311 }
312}
313
314impl<K, V> Default for Box<Slice<K, V>> {
315 fn default() -> Self {
316 Slice::from_boxed(Box::default())
317 }
318}
319
320impl<K: Clone, V: Clone> Clone for Box<Slice<K, V>> {
321 fn clone(&self) -> Self {
322 Slice::from_boxed(self.entries.to_vec().into_boxed_slice())
323 }
324}
325
326impl<K: Copy, V: Copy> From<&Slice<K, V>> for Box<Slice<K, V>> {
327 fn from(slice: &Slice<K, V>) -> Self {
328 Slice::from_boxed(Box::from(&slice.entries))
329 }
330}
331
332impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Slice<K, V> {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 f.debug_list().entries(self).finish()
335 }
336}
337
338impl<K: PartialEq, V: PartialEq> PartialEq for Slice<K, V> {
339 fn eq(&self, other: &Self) -> bool {
340 self.len() == other.len() && self.iter().eq(other)
341 }
342}
343
344impl<K: Eq, V: Eq> Eq for Slice<K, V> {}
345
346impl<K: PartialOrd, V: PartialOrd> PartialOrd for Slice<K, V> {
347 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
348 self.iter().partial_cmp(other)
349 }
350}
351
352impl<K: Ord, V: Ord> Ord for Slice<K, V> {
353 fn cmp(&self, other: &Self) -> Ordering {
354 self.iter().cmp(other)
355 }
356}
357
358impl<K: Hash, V: Hash> Hash for Slice<K, V> {
359 fn hash<H: Hasher>(&self, state: &mut H) {
360 self.len().hash(state);
361 for (key, value) in self {
362 key.hash(state);
363 value.hash(state);
364 }
365 }
366}
367
368impl<K, V> Index<usize> for Slice<K, V> {
369 type Output = V;
370
371 fn index(&self, index: usize) -> &V {
372 &self.entries[index].value
373 }
374}
375
376impl<K, V> IndexMut<usize> for Slice<K, V> {
377 fn index_mut(&mut self, index: usize) -> &mut V {
378 &mut self.entries[index].value
379 }
380}
381
382macro_rules! impl_index {
386 ($($range:ty),*) => {$(
387 impl<K, V, S> Index<$range> for IndexMap<K, V, S> {
388 type Output = Slice<K, V>;
389
390 fn index(&self, range: $range) -> &Self::Output {
391 Slice::from_slice(&self.as_entries()[range])
392 }
393 }
394
395 impl<K, V, S> IndexMut<$range> for IndexMap<K, V, S> {
396 fn index_mut(&mut self, range: $range) -> &mut Self::Output {
397 Slice::from_mut_slice(&mut self.as_entries_mut()[range])
398 }
399 }
400
401 impl<K, V> Index<$range> for Slice<K, V> {
402 type Output = Slice<K, V>;
403
404 fn index(&self, range: $range) -> &Self {
405 Self::from_slice(&self.entries[range])
406 }
407 }
408
409 impl<K, V> IndexMut<$range> for Slice<K, V> {
410 fn index_mut(&mut self, range: $range) -> &mut Self {
411 Self::from_mut_slice(&mut self.entries[range])
412 }
413 }
414 )*}
415}
416impl_index!(
417 ops::Range<usize>,
418 ops::RangeFrom<usize>,
419 ops::RangeFull,
420 ops::RangeInclusive<usize>,
421 ops::RangeTo<usize>,
422 ops::RangeToInclusive<usize>,
423 (Bound<usize>, Bound<usize>)
424);
425
426#[cfg(test)]
427mod tests {
428 use super::*;
429
430 #[test]
431 fn slice_index() {
432 fn check(
433 vec_slice: &[(i32, i32)],
434 map_slice: &Slice<i32, i32>,
435 sub_slice: &Slice<i32, i32>,
436 ) {
437 assert_eq!(map_slice as *const _, sub_slice as *const _);
438 itertools::assert_equal(
439 vec_slice.iter().copied(),
440 map_slice.iter().map(|(&k, &v)| (k, v)),
441 );
442 itertools::assert_equal(vec_slice.iter().map(|(k, _)| k), map_slice.keys());
443 itertools::assert_equal(vec_slice.iter().map(|(_, v)| v), map_slice.values());
444 }
445
446 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
447 let map: IndexMap<i32, i32> = vec.iter().cloned().collect();
448 let slice = map.as_slice();
449
450 check(&vec[..], &map[..], &slice[..]);
452
453 for i in 0usize..10 {
454 assert_eq!(vec[i].1, map[i]);
456 assert_eq!(vec[i].1, slice[i]);
457 assert_eq!(map[&(i as i32)], map[i]);
458 assert_eq!(map[&(i as i32)], slice[i]);
459
460 check(&vec[i..], &map[i..], &slice[i..]);
462
463 check(&vec[..i], &map[..i], &slice[..i]);
465
466 check(&vec[..=i], &map[..=i], &slice[..=i]);
468
469 let bounds = (Bound::Excluded(i), Bound::Unbounded);
471 check(&vec[i + 1..], &map[bounds], &slice[bounds]);
472
473 for j in i..=10 {
474 check(&vec[i..j], &map[i..j], &slice[i..j]);
476 }
477
478 for j in i..10 {
479 check(&vec[i..=j], &map[i..=j], &slice[i..=j]);
481 }
482 }
483 }
484
485 #[test]
486 fn slice_index_mut() {
487 fn check_mut(
488 vec_slice: &[(i32, i32)],
489 map_slice: &mut Slice<i32, i32>,
490 sub_slice: &mut Slice<i32, i32>,
491 ) {
492 assert_eq!(map_slice, sub_slice);
493 itertools::assert_equal(
494 vec_slice.iter().copied(),
495 map_slice.iter_mut().map(|(&k, &mut v)| (k, v)),
496 );
497 itertools::assert_equal(
498 vec_slice.iter().map(|&(_, v)| v),
499 map_slice.values_mut().map(|&mut v| v),
500 );
501 }
502
503 let vec: Vec<(i32, i32)> = (0..10).map(|i| (i, i * i)).collect();
504 let mut map: IndexMap<i32, i32> = vec.iter().cloned().collect();
505 let mut map2 = map.clone();
506 let slice = map2.as_mut_slice();
507
508 check_mut(&vec[..], &mut map[..], &mut slice[..]);
510
511 for i in 0usize..10 {
512 assert_eq!(&mut map[i], &mut slice[i]);
514
515 check_mut(&vec[i..], &mut map[i..], &mut slice[i..]);
517
518 check_mut(&vec[..i], &mut map[..i], &mut slice[..i]);
520
521 check_mut(&vec[..=i], &mut map[..=i], &mut slice[..=i]);
523
524 let bounds = (Bound::Excluded(i), Bound::Unbounded);
526 check_mut(&vec[i + 1..], &mut map[bounds], &mut slice[bounds]);
527
528 for j in i..=10 {
529 check_mut(&vec[i..j], &mut map[i..j], &mut slice[i..j]);
531 }
532
533 for j in i..10 {
534 check_mut(&vec[i..=j], &mut map[i..=j], &mut slice[i..=j]);
536 }
537 }
538 }
539}