1use alloc::collections::TryReserveError;
68use alloc::vec::Vec;
69use core::cmp::Ordering;
70use core::fmt;
71use core::hash::{Hash, Hasher};
72use core::iter::{FusedIterator, Zip};
73use core::ops::{Index, RangeBounds};
74use core::slice;
75
76use crate::hash::hash_unordered;
77use crate::key::Key;
78use crate::page::{DEFAULT_PAGE, Directory, Flat};
79use crate::sparse_set::{self, PagedSparseSet, Positions, Slot, index_bounds};
80
81pub struct PagedSparseMap<K, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
93 keys: PagedSparseSet<K, PAGE, D>,
97 values: Vec<V>,
98}
99
100impl<K: Key, V, const PAGE: usize, D: Directory> PagedSparseMap<K, V, PAGE, D> {
101 pub const PAGE_SIZE: usize = PAGE;
103
104 pub fn new() -> Self {
106 Self {
107 keys: PagedSparseSet::new(),
108 values: Vec::new(),
109 }
110 }
111
112 pub fn with_capacity(capacity: usize) -> Self {
115 Self {
116 keys: PagedSparseSet::with_capacity(capacity),
117 values: Vec::with_capacity(capacity),
118 }
119 }
120
121 #[inline]
123 pub fn len(&self) -> usize {
124 self.values.len()
125 }
126
127 #[inline]
129 pub fn is_empty(&self) -> bool {
130 self.values.is_empty()
131 }
132
133 #[inline]
135 pub fn capacity(&self) -> usize {
136 self.keys.capacity().min(self.values.capacity())
137 }
138
139 #[inline]
141 pub fn allocated_pages(&self) -> usize {
142 self.keys.allocated_pages()
143 }
144
145 pub fn reserve(&mut self, additional: usize) {
148 self.keys.reserve(additional);
149 self.values.reserve(additional);
150 }
151
152 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
156 self.keys.try_reserve(additional)?;
157 self.values.try_reserve(additional)
158 }
159
160 #[inline]
165 pub fn as_set(&self) -> &PagedSparseSet<K, PAGE, D> {
166 &self.keys
167 }
168
169 #[inline]
175 pub fn position(&self, key: K) -> Option<usize> {
176 self.keys.position(key)
177 }
178
179 #[inline]
181 pub fn contains_key(&self, key: K) -> bool {
182 self.keys.contains(key)
183 }
184
185 #[inline]
187 pub fn get(&self, key: K) -> Option<&V> {
188 self.position(key).map(|pos| &self.values[pos])
189 }
190
191 #[inline]
193 pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
194 self.position(key).map(|pos| &mut self.values[pos])
195 }
196
197 #[inline]
199 pub fn get_key_value(&self, key: K) -> Option<(&K, &V)> {
200 self.position(key).map(|pos| self.entry_at(pos))
201 }
202
203 #[inline]
207 pub fn occupant(&self, index: usize) -> Option<(&K, &V)> {
208 self.keys.occupant_pos(index).map(|pos| self.entry_at(pos))
209 }
210
211 #[inline]
213 pub fn occupant_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
214 let pos = self.keys.occupant_pos(index)?;
215 Some((&self.keys.as_slice()[pos], &mut self.values[pos]))
216 }
217
218 #[inline]
219 fn entry_at(&self, pos: usize) -> (&K, &V) {
220 (&self.keys.as_slice()[pos], &self.values[pos])
221 }
222
223 fn push_vacant(&mut self, key: K, index: usize, value: V) -> usize {
226 self.values.reserve(1);
229 self.keys.insert_vacant(key, index);
230 self.values.push(value);
231 self.values.len() - 1
232 }
233
234 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
248 let index = key.index();
249 match self.keys.occupant_pos(index) {
250 Some(pos) => {
251 if self.keys.as_slice()[pos] != key {
254 self.keys.overwrite_at(pos, key);
255 }
256 Some(core::mem::replace(&mut self.values[pos], value))
257 }
258 None => {
259 self.push_vacant(key, index, value);
260 None
261 }
262 }
263 }
264
265 pub fn replace(&mut self, key: K, value: V) -> Option<(K, V)> {
276 let index = key.index();
277 match self.keys.occupant_pos(index) {
278 Some(pos) => {
279 let old_key = self.keys.overwrite_at(pos, key);
280 let old_value = core::mem::replace(&mut self.values[pos], value);
281 Some((old_key, old_value))
282 }
283 None => {
284 self.push_vacant(key, index, value);
285 None
286 }
287 }
288 }
289
290 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, V> {
298 let index = key.index();
299 if self.keys.occupant_pos(index).is_some() {
300 return Err(value);
301 }
302 let pos = self.push_vacant(key, index, value);
303 Ok(&mut self.values[pos])
304 }
305
306 pub fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> &mut V {
316 self.entry(key).or_insert_with(make)
317 }
318
319 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, PAGE, D> {
338 let index = key.index();
339 let occupant = self.keys.occupant_pos(index);
340 match occupant {
341 Some(pos) if self.keys.as_slice()[pos] == key => {
342 Entry::Occupied(OccupiedEntry { map: self, pos })
343 }
344 _ => Entry::Vacant(VacantEntry {
345 map: self,
346 key,
347 index,
348 occupant,
349 }),
350 }
351 }
352
353 fn remove_at(&mut self, pos: usize) -> (K, V) {
356 let key = self.keys.remove_at(pos);
357 let value = self.values.swap_remove(pos);
358 (key, value)
359 }
360
361 pub fn remove(&mut self, key: K) -> Option<V> {
365 self.remove_entry(key).map(|(_, value)| value)
366 }
367
368 pub fn remove_entry(&mut self, key: K) -> Option<(K, V)> {
371 self.position(key).map(|pos| self.remove_at(pos))
372 }
373
374 pub fn remove_occupant(&mut self, index: usize) -> Option<(K, V)> {
376 self.keys.occupant_pos(index).map(|pos| self.remove_at(pos))
377 }
378
379 pub fn retain(&mut self, mut keep: impl FnMut(&K, &mut V) -> bool) {
385 let mut pos = 0;
386 while pos < self.values.len() {
387 let key = self.keys.as_slice()[pos];
388 if keep(&key, &mut self.values[pos]) {
389 pos += 1;
390 } else {
391 self.remove_at(pos);
395 }
396 }
397 }
398
399 pub fn clear(&mut self) {
405 self.keys.clear();
408 self.values.clear();
409 }
410
411 pub fn reset(&mut self) {
414 self.keys.clear();
417 self.values.clear();
418 self.keys.free_pages();
419 }
420
421 pub fn shrink_to_fit(&mut self) {
424 self.keys.shrink_to_fit();
425 self.values.shrink_to_fit();
426 }
427
428 #[inline]
430 pub fn key_slice(&self) -> &[K] {
431 self.keys.as_slice()
432 }
433
434 #[inline]
437 pub fn value_slice(&self) -> &[V] {
438 &self.values
439 }
440
441 #[inline]
443 pub fn value_slice_mut(&mut self) -> &mut [V] {
444 &mut self.values
445 }
446
447 #[inline]
449 pub fn keys(&self) -> slice::Iter<'_, K> {
450 self.keys.iter()
451 }
452
453 #[inline]
455 pub fn values(&self) -> slice::Iter<'_, V> {
456 self.values.iter()
457 }
458
459 #[inline]
461 pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {
462 self.values.iter_mut()
463 }
464
465 #[inline]
467 pub fn iter(&self) -> Iter<'_, K, V> {
468 Iter(self.keys.iter().zip(self.values.iter()))
469 }
470
471 #[inline]
474 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
475 IterMut(self.keys.iter().zip(self.values.iter_mut()))
476 }
477
478 pub fn drain(&mut self) -> Drain<'_, K, V> {
492 Drain(self.keys.drain().zip(self.values.drain(..)))
493 }
494
495 pub fn extract_if<F: FnMut(&K, &mut V) -> bool>(
513 &mut self,
514 pred: F,
515 ) -> ExtractIf<'_, K, V, F, PAGE, D> {
516 ExtractIf {
517 map: self,
518 pos: 0,
519 pred,
520 }
521 }
522
523 pub fn get_disjoint_mut<const N: usize>(&mut self, keys: [K; N]) -> [Option<&mut V>; N] {
540 let mut order = [(0, 0); N];
542 let mut n = 0;
543 for (i, &key) in keys.iter().enumerate() {
544 if let Some(pos) = self.position(key) {
545 order[n] = (pos, i);
546 n += 1;
547 }
548 }
549 let order = &mut order[..n];
550 order.sort_unstable();
551 for pair in order.windows(2) {
552 assert!(
553 pair[0].0 != pair[1].0,
554 "PagedSparseMap::get_disjoint_mut: key at positions {} and {} given twice",
555 pair[0].1,
556 pair[1].1
557 );
558 }
559 let mut out = [const { None }; N];
562 let mut rest: &mut [V] = &mut self.values;
563 let mut start = 0;
564 for &(pos, i) in order.iter() {
565 let (_, tail) = core::mem::take(&mut rest).split_at_mut(pos - start);
566 let (value, tail) = tail
567 .split_first_mut()
568 .expect("positions are inside the dense array");
569 out[i] = Some(value);
570 rest = tail;
571 start = pos + 1;
572 }
573 out
574 }
575
576 pub fn range(&self, keys: impl RangeBounds<K>) -> Range<'_, K, V, PAGE, D> {
599 self.range_of(&index_bounds(&keys))
600 }
601
602 fn range_of(&self, indices: &impl RangeBounds<usize>) -> Range<'_, K, V, PAGE, D> {
603 Range {
604 positions: self.keys.positions(indices),
605 values: &self.values,
606 }
607 }
608
609 pub fn first_key_value(&self) -> Option<(&K, &V)> {
612 self.range_of(&..).next()
613 }
614
615 pub fn last_key_value(&self) -> Option<(&K, &V)> {
618 self.range_of(&..).next_back()
619 }
620
621 pub fn next_occupant(&self, index: usize) -> Option<(&K, &V)> {
623 self.range_of(&(index..)).next()
624 }
625
626 pub fn prev_occupant(&self, index: usize) -> Option<(&K, &V)> {
628 self.range_of(&(..=index)).next_back()
629 }
630
631 pub fn pop_first(&mut self) -> Option<(K, V)> {
633 let pos = self.keys.positions(&..).next()?;
634 Some(self.remove_at(pos))
635 }
636
637 pub fn pop_last(&mut self) -> Option<(K, V)> {
639 let pos = self.keys.positions(&..).next_back()?;
640 Some(self.remove_at(pos))
641 }
642
643 pub fn into_keys(self) -> alloc::vec::IntoIter<K> {
645 self.keys.into_iter()
646 }
647
648 pub fn into_values(self) -> alloc::vec::IntoIter<V> {
650 self.values.into_iter()
651 }
652
653 fn reorder_by(&mut self, order: impl FnOnce(&mut [usize], &[K], &[V])) {
660 let mut perm: Vec<usize> = (0..self.len()).collect();
661 order(&mut perm, self.keys.as_slice(), &self.values);
662 let values = &mut self.values;
663 self.keys
664 .reorder_dense(|keys| permute(&mut perm, keys, values));
665 }
666
667 pub fn sort_by(&mut self, mut compare: impl FnMut((&K, &V), (&K, &V)) -> Ordering) {
674 self.reorder_by(|perm, keys, values| {
675 perm.sort_by(|&a, &b| compare((&keys[a], &values[a]), (&keys[b], &values[b])));
676 });
677 }
678
679 pub fn sort_by_key<T: Ord>(&mut self, mut f: impl FnMut(&K, &V) -> T) {
685 self.reorder_by(|perm, keys, values| {
686 perm.sort_by_key(|&i| f(&keys[i], &values[i]));
687 });
688 }
689
690 pub fn sort_by_cached_key<T: Ord>(&mut self, mut f: impl FnMut(&K, &V) -> T) {
697 self.reorder_by(|perm, keys, values| {
698 perm.sort_by_cached_key(|&i| f(&keys[i], &values[i]));
699 });
700 }
701
702 pub fn sort_keys(&mut self)
708 where
709 K: Ord,
710 {
711 self.reorder_by(|perm, keys, _| perm.sort_by_key(|&i| keys[i]));
712 }
713
714 pub fn binary_search_key(&self, key: &K) -> Result<usize, usize>
727 where
728 K: Ord,
729 {
730 self.keys.as_slice().binary_search(key)
731 }
732
733 pub fn binary_search_by(
738 &self,
739 mut compare: impl FnMut(&K, &V) -> Ordering,
740 ) -> Result<usize, usize> {
741 let (keys, values) = (self.keys.as_slice(), &self.values);
742 let mut size = keys.len();
744 let mut base = 0;
745 while size > 0 {
746 let half = size / 2;
747 let mid = base + half;
748 match compare(&keys[mid], &values[mid]) {
749 Ordering::Less => {
750 base = mid + 1;
751 size -= half + 1;
752 }
753 Ordering::Greater => size = half,
754 Ordering::Equal => return Ok(mid),
755 }
756 }
757 Err(base)
758 }
759
760 pub fn partition_point(&self, mut pred: impl FnMut(&K, &V) -> bool) -> usize {
764 self.binary_search_by(|key, value| {
765 if pred(key, value) {
766 Ordering::Less
767 } else {
768 Ordering::Greater
769 }
770 })
771 .unwrap_or_else(|pos| pos)
772 }
773
774 pub fn sort_unstable_by(&mut self, mut compare: impl FnMut((&K, &V), (&K, &V)) -> Ordering) {
780 self.reorder_by(|perm, keys, values| {
781 perm.sort_unstable_by(|&a, &b| compare((&keys[a], &values[a]), (&keys[b], &values[b])));
782 });
783 }
784
785 pub fn sort_unstable_by_key<T: Ord>(&mut self, mut f: impl FnMut(&K, &V) -> T) {
790 self.reorder_by(|perm, keys, values| {
791 perm.sort_unstable_by_key(|&i| f(&keys[i], &values[i]));
792 });
793 }
794
795 pub fn sort_unstable_keys(&mut self)
798 where
799 K: Ord,
800 {
801 self.reorder_by(|perm, keys, _| perm.sort_unstable_by_key(|&i| keys[i]));
802 }
803}
804
805fn permute<K, V>(perm: &mut [usize], keys: &mut [K], values: &mut [V]) {
813 debug_assert!(perm.len() == keys.len() && perm.len() == values.len());
814 for start in 0..perm.len() {
815 let mut cur = start;
818 while perm[cur] != start {
819 let next = perm[cur];
820 keys.swap(cur, next);
821 values.swap(cur, next);
822 perm[cur] = cur;
823 cur = next;
824 }
825 perm[cur] = cur;
826 }
827}
828
829impl<K: Key, V, const PAGE: usize, D: Directory> Default for PagedSparseMap<K, V, PAGE, D> {
830 fn default() -> Self {
831 Self::new()
832 }
833}
834
835impl<K: Key, V: Clone, const PAGE: usize, D: Directory> Clone for PagedSparseMap<K, V, PAGE, D>
836where
837 D::Store<Slot, PAGE>: Clone,
838{
839 fn clone(&self) -> Self {
840 Self {
841 keys: self.keys.clone(),
842 values: self.values.clone(),
843 }
844 }
845}
846
847impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
848 for PagedSparseMap<K, V, PAGE, D>
849{
850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851 f.debug_map().entries(self.iter()).finish()
852 }
853}
854
855impl<K: Key, V: PartialEq<W>, W, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
858 PartialEq<PagedSparseMap<K, W, P2, D2>> for PagedSparseMap<K, V, PAGE, D>
859{
860 fn eq(&self, other: &PagedSparseMap<K, W, P2, D2>) -> bool {
861 self.len() == other.len()
862 && self.iter().all(|(&key, value)| {
863 other
864 .get(key)
865 .is_some_and(|other_value| value == other_value)
866 })
867 }
868}
869
870impl<K: Key, V: Eq, const PAGE: usize, D: Directory> Eq for PagedSparseMap<K, V, PAGE, D> {}
872
873impl<K: Key + Hash, V: Hash, const PAGE: usize, D: Directory> Hash
875 for PagedSparseMap<K, V, PAGE, D>
876{
877 fn hash<H: Hasher>(&self, state: &mut H) {
878 hash_unordered(self.iter(), state);
879 }
880}
881
882impl<K: Key, V, const PAGE: usize, D: Directory> Index<K> for PagedSparseMap<K, V, PAGE, D> {
888 type Output = V;
889
890 fn index(&self, key: K) -> &V {
891 self.get(key).expect("key not in PagedSparseMap")
892 }
893}
894
895impl<K: Key, V, const PAGE: usize, D: Directory> Extend<(K, V)> for PagedSparseMap<K, V, PAGE, D> {
898 fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
899 for (key, value) in iter {
900 self.insert(key, value);
901 }
902 }
903}
904
905impl<'a, K: Key + 'a, V: Copy + 'a, const PAGE: usize, D: Directory> Extend<(&'a K, &'a V)>
906 for PagedSparseMap<K, V, PAGE, D>
907{
908 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
909 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
910 }
911}
912
913impl<K: Key, V, const PAGE: usize, D: Directory> FromIterator<(K, V)>
914 for PagedSparseMap<K, V, PAGE, D>
915{
916 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
917 let mut map = Self::new();
918 map.extend(iter);
919 map
920 }
921}
922
923impl<'a, K: Key, V, const PAGE: usize, D: Directory> IntoIterator
924 for &'a PagedSparseMap<K, V, PAGE, D>
925{
926 type Item = (&'a K, &'a V);
927 type IntoIter = Iter<'a, K, V>;
928
929 fn into_iter(self) -> Self::IntoIter {
930 self.iter()
931 }
932}
933
934impl<'a, K: Key, V, const PAGE: usize, D: Directory> IntoIterator
935 for &'a mut PagedSparseMap<K, V, PAGE, D>
936{
937 type Item = (&'a K, &'a mut V);
938 type IntoIter = IterMut<'a, K, V>;
939
940 fn into_iter(self) -> Self::IntoIter {
941 self.iter_mut()
942 }
943}
944
945impl<K: Key, V, const PAGE: usize, D: Directory> IntoIterator for PagedSparseMap<K, V, PAGE, D> {
946 type Item = (K, V);
947 type IntoIter = IntoIter<K, V>;
948
949 fn into_iter(self) -> Self::IntoIter {
950 IntoIter(self.keys.into_iter().zip(self.values))
951 }
952}
953
954macro_rules! zip_iterator {
955 ($(#[$doc:meta])* $name:ident<$($lt:lifetime,)? $k:ident, $v:ident>, $inner:ty, $item:ty) => {
956 $(#[$doc])*
957 #[derive(Debug)]
958 pub struct $name<$($lt,)? $k, $v>($inner);
959
960 impl<$($lt,)? $k, $v> Iterator for $name<$($lt,)? $k, $v> {
961 type Item = $item;
962
963 #[inline]
964 fn next(&mut self) -> Option<Self::Item> {
965 self.0.next()
966 }
967
968 #[inline]
969 fn size_hint(&self) -> (usize, Option<usize>) {
970 self.0.size_hint()
971 }
972 }
973
974 impl<$($lt,)? $k, $v> DoubleEndedIterator for $name<$($lt,)? $k, $v> {
975 #[inline]
976 fn next_back(&mut self) -> Option<Self::Item> {
977 self.0.next_back()
978 }
979 }
980
981 impl<$($lt,)? $k, $v> ExactSizeIterator for $name<$($lt,)? $k, $v> {}
982
983 impl<$($lt,)? $k, $v> FusedIterator for $name<$($lt,)? $k, $v> {}
984 };
985}
986
987zip_iterator!(
988 Iter<'a, K, V>,
991 Zip<slice::Iter<'a, K>, slice::Iter<'a, V>>,
992 (&'a K, &'a V)
993);
994
995zip_iterator!(
996 IterMut<'a, K, V>,
999 Zip<slice::Iter<'a, K>, slice::IterMut<'a, V>>,
1000 (&'a K, &'a mut V)
1001);
1002
1003zip_iterator!(
1004 IntoIter<K, V>,
1006 Zip<alloc::vec::IntoIter<K>, alloc::vec::IntoIter<V>>,
1007 (K, V)
1008);
1009
1010zip_iterator!(
1011 Drain<'a, K, V>,
1013 Zip<sparse_set::Drain<'a, K>, alloc::vec::Drain<'a, V>>,
1014 (K, V)
1015);
1016
1017pub struct Range<'a, K, V, const PAGE: usize = DEFAULT_PAGE, D: Directory + 'a = Flat> {
1019 positions: Positions<'a, K, PAGE, D>,
1020 values: &'a [V],
1021}
1022
1023impl<'a, K: Key, V, const PAGE: usize, D: Directory + 'a> Iterator for Range<'a, K, V, PAGE, D> {
1024 type Item = (&'a K, &'a V);
1025
1026 #[inline]
1027 fn next(&mut self) -> Option<Self::Item> {
1028 let pos = self.positions.next()?;
1029 Some((&self.positions.dense()[pos], &self.values[pos]))
1030 }
1031
1032 #[inline]
1033 fn size_hint(&self) -> (usize, Option<usize>) {
1034 self.positions.size_hint()
1035 }
1036}
1037
1038impl<'a, K: Key, V, const PAGE: usize, D: Directory + 'a> DoubleEndedIterator
1039 for Range<'a, K, V, PAGE, D>
1040{
1041 #[inline]
1042 fn next_back(&mut self) -> Option<Self::Item> {
1043 let pos = self.positions.next_back()?;
1044 Some((&self.positions.dense()[pos], &self.values[pos]))
1045 }
1046}
1047
1048impl<'a, K: Key, V, const PAGE: usize, D: Directory + 'a> FusedIterator
1049 for Range<'a, K, V, PAGE, D>
1050{
1051}
1052
1053impl<'a, K, V, const PAGE: usize, D: Directory + 'a> Clone for Range<'a, K, V, PAGE, D> {
1054 fn clone(&self) -> Self {
1055 Self {
1056 positions: self.positions.clone(),
1057 values: self.values,
1058 }
1059 }
1060}
1061
1062impl<'a, K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory + 'a> fmt::Debug
1063 for Range<'a, K, V, PAGE, D>
1064{
1065 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1066 f.debug_list().entries(self.clone()).finish()
1067 }
1068}
1069
1070pub enum Entry<'a, K: Key, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1073 Occupied(OccupiedEntry<'a, K, V, PAGE, D>),
1075 Vacant(VacantEntry<'a, K, V, PAGE, D>),
1077}
1078
1079pub struct OccupiedEntry<'a, K: Key, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1081 map: &'a mut PagedSparseMap<K, V, PAGE, D>,
1082 pos: usize,
1083}
1084
1085pub struct VacantEntry<'a, K: Key, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1087 map: &'a mut PagedSparseMap<K, V, PAGE, D>,
1088 key: K,
1089 index: usize,
1090 occupant: Option<usize>,
1091}
1092
1093impl<'a, K: Key, V, const PAGE: usize, D: Directory> Entry<'a, K, V, PAGE, D> {
1094 #[inline]
1096 pub fn key(&self) -> &K {
1097 match self {
1098 Entry::Occupied(entry) => entry.key(),
1099 Entry::Vacant(entry) => entry.key(),
1100 }
1101 }
1102
1103 #[inline]
1105 pub fn or_insert(self, default: V) -> &'a mut V {
1106 match self {
1107 Entry::Occupied(entry) => entry.into_mut(),
1108 Entry::Vacant(entry) => entry.insert(default),
1109 }
1110 }
1111
1112 #[inline]
1115 pub fn or_insert_with(self, make: impl FnOnce() -> V) -> &'a mut V {
1116 match self {
1117 Entry::Occupied(entry) => entry.into_mut(),
1118 Entry::Vacant(entry) => entry.insert(make()),
1119 }
1120 }
1121
1122 #[inline]
1124 pub fn or_insert_with_key(self, make: impl FnOnce(&K) -> V) -> &'a mut V {
1125 match self {
1126 Entry::Occupied(entry) => entry.into_mut(),
1127 Entry::Vacant(entry) => {
1128 let value = make(entry.key());
1129 entry.insert(value)
1130 }
1131 }
1132 }
1133
1134 #[inline]
1136 pub fn or_default(self) -> &'a mut V
1137 where
1138 V: Default,
1139 {
1140 self.or_insert_with(V::default)
1141 }
1142
1143 #[inline]
1145 pub fn and_modify(mut self, f: impl FnOnce(&mut V)) -> Self {
1146 if let Entry::Occupied(entry) = &mut self {
1147 f(entry.get_mut());
1148 }
1149 self
1150 }
1151
1152 #[inline]
1156 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, PAGE, D> {
1157 match self {
1158 Entry::Occupied(mut entry) => {
1159 entry.insert(value);
1160 entry
1161 }
1162 Entry::Vacant(entry) => entry.insert_entry(value),
1163 }
1164 }
1165}
1166
1167impl<'a, K: Key, V, const PAGE: usize, D: Directory> OccupiedEntry<'a, K, V, PAGE, D> {
1168 #[inline]
1170 pub fn key(&self) -> &K {
1171 &self.map.keys.as_slice()[self.pos]
1172 }
1173
1174 #[inline]
1176 pub fn get(&self) -> &V {
1177 &self.map.values[self.pos]
1178 }
1179
1180 #[inline]
1182 pub fn get_mut(&mut self) -> &mut V {
1183 &mut self.map.values[self.pos]
1184 }
1185
1186 #[inline]
1188 pub fn into_mut(self) -> &'a mut V {
1189 &mut self.map.values[self.pos]
1190 }
1191
1192 #[inline]
1194 pub fn insert(&mut self, value: V) -> V {
1195 core::mem::replace(self.get_mut(), value)
1196 }
1197
1198 #[inline]
1200 pub fn remove(self) -> V {
1201 self.remove_entry().1
1202 }
1203
1204 pub fn remove_entry(self) -> (K, V) {
1208 self.map.remove_at(self.pos)
1209 }
1210}
1211
1212impl<'a, K: Key, V, const PAGE: usize, D: Directory> VacantEntry<'a, K, V, PAGE, D> {
1213 #[inline]
1215 pub fn key(&self) -> &K {
1216 &self.key
1217 }
1218
1219 #[inline]
1221 pub fn into_key(self) -> K {
1222 self.key
1223 }
1224
1225 #[inline]
1233 pub fn insert(self, value: V) -> &'a mut V {
1234 self.insert_entry(value).into_mut()
1235 }
1236
1237 fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, PAGE, D> {
1238 let Self {
1239 map,
1240 key,
1241 index,
1242 occupant,
1243 } = self;
1244 let pos = match occupant {
1245 Some(pos) => {
1246 map.keys.overwrite_at(pos, key);
1247 drop(core::mem::replace(&mut map.values[pos], value));
1249 pos
1250 }
1251 None => map.push_vacant(key, index, value),
1252 };
1253 OccupiedEntry { map, pos }
1254 }
1255}
1256
1257impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1258 for Entry<'_, K, V, PAGE, D>
1259{
1260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261 match self {
1262 Entry::Occupied(entry) => f.debug_tuple("Occupied").field(entry).finish(),
1263 Entry::Vacant(entry) => f.debug_tuple("Vacant").field(entry).finish(),
1264 }
1265 }
1266}
1267
1268impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1269 for OccupiedEntry<'_, K, V, PAGE, D>
1270{
1271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1272 f.debug_struct("OccupiedEntry")
1273 .field("key", self.key())
1274 .field("value", self.get())
1275 .finish()
1276 }
1277}
1278
1279impl<K: Key + fmt::Debug, V, const PAGE: usize, D: Directory> fmt::Debug
1280 for VacantEntry<'_, K, V, PAGE, D>
1281{
1282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1283 f.debug_struct("VacantEntry")
1284 .field("key", self.key())
1285 .finish()
1286 }
1287}
1288
1289pub struct ExtractIf<'a, K, V, F, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1291 map: &'a mut PagedSparseMap<K, V, PAGE, D>,
1292 pos: usize,
1293 pred: F,
1294}
1295
1296impl<K: Key, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> Iterator
1297 for ExtractIf<'_, K, V, F, PAGE, D>
1298{
1299 type Item = (K, V);
1300
1301 fn next(&mut self) -> Option<(K, V)> {
1302 while self.pos < self.map.values.len() {
1303 let pos = self.pos;
1304 let key = self.map.keys.as_slice()[pos];
1305 self.pos += 1;
1307 if (self.pred)(&key, &mut self.map.values[pos]) {
1308 self.pos = pos;
1310 return Some(self.map.remove_at(pos));
1311 }
1312 }
1313 None
1314 }
1315
1316 fn size_hint(&self) -> (usize, Option<usize>) {
1317 (0, Some(self.map.values.len() - self.pos))
1318 }
1319}
1320
1321impl<K: Key, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> FusedIterator
1322 for ExtractIf<'_, K, V, F, PAGE, D>
1323{
1324}
1325
1326impl<K: Key + fmt::Debug, V: fmt::Debug, F, const PAGE: usize, D: Directory> fmt::Debug
1327 for ExtractIf<'_, K, V, F, PAGE, D>
1328{
1329 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1330 let pos = self.pos;
1331 f.debug_struct("ExtractIf")
1332 .field("untested_keys", &&self.map.keys.as_slice()[pos..])
1333 .field("untested_values", &&self.map.values[pos..])
1334 .finish_non_exhaustive()
1335 }
1336}
1337
1338impl<K, V> Clone for Iter<'_, K, V> {
1339 fn clone(&self) -> Self {
1340 Self(self.0.clone())
1341 }
1342}
1343
1344impl<K: Clone, V: Clone> Clone for IntoIter<K, V> {
1345 fn clone(&self) -> Self {
1346 Self(self.0.clone())
1347 }
1348}
1349
1350#[cfg(feature = "rayon")]
1351mod rayon_impl {
1352 use super::*;
1353 use rayon::iter::Zip;
1354 use rayon::prelude::*;
1355 use rayon::slice::{Iter, IterMut};
1356
1357 impl<K: Key, V, const PAGE: usize, D: Directory> PagedSparseMap<K, V, PAGE, D> {
1358 pub fn par_keys(&self) -> Iter<'_, K>
1360 where
1361 K: Sync,
1362 {
1363 self.key_slice().par_iter()
1364 }
1365
1366 pub fn par_values(&self) -> Iter<'_, V>
1368 where
1369 V: Sync,
1370 {
1371 self.value_slice().par_iter()
1372 }
1373
1374 pub fn par_values_mut(&mut self) -> IterMut<'_, V>
1376 where
1377 V: Send,
1378 {
1379 self.value_slice_mut().par_iter_mut()
1380 }
1381 }
1382
1383 impl<'a, K: Key + Sync, V: Sync, const PAGE: usize, D: Directory> IntoParallelIterator
1384 for &'a PagedSparseMap<K, V, PAGE, D>
1385 {
1386 type Item = (&'a K, &'a V);
1387 type Iter = Zip<Iter<'a, K>, Iter<'a, V>>;
1388
1389 fn into_par_iter(self) -> Self::Iter {
1390 self.par_keys().zip(self.par_values())
1391 }
1392 }
1393
1394 impl<'a, K: Key + Sync, V: Send, const PAGE: usize, D: Directory> IntoParallelIterator
1395 for &'a mut PagedSparseMap<K, V, PAGE, D>
1396 {
1397 type Item = (&'a K, &'a mut V);
1398 type Iter = Zip<Iter<'a, K>, IterMut<'a, V>>;
1399
1400 fn into_par_iter(self) -> Self::Iter {
1401 self.keys
1402 .as_slice()
1403 .par_iter()
1404 .zip(self.values.par_iter_mut())
1405 }
1406 }
1407}
1408
1409#[cfg(feature = "serde")]
1410mod serde_impl {
1411 use super::*;
1412 use core::marker::PhantomData;
1413 use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
1414 use serde::ser::{Serialize, Serializer};
1415
1416 fn max_prealloc<K, V>() -> usize {
1419 let entry = core::mem::size_of::<K>() + core::mem::size_of::<V>();
1420 usize::try_from(1_u32 << 20)
1422 .unwrap_or(usize::MAX)
1423 .checked_div(entry)
1424 .unwrap_or(usize::MAX)
1425 .min(4096)
1426 }
1427
1428 impl<K: Key + Serialize, V: Serialize, const PAGE: usize, D: Directory> Serialize
1430 for PagedSparseMap<K, V, PAGE, D>
1431 {
1432 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1433 serializer.collect_map(self.iter())
1434 }
1435 }
1436
1437 impl<'de, K, V, const PAGE: usize, D> Deserialize<'de> for PagedSparseMap<K, V, PAGE, D>
1446 where
1447 K: Key + Deserialize<'de>,
1448 V: Deserialize<'de>,
1449 D: Directory,
1450 {
1451 fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1452 struct MapVisitor<K, V, const PAGE: usize, D>(PhantomData<(K, V, D)>);
1453
1454 impl<'de, K, V, const PAGE: usize, D> Visitor<'de> for MapVisitor<K, V, PAGE, D>
1455 where
1456 K: Key + Deserialize<'de>,
1457 V: Deserialize<'de>,
1458 D: Directory,
1459 {
1460 type Value = PagedSparseMap<K, V, PAGE, D>;
1461
1462 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1463 f.write_str("a map of keys to values")
1464 }
1465
1466 fn visit_map<A: MapAccess<'de>>(
1467 self,
1468 mut access: A,
1469 ) -> Result<Self::Value, A::Error> {
1470 let hint = access.size_hint().unwrap_or(0).min(max_prealloc::<K, V>());
1473 let mut map = PagedSparseMap::with_capacity(hint);
1474 while let Some((key, value)) = access.next_entry()? {
1475 map.insert(key, value);
1476 }
1477 Ok(map)
1478 }
1479 }
1480
1481 deserializer.deserialize_map(MapVisitor::<K, V, PAGE, D>(PhantomData))
1482 }
1483 }
1484}
1485
1486#[cfg(all(test, any(target_pointer_width = "32", target_pointer_width = "64")))]
1489mod tests {
1490 use super::*;
1491 use alloc::string::{String, ToString};
1492
1493 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
1494 struct Gen(u32);
1495
1496 impl Key for Gen {
1497 fn index(self) -> usize {
1498 (self.0 & 0xffff) as usize
1499 }
1500 }
1501
1502 fn assert_parallel<K: Key + fmt::Debug, V, const PAGE: usize, D: Directory>(
1503 map: &PagedSparseMap<K, V, PAGE, D>,
1504 ) {
1505 assert_eq!(map.key_slice().len(), map.value_slice().len());
1506 for (pos, &key) in map.key_slice().iter().enumerate() {
1507 assert_eq!(map.position(key), Some(pos), "{key:?}");
1508 }
1509 }
1510
1511 #[test]
1512 fn remove_moves_last_entry_with_its_value() {
1513 let mut map: PagedSparseMap<u32, char, 4> = [(1, 'a'), (2, 'b'), (3, 'c'), (40, 'd')]
1514 .into_iter()
1515 .collect();
1516 assert_eq!(map.remove(1), Some('a'));
1517 assert_eq!(map.key_slice(), &[40, 2, 3]);
1518 assert_eq!(map.value_slice(), &['d', 'b', 'c']);
1519 assert_eq!(map.remove(1), None);
1520 assert_eq!(map.remove_entry(3), Some((3, 'c')));
1521 assert_eq!(map[40], 'd');
1522 assert_parallel(&map);
1523 }
1524
1525 #[test]
1526 fn insert_updates_in_place() {
1527 let mut map: PagedSparseMap<u32, u32> = (0..5).map(|k| (k, k * 10)).collect();
1528 assert_eq!(map.insert(2, 99), Some(20));
1529 assert_eq!(map.position(2), Some(2));
1530 assert_eq!(map.value_slice(), &[0, 10, 99, 30, 40]);
1531 *map.get_mut(4).unwrap() += 1;
1532 assert_eq!(map.get(4), Some(&41));
1533 }
1534
1535 #[derive(Clone, Copy, Debug)]
1537 struct Tagged {
1538 id: u32,
1539 tag: u8,
1540 }
1541
1542 impl PartialEq for Tagged {
1543 fn eq(&self, other: &Self) -> bool {
1544 self.id == other.id
1545 }
1546 }
1547
1548 impl Eq for Tagged {}
1549
1550 impl Key for Tagged {
1551 fn index(self) -> usize {
1552 self.id as usize
1553 }
1554 }
1555
1556 #[test]
1557 fn insert_keeps_an_equal_stored_key_and_replace_does_not() {
1558 let mut map: PagedSparseMap<Tagged, u8> = PagedSparseMap::new();
1559 map.insert(Tagged { id: 3, tag: 1 }, 10);
1560 assert_eq!(map.insert(Tagged { id: 3, tag: 2 }, 20), Some(10));
1561 assert_eq!(map.key_slice()[0].tag, 1);
1562 let (old, _) = map.replace(Tagged { id: 3, tag: 3 }, 30).unwrap();
1563 assert_eq!(old.tag, 1);
1564 assert_eq!(map.key_slice()[0].tag, 3);
1565 assert_eq!(map.clone().into_keys().next().map(|k| k.tag), Some(3));
1566 assert_eq!(map.into_values().collect::<Vec<_>>(), [30]);
1567 }
1568
1569 #[test]
1570 fn generations_by_method() {
1571 let old = Gen(7);
1572 let new = Gen(7 | 1 << 16);
1573 let mut map: PagedSparseMap<Gen, &str> = PagedSparseMap::new();
1574 assert_eq!(map.try_insert(old, "old").copied(), Ok("old"));
1575 assert_eq!(map.try_insert(new, "new"), Err("new"));
1576 assert_eq!(map.try_insert(old, "again"), Err("again"));
1577 assert_eq!(map.get(new), None);
1578 assert_eq!(map.occupant(7), Some((&old, &"old")));
1579
1580 assert_eq!(map.replace(new, "new"), Some((old, "old")));
1581 assert_eq!(map.get(old), None);
1582 assert_eq!(map.insert(old, "back"), Some("new"));
1583 assert_eq!(map.get_or_insert_with(new, || "made"), &"made");
1584 assert_eq!(map.get_or_insert_with(new, || unreachable!()), &"made");
1585 assert_eq!(map.len(), 1);
1586
1587 assert_eq!(map.remove(old), None);
1588 if let Some((_, v)) = map.occupant_mut(7) {
1589 *v = "edited";
1590 }
1591 assert_eq!(map.remove_occupant(7), Some((new, "edited")));
1592 assert!(map.is_empty());
1593 }
1594
1595 #[test]
1596 fn clear_is_lazy_but_correct() {
1597 let mut map: PagedSparseMap<u32, String, 4> = (0..10).map(|k| (k, k.to_string())).collect();
1598 map.clear();
1599 assert!(map.is_empty());
1600 assert_eq!(map.allocated_pages(), 3);
1601 assert!((0..10).all(|k| !map.contains_key(k)));
1602 map.insert(9, "nine".into());
1603 assert_eq!(map.get(0), None);
1604 assert_eq!(map.position(9), Some(0));
1605 map.reset();
1606 assert_eq!(map.allocated_pages(), 0);
1607 }
1608
1609 #[test]
1610 fn retain_and_sort_move_values_with_keys() {
1611 let mut map: PagedSparseMap<u32, u32, 8> = [9, 3, 7, 1, 8, 2]
1612 .into_iter()
1613 .map(|k| (k, k * 100))
1614 .collect();
1615 map.retain(|&k, v| {
1616 *v += 1;
1617 k % 3 != 0
1618 });
1619 map.sort_unstable_keys();
1620 assert_eq!(map.key_slice(), &[1, 2, 7, 8]);
1621 assert_eq!(map.value_slice(), &[101, 201, 701, 801]);
1622 assert_parallel(&map);
1623
1624 map.sort_unstable_by(|(_, a), (_, b)| b.cmp(a));
1625 assert_eq!(map.key_slice(), &[8, 7, 2, 1]);
1626 map.sort_unstable_by_key(|&k, _| k % 7);
1627 assert_eq!(map.key_slice(), &[7, 8, 1, 2]);
1628 assert_eq!(map.value_slice(), &[701, 801, 101, 201]);
1629 assert_parallel(&map);
1630 }
1631
1632 #[test]
1633 fn stable_sorts_keep_ties_in_order_and_searches_find_positions() {
1634 let mut map: PagedSparseMap<u32, u32, 4> = [(5, 1), (9, 0), (2, 1), (7, 0), (40, 1)]
1635 .into_iter()
1636 .collect();
1637 map.sort_by_key(|_, &v| v);
1638 assert_eq!(map.key_slice(), &[9, 7, 5, 2, 40]);
1639 assert_eq!(map.value_slice(), &[0, 0, 1, 1, 1]);
1640 assert_parallel(&map);
1641 assert_eq!(map.partition_point(|_, &v| v == 0), 2);
1642 assert_eq!(map.partition_point(|_, _| true), 5);
1643 assert_eq!(map.partition_point(|_, _| false), 0);
1644
1645 map.sort_by(|(a, _), (b, _)| (a % 2).cmp(&(b % 2)));
1646 assert_eq!(map.key_slice(), &[2, 40, 9, 7, 5]);
1647 let mut calls = 0;
1648 map.sort_by_cached_key(|&k, _| {
1649 calls += 1;
1650 k / 10
1651 });
1652 assert_eq!(calls, 5);
1653 assert_eq!(map.key_slice(), &[2, 9, 7, 5, 40]);
1654 assert_parallel(&map);
1655
1656 map.sort_keys();
1657 assert_eq!(map.key_slice(), &[2, 5, 7, 9, 40]);
1658 assert_eq!(map.value_slice(), &[1, 1, 0, 0, 1]);
1659 assert_parallel(&map);
1660 assert_eq!(map.binary_search_key(&7), Ok(2));
1661 assert_eq!(map.binary_search_key(&0), Err(0));
1662 assert_eq!(map.binary_search_key(&8), Err(3));
1663 assert_eq!(map.binary_search_key(&41), Err(5));
1664 for (pos, &key) in map.key_slice().iter().enumerate() {
1665 assert_eq!(map.binary_search_by(|k, _| k.cmp(&key)), Ok(pos));
1666 }
1667 assert_eq!(map.binary_search_by(|k, _| k.cmp(&6)), Err(2));
1668 let empty: PagedSparseMap<u32, u32> = PagedSparseMap::new();
1669 assert_eq!(empty.binary_search_key(&1), Err(0));
1670 assert_eq!(empty.partition_point(|_, _| true), 0);
1671 }
1672
1673 #[test]
1674 fn permute_handles_every_permutation_of_four() {
1675 for a in 0..4 {
1678 for b in 0..4 {
1679 for c in 0..4 {
1680 for d in 0..4 {
1681 let p = [a, b, c, d];
1682 if (0..4).any(|i| !p.contains(&i)) {
1683 continue;
1684 }
1685 let mut perm = p;
1686 let mut keys = [10, 11, 12, 13];
1687 let mut values = ['a', 'b', 'c', 'd'];
1688 permute(&mut perm, &mut keys, &mut values);
1689 assert_eq!(keys, p.map(|i| 10 + i), "{p:?}");
1690 assert_eq!(values, p.map(|i| ['a', 'b', 'c', 'd'][i]), "{p:?}");
1691 assert_eq!(perm, [0, 1, 2, 3]);
1692 }
1693 }
1694 }
1695 }
1696 }
1697
1698 #[test]
1699 fn equality_and_iterators() {
1700 let a: PagedSparseMap<u32, i32> = [(1, -1), (2, -2)].into_iter().collect();
1701 let mut b: PagedSparseMap<u32, i32> = [(2, -2), (1, -1)].into_iter().collect();
1702 assert_eq!(a, b);
1703 for (_, v) in &mut b {
1704 *v *= 2;
1705 }
1706 assert_ne!(a, b);
1707 assert_eq!(b.iter().rev().collect::<Vec<_>>(), [(&1, &-2), (&2, &-4)]);
1708 assert_eq!(b.iter().len(), 2);
1709 assert_eq!(b.into_iter().collect::<Vec<_>>(), [(2, -4), (1, -2)]);
1710 }
1711}