1use alloc::boxed::Box;
113use alloc::vec::{self, Vec};
114use core::fmt;
115use core::hash::{Hash, Hasher};
116use core::iter::{Fuse, FusedIterator};
117use core::marker::PhantomData;
118use core::mem;
119use core::ops::{Bound, Index, RangeBounds};
120use core::slice;
121
122use crate::key::{DirectKey, Key};
123use crate::page::{DEFAULT_PAGE, Directory, Flat, PageStore, split};
124
125pub type Slot<K, V> = Option<(<K as DirectKey>::Tag, V)>;
128
129type Store<K, V, const PAGE: usize, D> = <D as Directory>::Store<Slot<K, V>, PAGE>;
130type Pages<'a, K, V, const PAGE: usize, D> =
131 <Store<K, V, PAGE, D> as PageStore<Slot<K, V>, PAGE>>::Pages<'a>;
132type PagesMut<'a, K, V, const PAGE: usize, D> =
133 <Store<K, V, PAGE, D> as PageStore<Slot<K, V>, PAGE>>::PagesMut<'a>;
134type IntoPages<K, V, const PAGE: usize, D> =
135 <Store<K, V, PAGE, D> as PageStore<Slot<K, V>, PAGE>>::IntoPages;
136
137pub struct PagedDirectMap<K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
150 pages: Store<K, V, PAGE, D>,
154 len: usize,
155}
156
157impl<K: DirectKey, V, const PAGE: usize, D: Directory> PagedDirectMap<K, V, PAGE, D> {
158 pub const PAGE_SIZE: usize = PAGE;
160
161 pub fn new() -> Self {
163 Self {
164 pages: Default::default(),
165 len: 0,
166 }
167 }
168
169 #[inline]
171 pub fn len(&self) -> usize {
172 self.len
173 }
174
175 #[inline]
177 pub fn is_empty(&self) -> bool {
178 self.len == 0
179 }
180
181 #[inline]
183 pub fn allocated_pages(&self) -> usize {
184 self.pages.allocated()
185 }
186
187 #[inline]
188 fn slot(&self, index: usize) -> Option<&Slot<K, V>> {
189 let (page, offset) = split::<PAGE>(index);
190 self.pages.get(page).map(|page| &page[offset])
191 }
192
193 #[inline]
194 fn slot_mut(&mut self, index: usize) -> Option<&mut Slot<K, V>> {
195 let (page, offset) = split::<PAGE>(index);
196 self.pages.get_mut(page).map(|page| &mut page[offset])
197 }
198
199 #[inline]
202 fn slot_or_alloc(&mut self, index: usize) -> (&mut Slot<K, V>, &mut usize) {
203 let (page, offset) = split::<PAGE>(index);
204 (&mut self.pages.get_or_alloc(page)[offset], &mut self.len)
205 }
206
207 #[inline]
209 pub fn contains_key(&self, key: K) -> bool {
210 self.get(key).is_some()
211 }
212
213 #[inline]
215 pub fn get(&self, key: K) -> Option<&V> {
216 match self.slot(key.index())? {
217 Some((tag, value)) if *tag == key.tag() => Some(value),
218 _ => None,
219 }
220 }
221
222 #[inline]
224 pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
225 match self.slot_mut(key.index())? {
226 Some((tag, value)) if *tag == key.tag() => Some(value),
227 _ => None,
228 }
229 }
230
231 #[inline]
233 pub fn get_key_value(&self, key: K) -> Option<(K, &V)> {
234 let index = key.index();
235 match self.slot(index)? {
236 Some((tag, value)) if *tag == key.tag() => Some((K::from_parts(index, *tag), value)),
237 _ => None,
238 }
239 }
240
241 #[inline]
245 pub fn occupant(&self, index: usize) -> Option<(K, &V)> {
246 let (tag, value) = self.slot(index)?.as_ref()?;
247 Some((K::from_parts(index, *tag), value))
248 }
249
250 #[inline]
252 pub fn occupant_mut(&mut self, index: usize) -> Option<(K, &mut V)> {
253 let (tag, value) = self.slot_mut(index)?.as_mut()?;
254 Some((K::from_parts(index, *tag), value))
255 }
256
257 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
271 let tag = key.tag();
272 let (slot, len) = self.slot_or_alloc(key.index());
273 if let Some((stored, old)) = slot {
274 if *stored != tag {
275 *stored = tag;
276 }
277 return Some(mem::replace(old, value));
278 }
279 *slot = Some((tag, value));
280 *len += 1;
281 None
282 }
283
284 pub fn replace(&mut self, key: K, value: V) -> Option<(K, V)> {
294 let index = key.index();
295 let (slot, len) = self.slot_or_alloc(index);
296 let old = slot.replace((key.tag(), value));
297 if old.is_none() {
298 *len += 1;
299 }
300 old.map(|(tag, value)| (K::from_parts(index, tag), value))
301 }
302
303 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, V> {
311 let (slot, len) = self.slot_or_alloc(key.index());
312 if slot.is_some() {
313 return Err(value);
314 }
315 *len += 1;
316 let (_, value) = slot.insert((key.tag(), value));
317 Ok(value)
318 }
319
320 pub fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> &mut V {
330 let (index, tag) = (key.index(), key.tag());
331 let held_by_key = matches!(self.slot(index), Some(Some((stored, _))) if *stored == tag);
332 if !held_by_key {
333 let value = make();
335 let (slot, len) = self.slot_or_alloc(index);
336 if slot.is_none() {
337 *len += 1;
338 }
339 drop(slot.replace((tag, value)));
342 }
343 let (slot, _) = self.slot_or_alloc(index);
345 match slot {
346 Some((_, value)) => value,
347 None => unreachable!("slot was just filled"),
348 }
349 }
350
351 pub fn remove(&mut self, key: K) -> Option<V> {
353 self.remove_entry(key).map(|(_, value)| value)
354 }
355
356 pub fn remove_entry(&mut self, key: K) -> Option<(K, V)> {
359 let index = key.index();
360 let slot = self.slot_mut(index)?;
361 if !matches!(slot, Some((stored, _)) if *stored == key.tag()) {
362 return None;
363 }
364 let (tag, value) = slot.take()?;
365 self.len -= 1;
366 Some((K::from_parts(index, tag), value))
367 }
368
369 pub fn remove_occupant(&mut self, index: usize) -> Option<(K, V)> {
371 let (tag, value) = self.slot_mut(index)?.take()?;
372 self.len -= 1;
373 Some((K::from_parts(index, tag), value))
374 }
375
376 pub fn retain(&mut self, mut keep: impl FnMut(&K, &mut V) -> bool) {
382 let mut remaining = self.len;
383 for (number, page) in self.pages.pages_mut() {
384 for (offset, slot) in page.iter_mut().enumerate() {
385 if remaining == 0 {
386 return;
387 }
388 let Some((tag, value)) = slot else { continue };
389 remaining -= 1;
390 let key = K::from_parts(number * PAGE + offset, *tag);
391 if !keep(&key, value) {
392 let removed = slot.take();
393 self.len -= 1;
394 drop(removed);
395 }
396 }
397 }
398 }
399
400 pub fn clear(&mut self) {
406 self.retain(|_, _| false);
407 }
408
409 pub fn reset(&mut self) {
411 let pages = mem::take(&mut self.pages);
414 self.len = 0;
415 drop(pages);
416 }
417
418 pub fn shrink_to_fit(&mut self) {
420 if self.len == 0 {
421 self.pages.clear();
422 } else {
423 let empty: Vec<usize> = self
424 .pages
425 .pages()
426 .filter(|(_, page)| page.iter().all(Option::is_none))
427 .map(|(number, _)| number)
428 .collect();
429 for number in empty {
430 self.pages.remove(number);
431 }
432 }
433 self.pages.shrink_to_fit();
434 }
435
436 #[inline]
438 pub fn iter(&self) -> Iter<'_, K, V, PAGE, D> {
439 Iter(Cursor::new(self.pages.pages(), self.len))
440 }
441
442 #[inline]
445 pub fn iter_mut(&mut self) -> IterMut<'_, K, V, PAGE, D> {
446 IterMut(Cursor::new(self.pages.pages_mut(), self.len))
447 }
448
449 #[inline]
451 pub fn keys(&self) -> Keys<'_, K, V, PAGE, D> {
452 Keys(self.iter())
453 }
454
455 #[inline]
457 pub fn values(&self) -> Values<'_, K, V, PAGE, D> {
458 Values(self.iter())
459 }
460
461 #[inline]
463 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V, PAGE, D> {
464 ValuesMut(self.iter_mut())
465 }
466
467 pub fn range(&self, keys: impl RangeBounds<K>) -> Range<'_, K, V, PAGE, D> {
477 self.slot_range(index_bounds(&keys))
478 }
479
480 pub fn range_mut(&mut self, keys: impl RangeBounds<K>) -> RangeMut<'_, K, V, PAGE, D> {
482 self.slot_range_mut(index_bounds(&keys))
483 }
484
485 pub fn slot_range(&self, indices: impl RangeBounds<usize>) -> Range<'_, K, V, PAGE, D> {
488 let span = Span::new::<PAGE>(&indices, self.len);
489 Range(Cursor::new(
490 Trim {
491 pages: self.pages.pages_in(span.pages.clone()),
492 first: span.first,
493 last: span.last,
494 },
495 span.most,
496 ))
497 }
498
499 pub fn slot_range_mut(
502 &mut self,
503 indices: impl RangeBounds<usize>,
504 ) -> RangeMut<'_, K, V, PAGE, D> {
505 let span = Span::new::<PAGE>(&indices, self.len);
506 RangeMut(Cursor::new(
507 Trim {
508 pages: self.pages.pages_in_mut(span.pages.clone()),
509 first: span.first,
510 last: span.last,
511 },
512 span.most,
513 ))
514 }
515
516 #[inline]
520 pub fn next_occupant(&self, index: usize) -> Option<(K, &V)> {
521 self.slot_range(index..).next()
522 }
523
524 #[inline]
528 pub fn prev_occupant(&self, index: usize) -> Option<(K, &V)> {
529 self.slot_range(..=index).next_back()
530 }
531
532 #[inline]
534 pub fn first_key_value(&self) -> Option<(K, &V)> {
535 self.iter().next()
536 }
537
538 #[inline]
540 pub fn last_key_value(&self) -> Option<(K, &V)> {
541 self.iter().next_back()
542 }
543
544 pub fn pop_first(&mut self) -> Option<(K, V)> {
546 let index = self.first_key_value()?.0.index();
547 self.remove_occupant(index)
548 }
549
550 pub fn pop_last(&mut self) -> Option<(K, V)> {
552 let index = self.last_key_value()?.0.index();
553 self.remove_occupant(index)
554 }
555
556 pub fn drain(&mut self) -> Drain<'_, K, V, PAGE, D> {
572 Drain {
573 map: self,
574 next: Some(0),
575 }
576 }
577
578 pub fn extract_if<F: FnMut(&K, &mut V) -> bool>(
594 &mut self,
595 pred: F,
596 ) -> ExtractIf<'_, K, V, F, PAGE, D> {
597 ExtractIf {
598 map: self,
599 next: Some(0),
600 pred,
601 }
602 }
603
604 pub fn get_disjoint_mut<const N: usize>(&mut self, keys: [K; N]) -> [Option<&mut V>; N] {
622 let mut order = [(0, 0); N];
624 let mut n = 0;
625 for (i, &key) in keys.iter().enumerate() {
626 if self.get(key).is_some() {
627 order[n] = (key.index(), i);
628 n += 1;
629 }
630 }
631 let order = &mut order[..n];
632 order.sort_unstable();
633 for pair in order.windows(2) {
634 assert!(
635 pair[0].0 != pair[1].0,
636 "PagedDirectMap::get_disjoint_mut: key at positions {} and {} given twice",
637 pair[0].1,
638 pair[1].1
639 );
640 }
641 let mut out = [const { None }; N];
642 let (Some(&(lo, _)), Some(&(hi, _))) = (order.first(), order.last()) else {
643 return out;
644 };
645 let mut want = order.iter().peekable();
648 for (number, page) in self
649 .pages
650 .pages_in_mut(split::<PAGE>(lo).0..=split::<PAGE>(hi).0)
651 {
652 let mut rest: &mut [Slot<K, V>] = page;
653 let mut start = 0;
654 while let Some(&&(index, i)) = want.peek() {
655 let (wanted, offset) = split::<PAGE>(index);
656 if wanted > number {
657 break;
658 }
659 want.next();
660 if wanted < number {
661 continue;
664 }
665 let (_, tail) = mem::take(&mut rest).split_at_mut(offset - start);
666 let (slot, tail) = tail.split_first_mut().expect("offsets are inside the page");
667 if let Some((_, value)) = slot {
668 out[i] = Some(value);
669 }
670 rest = tail;
671 start = offset + 1;
672 }
673 }
674 out
675 }
676
677 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, PAGE, D> {
695 let index = key.index();
696 let stored = match self.slot(index) {
697 Some(Some((stored, _))) if *stored == key.tag() => *stored,
698 _ => return Entry::Vacant(VacantEntry { map: self, key }),
699 };
700 let (page, offset) = split::<PAGE>(index);
701 match self.pages.get_mut(page) {
702 Some(page) => Entry::Occupied(OccupiedEntry {
703 key: K::from_parts(index, stored),
704 slot: &mut page[offset],
705 len: &mut self.len,
706 }),
707 None => unreachable!("the slot was just found"),
708 }
709 }
710
711 pub fn into_keys(self) -> IntoKeys<K, V, PAGE, D> {
713 IntoKeys(self.into_iter())
714 }
715
716 pub fn into_values(self) -> IntoValues<K, V, PAGE, D> {
718 IntoValues(self.into_iter())
719 }
720}
721
722impl<K: DirectKey, V, const PAGE: usize, D: Directory> Default for PagedDirectMap<K, V, PAGE, D> {
723 fn default() -> Self {
724 Self::new()
725 }
726}
727
728impl<K: DirectKey, V: Clone, const PAGE: usize, D: Directory> Clone
729 for PagedDirectMap<K, V, PAGE, D>
730where
731 Store<K, V, PAGE, D>: Clone,
732{
733 fn clone(&self) -> Self {
734 Self {
735 pages: self.pages.clone(),
736 len: self.len,
737 }
738 }
739}
740
741impl<K: DirectKey + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
742 for PagedDirectMap<K, V, PAGE, D>
743{
744 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
745 f.debug_map().entries(self.iter()).finish()
746 }
747}
748
749impl<
752 K: DirectKey,
753 V: PartialEq<W>,
754 W,
755 const PAGE: usize,
756 D: Directory,
757 const P2: usize,
758 D2: Directory,
759> PartialEq<PagedDirectMap<K, W, P2, D2>> for PagedDirectMap<K, V, PAGE, D>
760{
761 fn eq(&self, other: &PagedDirectMap<K, W, P2, D2>) -> bool {
762 self.len == other.len
763 && self
764 .iter()
765 .zip(other.iter())
766 .all(|((key, value), (other_key, other_value))| {
767 key == other_key && value == other_value
768 })
769 }
770}
771
772impl<K: DirectKey, V: Eq, const PAGE: usize, D: Directory> Eq for PagedDirectMap<K, V, PAGE, D> {}
774
775impl<K: DirectKey + Hash, V: Hash, const PAGE: usize, D: Directory> Hash
778 for PagedDirectMap<K, V, PAGE, D>
779{
780 fn hash<H: Hasher>(&self, state: &mut H) {
781 state.write_usize(self.len);
782 for entry in self {
783 entry.hash(state);
784 }
785 }
786}
787
788impl<K: DirectKey, V, const PAGE: usize, D: Directory> Index<K> for PagedDirectMap<K, V, PAGE, D> {
794 type Output = V;
795
796 fn index(&self, key: K) -> &V {
797 self.get(key).expect("key not in PagedDirectMap")
798 }
799}
800
801impl<K: DirectKey, V, const PAGE: usize, D: Directory> Extend<(K, V)>
804 for PagedDirectMap<K, V, PAGE, D>
805{
806 fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
807 for (key, value) in iter {
808 self.insert(key, value);
809 }
810 }
811}
812
813impl<'a, K: DirectKey + 'a, V: Copy + 'a, const PAGE: usize, D: Directory> Extend<(&'a K, &'a V)>
814 for PagedDirectMap<K, V, PAGE, D>
815{
816 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
817 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
818 }
819}
820
821impl<K: DirectKey, V, const PAGE: usize, D: Directory> FromIterator<(K, V)>
822 for PagedDirectMap<K, V, PAGE, D>
823{
824 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
825 let mut map = Self::new();
826 map.extend(iter);
827 map
828 }
829}
830
831impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> IntoIterator
832 for &'a PagedDirectMap<K, V, PAGE, D>
833{
834 type Item = (K, &'a V);
835 type IntoIter = Iter<'a, K, V, PAGE, D>;
836
837 fn into_iter(self) -> Self::IntoIter {
838 self.iter()
839 }
840}
841
842impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> IntoIterator
843 for &'a mut PagedDirectMap<K, V, PAGE, D>
844{
845 type Item = (K, &'a mut V);
846 type IntoIter = IterMut<'a, K, V, PAGE, D>;
847
848 fn into_iter(self) -> Self::IntoIter {
849 self.iter_mut()
850 }
851}
852
853impl<K: DirectKey, V, const PAGE: usize, D: Directory> IntoIterator
854 for PagedDirectMap<K, V, PAGE, D>
855{
856 type Item = (K, V);
857 type IntoIter = IntoIter<K, V, PAGE, D>;
858
859 fn into_iter(self) -> Self::IntoIter {
860 IntoIter(Cursor::new(self.pages.into_pages(), self.len))
861 }
862}
863
864#[derive(Clone, Default)]
871struct Indexed<S> {
872 start: usize,
874 slots: S,
875}
876
877impl<S: ExactSizeIterator + DoubleEndedIterator> Iterator for Indexed<S> {
878 type Item = (usize, S::Item);
879
880 #[inline]
881 fn next(&mut self) -> Option<Self::Item> {
882 let slot = self.slots.next()?;
883 let index = self.start;
884 self.start = index.wrapping_add(1);
886 Some((index, slot))
887 }
888}
889
890impl<S: ExactSizeIterator + DoubleEndedIterator> DoubleEndedIterator for Indexed<S> {
891 #[inline]
892 fn next_back(&mut self) -> Option<Self::Item> {
893 let slot = self.slots.next_back()?;
894 Some((self.start.wrapping_add(self.slots.len()), slot))
895 }
896}
897
898trait PageSlots {
901 type Slots: DoubleEndedIterator + Default;
902 fn slots(self) -> Self::Slots;
903}
904
905#[inline]
908fn page_start<const PAGE: usize>(number: usize) -> usize {
909 number.wrapping_mul(PAGE)
910}
911
912impl<'a, T> PageSlots for (usize, &'a [T]) {
914 type Slots = Indexed<slice::Iter<'a, T>>;
915 fn slots(self) -> Self::Slots {
916 Indexed {
917 start: self.0,
918 slots: self.1.iter(),
919 }
920 }
921}
922
923impl<'a, T> PageSlots for (usize, &'a mut [T]) {
924 type Slots = Indexed<slice::IterMut<'a, T>>;
925 fn slots(self) -> Self::Slots {
926 Indexed {
927 start: self.0,
928 slots: self.1.iter_mut(),
929 }
930 }
931}
932
933impl<'a, T, const PAGE: usize> PageSlots for (usize, &'a [T; PAGE]) {
935 type Slots = Indexed<slice::Iter<'a, T>>;
936 fn slots(self) -> Self::Slots {
937 Indexed {
938 start: page_start::<PAGE>(self.0),
939 slots: self.1.iter(),
940 }
941 }
942}
943
944impl<'a, T, const PAGE: usize> PageSlots for (usize, &'a mut [T; PAGE]) {
945 type Slots = Indexed<slice::IterMut<'a, T>>;
946 fn slots(self) -> Self::Slots {
947 Indexed {
948 start: page_start::<PAGE>(self.0),
949 slots: self.1.iter_mut(),
950 }
951 }
952}
953
954impl<T, const PAGE: usize> PageSlots for (usize, Box<[T; PAGE]>) {
955 type Slots = Indexed<vec::IntoIter<T>>;
956 fn slots(self) -> Self::Slots {
957 let page: Box<[T]> = self.1;
958 Indexed {
959 start: page_start::<PAGE>(self.0),
960 slots: Vec::from(page).into_iter(),
961 }
962 }
963}
964
965trait SlotEntry<K> {
968 type Entry;
969 fn entry(self, index: usize) -> Option<Self::Entry>;
970}
971
972impl<'a, K: DirectKey, V: 'a> SlotEntry<K> for &'a Option<(K::Tag, V)> {
973 type Entry = (K, &'a V);
974 #[inline]
975 fn entry(self, index: usize) -> Option<Self::Entry> {
976 let (tag, value) = self.as_ref()?;
977 Some((K::from_parts(index, *tag), value))
978 }
979}
980
981impl<'a, K: DirectKey, V: 'a> SlotEntry<K> for &'a mut Option<(K::Tag, V)> {
982 type Entry = (K, &'a mut V);
983 #[inline]
984 fn entry(self, index: usize) -> Option<Self::Entry> {
985 let (tag, value) = self.as_mut()?;
986 Some((K::from_parts(index, *tag), value))
987 }
988}
989
990impl<K: DirectKey, V> SlotEntry<K> for Option<(K::Tag, V)> {
991 type Entry = (K, V);
992 #[inline]
993 fn entry(self, index: usize) -> Option<Self::Entry> {
994 let (tag, value) = self?;
995 Some((K::from_parts(index, tag), value))
996 }
997}
998
999struct Cursor<K, P, S> {
1000 pages: Fuse<P>,
1001 front: S,
1002 back: S,
1003 remaining: usize,
1004 key: PhantomData<fn() -> K>,
1005}
1006
1007impl<K, P: Clone, S: Clone> Clone for Cursor<K, P, S> {
1008 fn clone(&self) -> Self {
1009 Self {
1010 pages: self.pages.clone(),
1011 front: self.front.clone(),
1012 back: self.back.clone(),
1013 remaining: self.remaining,
1014 key: PhantomData,
1015 }
1016 }
1017}
1018
1019impl<K, P, S, X> Cursor<K, P, S>
1020where
1021 P: DoubleEndedIterator,
1022 P::Item: PageSlots<Slots = S>,
1023 S: DoubleEndedIterator<Item = (usize, X)> + Default,
1024 X: SlotEntry<K>,
1025{
1026 #[inline]
1027 fn len(&self) -> usize {
1028 self.remaining
1029 }
1030
1031 fn new(pages: P, remaining: usize) -> Self {
1032 Self {
1033 pages: pages.fuse(),
1034 front: S::default(),
1035 back: S::default(),
1036 remaining,
1037 key: PhantomData,
1038 }
1039 }
1040
1041 fn next(&mut self) -> Option<X::Entry> {
1042 while self.remaining > 0 {
1043 let (index, slot) = match self.front.next() {
1044 Some(slot) => slot,
1045 None => match self.pages.next() {
1046 Some(page) => {
1047 self.front = page.slots();
1048 continue;
1049 }
1050 None => match self.back.next() {
1052 Some(slot) => slot,
1053 None => break,
1054 },
1055 },
1056 };
1057 if let Some(entry) = slot.entry(index) {
1058 self.remaining -= 1;
1059 return Some(entry);
1060 }
1061 }
1062 self.remaining = 0;
1065 None
1066 }
1067
1068 fn next_back(&mut self) -> Option<X::Entry> {
1069 while self.remaining > 0 {
1070 let (index, slot) = match self.back.next_back() {
1071 Some(slot) => slot,
1072 None => match self.pages.next_back() {
1073 Some(page) => {
1074 self.back = page.slots();
1075 continue;
1076 }
1077 None => match self.front.next_back() {
1078 Some(slot) => slot,
1079 None => break,
1080 },
1081 },
1082 };
1083 if let Some(entry) = slot.entry(index) {
1084 self.remaining -= 1;
1085 return Some(entry);
1086 }
1087 }
1088 self.remaining = 0;
1091 None
1092 }
1093}
1094
1095pub struct Drain<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1097 map: &'a mut PagedDirectMap<K, V, PAGE, D>,
1098 next: Option<usize>,
1100}
1101
1102impl<K: DirectKey, V, const PAGE: usize, D: Directory> Iterator for Drain<'_, K, V, PAGE, D> {
1103 type Item = (K, V);
1104
1105 fn next(&mut self) -> Option<(K, V)> {
1106 let start = self.next?;
1107 let Some((key, _)) = self.map.slot_range(start..).next() else {
1108 self.next = None;
1109 return None;
1110 };
1111 let index = key.index();
1112 self.next = index.checked_add(1);
1113 self.map.remove_occupant(index)
1114 }
1115
1116 fn size_hint(&self) -> (usize, Option<usize>) {
1117 (self.map.len, Some(self.map.len))
1119 }
1120}
1121
1122impl<K: DirectKey, V, const PAGE: usize, D: Directory> ExactSizeIterator
1123 for Drain<'_, K, V, PAGE, D>
1124{
1125}
1126
1127impl<K: DirectKey, V, const PAGE: usize, D: Directory> FusedIterator for Drain<'_, K, V, PAGE, D> {}
1128
1129impl<K: DirectKey, V, const PAGE: usize, D: Directory> Drop for Drain<'_, K, V, PAGE, D> {
1130 fn drop(&mut self) {
1131 self.for_each(drop);
1132 }
1133}
1134
1135impl<K: DirectKey + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1136 for Drain<'_, K, V, PAGE, D>
1137{
1138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139 f.debug_list().entries(self.map.iter()).finish()
1141 }
1142}
1143
1144pub struct ExtractIf<'a, K: DirectKey, V, F, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat>
1147{
1148 map: &'a mut PagedDirectMap<K, V, PAGE, D>,
1149 next: Option<usize>,
1150 pred: F,
1151}
1152
1153impl<K: DirectKey, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> Iterator
1154 for ExtractIf<'_, K, V, F, PAGE, D>
1155{
1156 type Item = (K, V);
1157
1158 fn next(&mut self) -> Option<(K, V)> {
1159 loop {
1160 let start = self.next?;
1161 let Some((key, value)) = self.map.slot_range_mut(start..).next() else {
1162 self.next = None;
1163 return None;
1164 };
1165 let index = key.index();
1166 self.next = index.checked_add(1);
1168 if (self.pred)(&key, value) {
1169 return self.map.remove_occupant(index);
1170 }
1171 }
1172 }
1173
1174 fn size_hint(&self) -> (usize, Option<usize>) {
1175 (0, Some(if self.next.is_some() { self.map.len } else { 0 }))
1176 }
1177}
1178
1179impl<K: DirectKey, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> FusedIterator
1180 for ExtractIf<'_, K, V, F, PAGE, D>
1181{
1182}
1183
1184impl<K: DirectKey + fmt::Debug, V: fmt::Debug, F, const PAGE: usize, D: Directory> fmt::Debug
1185 for ExtractIf<'_, K, V, F, PAGE, D>
1186{
1187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1188 f.debug_struct("ExtractIf")
1189 .field("next", &self.next)
1190 .finish_non_exhaustive()
1191 }
1192}
1193
1194fn index_bounds<K: Key>(keys: &impl RangeBounds<K>) -> (Bound<usize>, Bound<usize>) {
1196 (
1197 keys.start_bound().map(|key| key.index()),
1198 keys.end_bound().map(|key| key.index()),
1199 )
1200}
1201
1202struct Span {
1206 first: usize,
1207 last: usize,
1208 pages: core::ops::RangeInclusive<usize>,
1209 most: usize,
1210}
1211
1212impl Span {
1213 fn new<const PAGE: usize>(indices: &impl RangeBounds<usize>, len: usize) -> Self {
1215 let first = match indices.start_bound() {
1216 Bound::Included(&index) => Some(index),
1217 Bound::Excluded(&index) => index.checked_add(1),
1218 Bound::Unbounded => Some(0),
1219 };
1220 let last = match indices.end_bound() {
1221 Bound::Included(&index) => Some(index),
1222 Bound::Excluded(&index) => index.checked_sub(1),
1223 Bound::Unbounded => Some(usize::MAX),
1224 };
1225 match (first, last) {
1226 (Some(first), Some(last)) if first <= last => Self {
1227 first,
1228 last,
1229 pages: split::<PAGE>(first).0..=split::<PAGE>(last).0,
1230 most: (last - first).saturating_add(1).min(len),
1231 },
1232 #[allow(clippy::reversed_empty_ranges)]
1233 _ => Self {
1234 first: 1,
1235 last: 0,
1236 pages: 1..=0,
1237 most: 0,
1238 },
1239 }
1240 }
1241}
1242
1243trait Cut<const PAGE: usize> {
1246 type Part;
1247 fn cut(self, first: usize, last: usize) -> Self::Part;
1248}
1249
1250fn offsets<const PAGE: usize>(number: usize, first: usize, last: usize) -> core::ops::Range<usize> {
1252 let base = number.saturating_mul(PAGE);
1253 let end = match last.checked_sub(base) {
1254 Some(offset) => offset.saturating_add(1).min(PAGE),
1255 None => 0,
1258 };
1259 first.saturating_sub(base).min(end)..end
1260}
1261
1262impl<'a, T, const PAGE: usize> Cut<PAGE> for (usize, &'a [T; PAGE]) {
1263 type Part = (usize, &'a [T]);
1264 fn cut(self, first: usize, last: usize) -> Self::Part {
1265 let offsets = offsets::<PAGE>(self.0, first, last);
1266 let start = page_start::<PAGE>(self.0).wrapping_add(offsets.start);
1267 (start, &self.1[offsets])
1268 }
1269}
1270
1271impl<'a, T, const PAGE: usize> Cut<PAGE> for (usize, &'a mut [T; PAGE]) {
1272 type Part = (usize, &'a mut [T]);
1273 fn cut(self, first: usize, last: usize) -> Self::Part {
1274 let offsets = offsets::<PAGE>(self.0, first, last);
1275 let start = page_start::<PAGE>(self.0).wrapping_add(offsets.start);
1276 (start, &mut self.1[offsets])
1277 }
1278}
1279
1280#[derive(Clone)]
1282struct Trim<P, const PAGE: usize> {
1283 pages: P,
1284 first: usize,
1285 last: usize,
1286}
1287
1288impl<P: Iterator, const PAGE: usize> Iterator for Trim<P, PAGE>
1289where
1290 P::Item: Cut<PAGE>,
1291{
1292 type Item = <P::Item as Cut<PAGE>>::Part;
1293
1294 fn next(&mut self) -> Option<Self::Item> {
1295 let page = self.pages.next()?;
1296 Some(page.cut(self.first, self.last))
1297 }
1298}
1299
1300impl<P: DoubleEndedIterator, const PAGE: usize> DoubleEndedIterator for Trim<P, PAGE>
1301where
1302 P::Item: Cut<PAGE>,
1303{
1304 fn next_back(&mut self) -> Option<Self::Item> {
1305 let page = self.pages.next_back()?;
1306 Some(page.cut(self.first, self.last))
1307 }
1308}
1309
1310macro_rules! range_iterator {
1311 (
1312 $(#[$doc:meta])*
1313 $name:ident, $pages:ident, $slots:ident, $item:ty
1314 ) => {
1315 $(#[$doc])*
1316 pub struct $name<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat>(
1317 Cursor<K, Trim<$pages<'a, K, V, PAGE, D>, PAGE>, Indexed<slice::$slots<'a, Slot<K, V>>>>,
1318 )
1319 where
1320 K: 'a,
1321 V: 'a,
1322 D: 'a;
1323
1324 impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> Iterator for $name<'a, K, V, PAGE, D> {
1325 type Item = $item;
1326
1327 #[inline]
1328 fn next(&mut self) -> Option<Self::Item> {
1329 self.0.next()
1330 }
1331
1332 #[inline]
1336 fn size_hint(&self) -> (usize, Option<usize>) {
1337 (0, Some(self.0.remaining))
1338 }
1339 }
1340
1341 impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> DoubleEndedIterator
1342 for $name<'a, K, V, PAGE, D>
1343 {
1344 #[inline]
1345 fn next_back(&mut self) -> Option<Self::Item> {
1346 self.0.next_back()
1347 }
1348 }
1349
1350 impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> FusedIterator
1351 for $name<'a, K, V, PAGE, D>
1352 {
1353 }
1354
1355 impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> fmt::Debug for $name<'a, K, V, PAGE, D> {
1356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1357 f.debug_struct(stringify!($name)).finish_non_exhaustive()
1358 }
1359 }
1360 };
1361}
1362
1363range_iterator!(
1364 Range,
1368 Pages,
1369 Iter,
1370 (K, &'a V)
1371);
1372
1373range_iterator!(
1374 RangeMut,
1379 PagesMut,
1380 IterMut,
1381 (K, &'a mut V)
1382);
1383
1384impl<K: DirectKey, V, const PAGE: usize, D: Directory> Clone for Range<'_, K, V, PAGE, D> {
1385 fn clone(&self) -> Self {
1386 Self(self.0.clone())
1387 }
1388}
1389
1390macro_rules! entry_iterator {
1391 (
1392 $(#[$doc:meta])*
1393 $name:ident<$($lt:lifetime,)? K, V, PAGE, D>,
1394 $inner:ty,
1395 $item:ty,
1396 |$entry:pat_param| $map:expr
1397 ) => {
1398 $(#[$doc])*
1399 pub struct $name<$($lt,)? K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat>($inner)
1400 where
1401 $(K: $lt, V: $lt, D: $lt)?;
1402
1403 impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> Iterator for $name<$($lt,)? K, V, PAGE, D>
1404 where
1405 $(K: $lt, V: $lt, D: $lt)?
1406 {
1407 type Item = $item;
1408
1409 #[inline]
1410 fn next(&mut self) -> Option<Self::Item> {
1411 self.0.next().map(|$entry| $map)
1412 }
1413
1414 #[inline]
1415 fn size_hint(&self) -> (usize, Option<usize>) {
1416 let len = self.len();
1417 (len, Some(len))
1418 }
1419 }
1420
1421 impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> DoubleEndedIterator
1422 for $name<$($lt,)? K, V, PAGE, D>
1423 where
1424 $(K: $lt, V: $lt, D: $lt)?
1425 {
1426 #[inline]
1427 fn next_back(&mut self) -> Option<Self::Item> {
1428 self.0.next_back().map(|$entry| $map)
1429 }
1430 }
1431
1432 impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> ExactSizeIterator
1433 for $name<$($lt,)? K, V, PAGE, D>
1434 where
1435 $(K: $lt, V: $lt, D: $lt)?
1436 {
1437 #[inline]
1438 fn len(&self) -> usize {
1439 self.0.len()
1440 }
1441 }
1442
1443 impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> FusedIterator
1444 for $name<$($lt,)? K, V, PAGE, D>
1445 where
1446 $(K: $lt, V: $lt, D: $lt)?
1447 {
1448 }
1449
1450 impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> fmt::Debug
1451 for $name<$($lt,)? K, V, PAGE, D>
1452 where
1453 $(K: $lt, V: $lt, D: $lt)?
1454 {
1455 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1456 f.debug_struct(stringify!($name))
1457 .field("remaining", &self.len())
1458 .finish_non_exhaustive()
1459 }
1460 }
1461 };
1462}
1463
1464entry_iterator!(
1465 Iter<'a, K, V, PAGE, D>,
1468 Cursor<K, Pages<'a, K, V, PAGE, D>, Indexed<slice::Iter<'a, Slot<K, V>>>>,
1469 (K, &'a V),
1470 |entry| entry
1471);
1472
1473entry_iterator!(
1474 IterMut<'a, K, V, PAGE, D>,
1477 Cursor<K, PagesMut<'a, K, V, PAGE, D>, Indexed<slice::IterMut<'a, Slot<K, V>>>>,
1478 (K, &'a mut V),
1479 |entry| entry
1480);
1481
1482entry_iterator!(
1483 IntoIter<K, V, PAGE, D>,
1486 Cursor<K, IntoPages<K, V, PAGE, D>, Indexed<vec::IntoIter<Slot<K, V>>>>,
1487 (K, V),
1488 |entry| entry
1489);
1490
1491entry_iterator!(
1492 Keys<'a, K, V, PAGE, D>,
1495 Iter<'a, K, V, PAGE, D>,
1496 K,
1497 |(key, _)| key
1498);
1499
1500entry_iterator!(
1501 Values<'a, K, V, PAGE, D>,
1504 Iter<'a, K, V, PAGE, D>,
1505 &'a V,
1506 |(_, value)| value
1507);
1508
1509entry_iterator!(
1510 ValuesMut<'a, K, V, PAGE, D>,
1513 IterMut<'a, K, V, PAGE, D>,
1514 &'a mut V,
1515 |(_, value)| value
1516);
1517
1518entry_iterator!(
1519 IntoKeys<K, V, PAGE, D>,
1522 IntoIter<K, V, PAGE, D>,
1523 K,
1524 |(key, _)| key
1525);
1526
1527entry_iterator!(
1528 IntoValues<K, V, PAGE, D>,
1531 IntoIter<K, V, PAGE, D>,
1532 V,
1533 |(_, value)| value
1534);
1535
1536impl<K: DirectKey, V, const PAGE: usize, D: Directory> Clone for Iter<'_, K, V, PAGE, D> {
1537 fn clone(&self) -> Self {
1538 Self(self.0.clone())
1539 }
1540}
1541
1542impl<K: DirectKey, V, const PAGE: usize, D: Directory> Clone for Keys<'_, K, V, PAGE, D> {
1543 fn clone(&self) -> Self {
1544 Self(self.0.clone())
1545 }
1546}
1547
1548impl<K: DirectKey, V, const PAGE: usize, D: Directory> Clone for Values<'_, K, V, PAGE, D> {
1549 fn clone(&self) -> Self {
1550 Self(self.0.clone())
1551 }
1552}
1553
1554#[cfg(feature = "rayon")]
1555pub use rayon_impl::{ParIter, ParIterMut};
1556
1557#[cfg(feature = "rayon")]
1558mod rayon_impl {
1559 use super::*;
1560 use rayon::iter::plumbing::UnindexedConsumer;
1561 use rayon::prelude::*;
1562
1563 pub struct ParIter<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE>(
1565 Vec<(usize, &'a [Slot<K, V>; PAGE])>,
1566 );
1567
1568 pub struct ParIterMut<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE>(
1570 Vec<(usize, &'a mut [Slot<K, V>; PAGE])>,
1571 );
1572
1573 impl<'a, K: DirectKey + Send, V: Sync, const PAGE: usize, D: Directory> IntoParallelIterator
1574 for &'a PagedDirectMap<K, V, PAGE, D>
1575 where
1576 K::Tag: Sync,
1577 Store<K, V, PAGE, D>: Sync,
1578 {
1579 type Item = (K, &'a V);
1580 type Iter = ParIter<'a, K, V, PAGE>;
1581
1582 fn into_par_iter(self) -> Self::Iter {
1583 ParIter(self.pages.pages().collect())
1584 }
1585 }
1586
1587 impl<'a, K: DirectKey + Send, V: Send, const PAGE: usize, D: Directory> IntoParallelIterator
1588 for &'a mut PagedDirectMap<K, V, PAGE, D>
1589 where
1590 K::Tag: Send,
1591 {
1592 type Item = (K, &'a mut V);
1593 type Iter = ParIterMut<'a, K, V, PAGE>;
1594
1595 fn into_par_iter(self) -> Self::Iter {
1596 ParIterMut(self.pages.pages_mut().collect())
1597 }
1598 }
1599
1600 impl<'a, K: DirectKey + Send, V: Sync, const PAGE: usize> ParallelIterator
1601 for ParIter<'a, K, V, PAGE>
1602 where
1603 K::Tag: Sync,
1604 {
1605 type Item = (K, &'a V);
1606
1607 fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
1608 self.0
1609 .into_par_iter()
1610 .flat_map_iter(|page| {
1611 page.slots()
1612 .filter_map(|(index, slot)| SlotEntry::<K>::entry(slot, index))
1613 })
1614 .drive_unindexed(consumer)
1615 }
1616 }
1617
1618 impl<'a, K: DirectKey + Send, V: Send, const PAGE: usize> ParallelIterator
1619 for ParIterMut<'a, K, V, PAGE>
1620 where
1621 K::Tag: Send,
1622 {
1623 type Item = (K, &'a mut V);
1624
1625 fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
1626 self.0
1627 .into_par_iter()
1628 .flat_map_iter(|page| {
1629 page.slots()
1630 .filter_map(|(index, slot)| SlotEntry::<K>::entry(slot, index))
1631 })
1632 .drive_unindexed(consumer)
1633 }
1634 }
1635}
1636
1637#[cfg(feature = "serde")]
1638mod serde_impl {
1639 use super::*;
1640 use core::marker::PhantomData;
1641 use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
1642 use serde::ser::{Serialize, Serializer};
1643
1644 impl<K: DirectKey + Serialize, V: Serialize, const PAGE: usize, D: Directory> Serialize
1646 for PagedDirectMap<K, V, PAGE, D>
1647 {
1648 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1649 serializer.collect_map(self.iter())
1650 }
1651 }
1652
1653 impl<'de, K, V, const PAGE: usize, D> Deserialize<'de> for PagedDirectMap<K, V, PAGE, D>
1662 where
1663 K: DirectKey + Deserialize<'de>,
1664 V: Deserialize<'de>,
1665 D: Directory,
1666 {
1667 fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1668 struct MapVisitor<K, V, const PAGE: usize, D>(PhantomData<(K, V, D)>);
1669
1670 impl<'de, K, V, const PAGE: usize, D> Visitor<'de> for MapVisitor<K, V, PAGE, D>
1671 where
1672 K: DirectKey + Deserialize<'de>,
1673 V: Deserialize<'de>,
1674 D: Directory,
1675 {
1676 type Value = PagedDirectMap<K, V, PAGE, D>;
1677
1678 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1679 f.write_str("a map of keys to values")
1680 }
1681
1682 fn visit_map<A: MapAccess<'de>>(
1683 self,
1684 mut access: A,
1685 ) -> Result<Self::Value, A::Error> {
1686 let mut map = PagedDirectMap::new();
1687 while let Some((key, value)) = access.next_entry()? {
1688 map.insert(key, value);
1689 }
1690 Ok(map)
1691 }
1692 }
1693
1694 deserializer.deserialize_map(MapVisitor::<K, V, PAGE, D>(PhantomData))
1695 }
1696 }
1697}
1698
1699pub enum Entry<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1702 Occupied(OccupiedEntry<'a, K, V>),
1704 Vacant(VacantEntry<'a, K, V, PAGE, D>),
1707}
1708
1709pub struct OccupiedEntry<'a, K: DirectKey, V> {
1711 key: K,
1714 slot: &'a mut Slot<K, V>,
1715 len: &'a mut usize,
1716}
1717
1718pub struct VacantEntry<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1720 map: &'a mut PagedDirectMap<K, V, PAGE, D>,
1721 key: K,
1722}
1723
1724impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> Entry<'a, K, V, PAGE, D> {
1725 #[inline]
1728 pub fn key(&self) -> &K {
1729 match self {
1730 Entry::Occupied(entry) => entry.key(),
1731 Entry::Vacant(entry) => entry.key(),
1732 }
1733 }
1734
1735 #[inline]
1738 pub fn or_insert(self, default: V) -> &'a mut V {
1739 match self {
1740 Entry::Occupied(entry) => entry.into_mut(),
1741 Entry::Vacant(entry) => entry.insert(default),
1742 }
1743 }
1744
1745 #[inline]
1748 pub fn or_insert_with(self, make: impl FnOnce() -> V) -> &'a mut V {
1749 match self {
1750 Entry::Occupied(entry) => entry.into_mut(),
1751 Entry::Vacant(entry) => entry.insert(make()),
1752 }
1753 }
1754
1755 #[inline]
1758 pub fn or_insert_with_key(self, make: impl FnOnce(&K) -> V) -> &'a mut V {
1759 match self {
1760 Entry::Occupied(entry) => entry.into_mut(),
1761 Entry::Vacant(entry) => {
1762 let value = make(&entry.key);
1763 entry.insert(value)
1764 }
1765 }
1766 }
1767
1768 #[inline]
1770 pub fn or_default(self) -> &'a mut V
1771 where
1772 V: Default,
1773 {
1774 self.or_insert_with(V::default)
1775 }
1776
1777 #[inline]
1779 pub fn and_modify(mut self, f: impl FnOnce(&mut V)) -> Self {
1780 if let Entry::Occupied(entry) = &mut self {
1781 f(entry.get_mut());
1782 }
1783 self
1784 }
1785
1786 #[inline]
1789 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
1790 match self {
1791 Entry::Occupied(mut entry) => {
1792 entry.insert(value);
1793 entry
1794 }
1795 Entry::Vacant(entry) => entry.insert_entry(value),
1796 }
1797 }
1798}
1799
1800impl<'a, K: DirectKey, V> OccupiedEntry<'a, K, V> {
1801 #[inline]
1802 fn pair(&self) -> &(K::Tag, V) {
1803 match &*self.slot {
1804 Some(pair) => pair,
1805 None => unreachable!("an occupied entry's slot is full"),
1806 }
1807 }
1808
1809 #[inline]
1810 fn pair_mut(&mut self) -> &mut (K::Tag, V) {
1811 match &mut *self.slot {
1812 Some(pair) => pair,
1813 None => unreachable!("an occupied entry's slot is full"),
1814 }
1815 }
1816
1817 #[inline]
1819 pub fn key(&self) -> &K {
1820 &self.key
1821 }
1822
1823 #[inline]
1825 pub fn get(&self) -> &V {
1826 &self.pair().1
1827 }
1828
1829 #[inline]
1831 pub fn get_mut(&mut self) -> &mut V {
1832 &mut self.pair_mut().1
1833 }
1834
1835 #[inline]
1837 pub fn into_mut(self) -> &'a mut V {
1838 match self.slot {
1839 Some((_, value)) => value,
1840 None => unreachable!("an occupied entry's slot is full"),
1841 }
1842 }
1843
1844 #[inline]
1846 pub fn insert(&mut self, value: V) -> V {
1847 mem::replace(self.get_mut(), value)
1848 }
1849
1850 #[inline]
1852 pub fn remove(self) -> V {
1853 self.remove_entry().1
1854 }
1855
1856 pub fn remove_entry(self) -> (K, V) {
1858 match self.slot.take() {
1859 Some((_, value)) => {
1860 *self.len -= 1;
1861 (self.key, value)
1862 }
1863 None => unreachable!("an occupied entry's slot is full"),
1864 }
1865 }
1866}
1867
1868impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> VacantEntry<'a, K, V, PAGE, D> {
1869 #[inline]
1871 pub fn key(&self) -> &K {
1872 &self.key
1873 }
1874
1875 #[inline]
1877 pub fn into_key(self) -> K {
1878 self.key
1879 }
1880
1881 #[inline]
1884 pub fn occupant(&self) -> Option<(K, &V)> {
1885 self.map.occupant(self.key.index())
1886 }
1887
1888 #[inline]
1896 pub fn insert(self, value: V) -> &'a mut V {
1897 self.insert_entry(value).into_mut()
1898 }
1899
1900 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
1902 let VacantEntry { map, key } = self;
1903 let (slot, len) = map.slot_or_alloc(key.index());
1904 if slot.is_none() {
1905 *len += 1;
1906 }
1907 drop(slot.replace((key.tag(), value)));
1910 OccupiedEntry { key, slot, len }
1911 }
1912}
1913
1914impl<K: DirectKey + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1915 for Entry<'_, K, V, PAGE, D>
1916{
1917 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1918 match self {
1919 Entry::Occupied(entry) => f.debug_tuple("Occupied").field(entry).finish(),
1920 Entry::Vacant(entry) => f.debug_tuple("Vacant").field(entry).finish(),
1921 }
1922 }
1923}
1924
1925impl<K: DirectKey + fmt::Debug, V: fmt::Debug> fmt::Debug for OccupiedEntry<'_, K, V> {
1926 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1927 f.debug_struct("OccupiedEntry")
1928 .field("key", self.key())
1929 .field("value", self.get())
1930 .finish()
1931 }
1932}
1933
1934impl<K: DirectKey + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1935 for VacantEntry<'_, K, V, PAGE, D>
1936{
1937 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1938 f.debug_struct("VacantEntry")
1939 .field("key", &self.key)
1940 .field("occupant", &self.occupant())
1941 .finish()
1942 }
1943}
1944
1945#[cfg(all(test, any(target_pointer_width = "32", target_pointer_width = "64")))]
1948mod tests {
1949 use super::*;
1950 use crate::page::Tree;
1951 use alloc::vec;
1952
1953 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
1954 struct Gen(u32);
1955
1956 impl Key for Gen {
1957 fn index(self) -> usize {
1958 (self.0 & 0xffff) as usize
1959 }
1960 }
1961
1962 impl DirectKey for Gen {
1963 type Tag = u16;
1964 fn tag(self) -> u16 {
1965 (self.0 >> 16) as u16
1966 }
1967 fn from_parts(index: usize, tag: u16) -> Self {
1968 Gen(index as u32 | u32::from(tag) << 16)
1969 }
1970 }
1971
1972 fn entries<K: DirectKey, V: Clone, const PAGE: usize, D: Directory>(
1973 map: &PagedDirectMap<K, V, PAGE, D>,
1974 ) -> Vec<(K, V)> {
1975 map.iter().map(|(k, v)| (k, v.clone())).collect()
1976 }
1977
1978 #[test]
1979 fn iterates_in_key_order_from_both_ends() {
1980 let map: PagedDirectMap<u32, u32, 4> =
1981 [(9, 90), (1, 10), (40, 400), (2, 20)].into_iter().collect();
1982 assert_eq!(map.len(), 4);
1983 assert_eq!(map.allocated_pages(), 3);
1984 assert_eq!(entries(&map), [(1, 10), (2, 20), (9, 90), (40, 400)]);
1985 let back: Vec<u32> = map.keys().rev().collect();
1986 assert_eq!(back, [40, 9, 2, 1]);
1987
1988 let mut it = map.iter();
1990 assert_eq!(it.len(), 4);
1991 assert_eq!(it.next(), Some((1, &10)));
1992 assert_eq!(it.next_back(), Some((40, &400)));
1993 assert_eq!(it.next_back(), Some((9, &90)));
1994 assert_eq!(it.next(), Some((2, &20)));
1995 assert_eq!(it.next(), None);
1996 assert_eq!(it.next_back(), None);
1997
1998 let owned: Vec<(u32, u32)> = map.clone().into_iter().rev().collect();
1999 assert_eq!(owned, [(40, 400), (9, 90), (2, 20), (1, 10)]);
2000 let values: Vec<u32> = map.into_values().collect();
2001 assert_eq!(values, [10, 20, 90, 400]);
2002 }
2003
2004 #[test]
2005 fn same_order_with_tree_directory() {
2006 let keys = [u32::MAX - 1, 5, 1 << 31, 6];
2007 let map: PagedDirectMap<u32, (), 1024, Tree> = keys.iter().map(|&k| (k, ())).collect();
2008 let got: Vec<u32> = map.keys().collect();
2009 assert_eq!(got, [5, 6, 1 << 31, u32::MAX - 1]);
2010 assert_eq!(map.allocated_pages(), 3);
2011 }
2012
2013 #[test]
2014 fn generations_compete_for_one_slot() {
2015 let mut map: PagedDirectMap<Gen, &str> = PagedDirectMap::new();
2016 let old = Gen(3);
2017 let new = Gen(3 | 1 << 16);
2018 assert_eq!(map.insert(old, "old"), None);
2019 assert_eq!(map.try_insert(new, "x"), Err("x"));
2020 assert_eq!(map.get(new), None);
2021 assert_eq!(map.occupant(3), Some((old, &"old")));
2022 assert_eq!(map.insert(new, "new"), Some("old"));
2024 assert_eq!(map.get(old), None);
2025 assert_eq!(map.get(new), Some(&"new"));
2026 assert_eq!(map.len(), 1);
2027 assert_eq!(map.replace(old, "back"), Some((new, "new")));
2029 assert_eq!(map.remove(new), None);
2030 assert_eq!(map.remove_occupant(3), Some((old, "back")));
2031 assert!(map.is_empty());
2032 }
2033
2034 #[test]
2035 fn entry_occupied_and_vacant() {
2036 let mut map: PagedDirectMap<u32, i32> = PagedDirectMap::new();
2037 assert!(matches!(map.entry(9), Entry::Vacant(_)));
2038 assert_eq!(map.allocated_pages(), 0, "a vacant entry allocates nothing");
2039 *map.entry(9).or_insert(1) += 10;
2040 map.entry(9).and_modify(|v| *v *= 2).or_insert(-1);
2041 assert_eq!(map.get(9), Some(&22));
2042 assert_eq!(*map.entry(70_000).or_default(), 0);
2043 assert_eq!(*map.entry(5).or_insert_with_key(|&k| k as i32), 5);
2044 assert_eq!(map.len(), 3);
2045 match map.entry(9) {
2046 Entry::Occupied(mut e) => {
2047 assert_eq!((e.key(), e.get()), (&9, &22));
2048 assert_eq!(e.insert(4), 22);
2049 assert_eq!(e.remove_entry(), (9, 4));
2050 }
2051 Entry::Vacant(_) => panic!("9 is present"),
2052 }
2053 assert_eq!(map.len(), 2);
2054 assert_eq!(map.get(9), None);
2055 let e = map.entry(9).insert_entry(8);
2056 assert_eq!(e.remove(), 8);
2057 assert_eq!(entries(&map), [(5, 5), (70_000, 0)]);
2058 }
2059
2060 #[test]
2061 fn entry_treats_another_generation_as_vacant_and_evicts_it() {
2062 let mut map: PagedDirectMap<Gen, &str, 4, Tree> = PagedDirectMap::new();
2063 let (old, new) = (Gen(3), Gen(3 | 1 << 16));
2064 map.insert(old, "old");
2065 match map.entry(new) {
2066 Entry::Vacant(e) => {
2067 assert_eq!(e.occupant(), Some((old, &"old")));
2068 assert_eq!(*e.insert("new"), "new");
2069 }
2070 Entry::Occupied(_) => panic!("only `old` is present"),
2071 }
2072 assert_eq!(map.len(), 1);
2073 assert_eq!(entries(&map), [(new, "new")]);
2074 assert_eq!(*map.entry(new).or_insert("x"), "new");
2076 }
2077
2078 #[cfg(feature = "std")]
2079 #[test]
2080 fn entry_or_insert_with_panic_leaves_map_unchanged() {
2081 let mut map: PagedDirectMap<u32, i32> = PagedDirectMap::new();
2082 let result = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
2083 map.entry(3).or_insert_with(|| panic!("make"));
2084 }));
2085 assert!(result.is_err());
2086 assert!(map.is_empty());
2087 assert_eq!(map.allocated_pages(), 0);
2088 }
2089
2090 #[test]
2091 fn get_or_insert_with_runs_make_only_when_absent() {
2092 let mut map: PagedDirectMap<u32, i32> = PagedDirectMap::new();
2093 *map.get_or_insert_with(4, || 1) += 10;
2094 *map.get_or_insert_with(4, || panic!("present")) += 100;
2095 assert_eq!(map[4], 111);
2096 assert_eq!(map.len(), 1);
2097 }
2098
2099 #[test]
2100 fn retain_clear_shrink_and_reset() {
2101 let mut map: PagedDirectMap<u32, u32, 4> = (0..12).map(|k| (k, k)).collect();
2102 map.retain(|&k, v| {
2103 *v *= 2;
2104 !(4..8).contains(&k)
2105 });
2106 assert_eq!(map.len(), 8);
2107 assert_eq!(map.get(9), Some(&18));
2108 assert_eq!(map.allocated_pages(), 3);
2109 map.shrink_to_fit();
2110 assert_eq!(map.allocated_pages(), 2);
2111 assert_eq!(map.get(9), Some(&18));
2112
2113 map.clear();
2114 assert!(map.is_empty());
2115 assert_eq!(map.iter().next(), None);
2116 assert_eq!(map.allocated_pages(), 2);
2117 map.reset();
2118 assert_eq!(map.allocated_pages(), 0);
2119 }
2120
2121 fn ordered_queries<D: Directory>() {
2122 let keys = [1_u32, 2, 9, 40, 41, 43];
2123 let mut map: PagedDirectMap<u32, u32, 4, D> = keys.iter().map(|&k| (k, k * 10)).collect();
2124 map.insert(20, 0);
2126 map.remove(20);
2127 let range = |r: (Bound<u32>, Bound<u32>)| -> Vec<u32> {
2128 let got: Vec<u32> = map.range(r).map(|(k, _)| k).collect();
2129 let mut back: Vec<u32> = map.range(r).rev().map(|(k, _)| k).collect();
2130 back.reverse();
2131 assert_eq!(got, back);
2132 got
2133 };
2134 use Bound::{Excluded as Ex, Included as In, Unbounded as Un};
2135 assert_eq!(range((Un, Un)), keys);
2136 assert_eq!(range((In(2), Ex(41))), [2, 9, 40]);
2137 assert_eq!(range((Ex(2), In(41))), [9, 40, 41]);
2138 assert_eq!(range((In(3), In(8))), [0_u32; 0]);
2139 assert_eq!(range((In(9), In(9))), [9]);
2140 assert_eq!(range((In(42), Un)), [43]);
2141 assert_eq!(range((In(44), Un)), [0_u32; 0]);
2142 assert_eq!(range((In(41), In(2))), [0_u32; 0]);
2143 assert_eq!(range((Ex(u32::MAX), Un)), [0_u32; 0]);
2144 assert_eq!(range((Un, Ex(0))), [0_u32; 0]);
2145 assert_eq!(map.slot_range(..).count(), keys.len());
2146 assert_eq!(map.slot_range((Ex(usize::MAX), Un)).next(), None);
2147 assert_eq!(map.slot_range(usize::MAX..).next(), None);
2148
2149 {
2151 let mut it = map.range(40..=43);
2152 assert_eq!(it.size_hint(), (0, Some(4)));
2153 assert_eq!(it.next(), Some((40, &400)));
2154 assert_eq!(it.next_back(), Some((43, &430)));
2155 assert_eq!(it.clone().next_back(), Some((41, &410)));
2156 assert_eq!(it.next(), Some((41, &410)));
2157 assert_eq!(it.next(), None);
2158 assert_eq!(it.next_back(), None);
2159 }
2160
2161 assert_eq!(map.next_occupant(0), Some((1, &10)));
2162 assert_eq!(map.next_occupant(9), Some((9, &90)));
2163 assert_eq!(map.next_occupant(10), Some((40, &400)));
2164 assert_eq!(map.next_occupant(44), None);
2165 assert_eq!(map.prev_occupant(0), None);
2166 assert_eq!(map.prev_occupant(39), Some((9, &90)));
2167 assert_eq!(map.prev_occupant(usize::MAX), Some((43, &430)));
2168 assert_eq!(map.first_key_value(), Some((1, &10)));
2169 assert_eq!(map.last_key_value(), Some((43, &430)));
2170
2171 for (_, value) in map.range_mut(2..41) {
2172 *value += 1;
2173 }
2174 assert_eq!(
2175 entries(&map),
2176 [(1, 10), (2, 21), (9, 91), (40, 401), (41, 410), (43, 430)]
2177 );
2178 assert_eq!(map.slot_range_mut(40..).next_back(), Some((43, &mut 430)));
2179
2180 assert_eq!(map.pop_first(), Some((1, 10)));
2181 assert_eq!(map.pop_last(), Some((43, 430)));
2182 assert_eq!(map.len(), 4);
2183 assert_eq!(map.first_key_value(), Some((2, &21)));
2184 map.clear();
2185 assert_eq!(map.pop_first(), None);
2186 assert_eq!(map.pop_last(), None);
2187 assert_eq!(map.next_occupant(0), None);
2188 assert_eq!(map.range(..).next(), None);
2189 }
2190
2191 #[test]
2192 fn ordered_queries_with_both_directories() {
2193 ordered_queries::<Flat>();
2194 ordered_queries::<Tree>();
2195 }
2196
2197 #[test]
2198 fn a_range_bounds_generational_keys_by_index() {
2199 let mut map: PagedDirectMap<Gen, u8> = PagedDirectMap::new();
2200 let held = Gen(3 | 2 << 16);
2201 map.insert(held, 1);
2202 map.insert(Gen(7), 2);
2203 let other = Gen(3);
2204 assert_eq!(map.range(other..=other).next(), Some((held, &1)));
2205 assert_eq!(map.range(Gen(4 | 9 << 16)..).next(), Some((Gen(7), &2)));
2206 }
2207
2208 #[cfg(feature = "std")]
2209 #[test]
2210 fn eq_and_hash_ignore_pages() {
2211 use core::hash::BuildHasher;
2212 let a: PagedDirectMap<u32, u8, 4> = [(1, 1), (9, 9)].into_iter().collect();
2213 let mut b: PagedDirectMap<u32, u8, 4> = [(9, 9), (5, 5), (1, 1)].into_iter().collect();
2214 assert_ne!(a, b);
2215 b.remove(5);
2216 assert_eq!(a, b);
2217 let s = std::hash::RandomState::new();
2218 assert_eq!(s.hash_one(&a), s.hash_one(&b));
2219 assert_eq!(vec![(1, 1), (9, 9)], entries(&b));
2220 }
2221
2222 #[cfg(feature = "serde")]
2223 #[test]
2224 fn serde_round_trip() {
2225 let map: PagedDirectMap<u32, u8> = [(70_000, 7), (2, 2)].into_iter().collect();
2226 let json = serde_json::to_string(&map).unwrap();
2227 assert_eq!(json, r#"{"2":2,"70000":7}"#);
2228 let back: PagedDirectMap<u32, u8> = serde_json::from_str(&json).unwrap();
2229 assert_eq!(back, map);
2230 }
2231}