1use alloc::boxed::Box;
4use alloc::vec::{IntoIter, Vec};
5use core::fmt;
6use core::iter::FusedIterator;
7
8use super::append::{AppendLog, DenseIter};
9use super::atomic::{AtomicU32, Ordering};
10use super::directory::{SharedDirectory, SharedPages};
11use super::index::retry;
12use super::vec::VecIterMut;
13use crate::key::Key;
14use crate::page::{DEFAULT_PAGE, Flat};
15use crate::sparse_map::PagedSparseMap;
16use crate::sparse_set::PagedSparseSet;
17
18const RESERVED: u32 = u32::MAX;
19const DENSE_LIMIT: usize = (u32::MAX - 1) as usize;
21
22struct IndexPage {
23 slots: Box<[AtomicU32]>,
24}
25
26struct Index<const PAGE: usize, D: SharedDirectory = Flat> {
27 pages: D::Pages<IndexPage>,
28}
29
30struct Reservation<'a> {
33 slot: &'a AtomicU32,
34 armed: bool,
35}
36
37impl Reservation<'_> {
38 fn publish(mut self, pos: usize) {
39 self.slot.store(pos as u32 + 1, Ordering::Release);
42 self.armed = false;
43 }
44}
45
46impl Drop for Reservation<'_> {
47 fn drop(&mut self) {
48 if self.armed {
49 self.slot.store(0, Ordering::Release);
52 }
53 }
54}
55
56impl<const PAGE: usize, D: SharedDirectory> Index<PAGE, D> {
57 fn valid_page_capacity() -> bool {
58 PAGE > 0 && PAGE <= isize::MAX as usize / core::mem::size_of::<AtomicU32>()
59 }
60
61 fn new() -> Self {
62 assert!(
63 Self::valid_page_capacity(),
64 "ConcurrentSparse: invalid page capacity"
65 );
66 Self {
67 pages: D::Pages::<IndexPage>::new(),
68 }
69 }
70
71 fn page_number(index: usize) -> usize {
72 D::Pages::<IndexPage>::page_number::<PAGE>(index)
73 .expect("ConcurrentSparse: key index exceeds sparse spine range")
74 }
75
76 fn slot(&self, index: usize) -> Option<&AtomicU32> {
77 self.pages
78 .get(Self::page_number(index))
79 .map(|page| &page.slots[index % PAGE])
80 }
81
82 fn ensure_slot(&self, index: usize) -> &AtomicU32 {
83 let page = self.pages.get_or_insert_with(Self::page_number(index), || {
84 Box::new(IndexPage {
85 slots: (0..PAGE).map(|_| AtomicU32::new(0)).collect(),
86 })
87 });
88 &page.slots[index % PAGE]
89 }
90
91 fn shrink_to_fit(&mut self) {
94 self.pages.retain(|_, page| {
95 page.slots
96 .iter()
97 .any(|slot| slot.load(Ordering::Relaxed) != 0)
99 });
100 }
101
102 fn position(&self, index: usize) -> Option<usize> {
103 match self.slot(index)?.load(Ordering::Acquire) {
105 0 | RESERVED => None,
106 word => Some(word as usize - 1),
107 }
108 }
109
110 fn try_claim(slot: &AtomicU32) -> Claim<'_> {
112 match slot.load(Ordering::Acquire) {
114 0 => {
115 match slot.compare_exchange(0, RESERVED, Ordering::AcqRel, Ordering::Acquire) {
118 Ok(_) => Claim::Owned(Reservation { slot, armed: true }),
119 Err(RESERVED) => Claim::Busy,
121 Err(word) => Claim::Present(word as usize - 1),
122 }
123 }
124 RESERVED => Claim::Busy,
125 word => Claim::Present(word as usize - 1),
126 }
127 }
128
129 fn claim(&self, index: usize) -> Result<Reservation<'_>, usize> {
130 let slot = self.ensure_slot(index);
131 let mut spins = 0;
132 loop {
133 match Self::try_claim(slot) {
134 Claim::Owned(owner) => return Ok(owner),
135 Claim::Present(pos) => return Err(pos),
136 Claim::Busy => retry(&mut spins),
140 }
141 }
142 }
143}
144
145enum Claim<'a> {
146 Owned(Reservation<'a>),
147 Present(usize),
148 Busy,
149}
150
151const BATCH: usize = 256;
155
156#[cfg(all(test, loom))]
159pub(super) static BATCH_BUSY: std::sync::atomic::AtomicUsize =
160 std::sync::atomic::AtomicUsize::new(0);
161
162fn insert_batched<'a, K: Key, T, const PAGE: usize, D: SharedDirectory>(
169 index: &'a Index<PAGE, D>,
170 dense: &AppendLog<T, PAGE>,
171 items: impl IntoIterator<Item = T>,
172 key_of: impl Fn(&T) -> K,
173 insert_one: impl Fn(T) -> bool,
174 full: &str,
175) -> usize {
176 let mut items = items.into_iter();
177 let mut inserted = 0;
178 let mut pending = Vec::with_capacity(BATCH);
182 let mut deferred = Vec::new();
183 let mut entries: Vec<T> = Vec::with_capacity(BATCH);
184 let mut owners: Vec<Reservation<'a>> = Vec::with_capacity(BATCH);
185 loop {
186 for item in items.by_ref().take(BATCH) {
189 let key_index = key_of(&item).index();
190 let slot = index.ensure_slot(key_index);
191 pending.push((key_index, slot, Some(item)));
192 }
193 let taken = pending.len();
194 deferred.reserve(taken);
197 for &mut (key_index, slot, ref mut item) in &mut pending {
198 if deferred.iter().any(|(key, _)| *key == key_index) {
201 deferred.push((key_index, item.take().expect("prepared item")));
202 } else {
203 match Index::<PAGE, D>::try_claim(slot) {
204 Claim::Owned(owner) => {
205 owners.push(owner);
206 entries.push(item.take().expect("prepared item"));
207 }
208 Claim::Present(_) => {}
209 Claim::Busy => {
210 #[cfg(all(test, loom))]
211 BATCH_BUSY.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
212 deferred.push((key_index, item.take().expect("prepared item")));
213 }
214 }
215 }
216 }
217 if !owners.is_empty() {
218 let Some(start) = dense.push_many_from(&mut entries, DENSE_LIMIT) else {
219 panic!("{full}");
220 };
221 inserted += owners.len();
222 for (i, owner) in owners.drain(..).enumerate() {
223 owner.publish(start + i);
224 }
225 }
226 pending.clear();
228 for (_, item) in deferred.drain(..) {
229 inserted += usize::from(insert_one(item));
230 }
231 if taken < BATCH {
234 return inserted;
235 }
236 }
237}
238
239pub struct ConcurrentSparseSet<K: Key, const PAGE: usize = DEFAULT_PAGE, D: SharedDirectory = Flat>
267{
268 index: Index<PAGE, D>,
269 dense: AppendLog<K, PAGE>,
271}
272
273unsafe impl<K: Key + Send, const PAGE: usize, D: SharedDirectory> Send
275 for ConcurrentSparseSet<K, PAGE, D>
276{
277}
278unsafe impl<K: Key + Send + Sync, const PAGE: usize, D: SharedDirectory> Sync
281 for ConcurrentSparseSet<K, PAGE, D>
282{
283}
284
285impl<K: Key, const PAGE: usize, D: SharedDirectory> ConcurrentSparseSet<K, PAGE, D> {
286 pub const PAGE_SIZE: usize = PAGE;
288
289 pub fn new() -> Self {
295 Self {
296 index: Index::new(),
297 dense: AppendLog::new(),
298 }
299 }
300
301 pub fn insert(&self, key: K) -> bool {
309 let Ok(owner) = self.index.claim(key.index()) else {
310 return false;
311 };
312 match self.dense.push(key, DENSE_LIMIT) {
313 Ok(pos) => owner.publish(pos),
314 Err(_) => {
315 drop(owner);
316 panic!("ConcurrentSparseSet cannot hold more than u32::MAX - 1 keys");
317 }
318 }
319 true
320 }
321
322 pub fn insert_many(&self, keys: impl IntoIterator<Item = K>) -> usize {
334 insert_batched(
335 &self.index,
336 &self.dense,
337 keys,
338 |&key| key,
339 |key| self.insert(key),
340 "ConcurrentSparseSet cannot hold more than u32::MAX - 1 keys",
341 )
342 }
343
344 pub fn position(&self, key: K) -> Option<usize> {
348 let pos = self.index.position(key.index())?;
349 self.dense
352 .get(pos)
353 .filter(|&&stored| stored == key)
354 .map(|_| pos)
355 }
356
357 pub fn contains(&self, key: K) -> bool {
360 self.position(key).is_some()
361 }
362
363 pub fn len(&self) -> usize {
365 self.dense.len()
366 }
367
368 pub fn is_empty(&self) -> bool {
370 self.len() == 0
371 }
372
373 pub fn iter(&self) -> DenseIter<'_, K, PAGE> {
375 self.dense.iter()
376 }
377
378 pub fn pages(
381 &self,
382 ) -> impl DoubleEndedIterator<Item = &[K]> + ExactSizeIterator + FusedIterator {
383 self.dense.pages()
384 }
385
386 pub fn remove(&mut self, key: K) -> bool {
389 let Some(pos) = self.position(key) else {
390 return false;
391 };
392 let last = self.dense.len() - 1;
393 let removed = self
395 .index
396 .slot(key.index())
397 .expect("present key has a slot");
398 let moved = if pos == last {
399 None
400 } else {
401 Some(
402 self.index
403 .slot(self.dense.get(last).expect("last key exists").index())
404 .expect("moved key has a slot"),
405 )
406 };
407 self.dense.swap_remove(pos);
408 removed.store(0, Ordering::Relaxed);
410 if let Some(slot) = moved {
411 slot.store(pos as u32 + 1, Ordering::Relaxed);
413 }
414 true
415 }
416
417 pub fn clear(&mut self) {
420 while self.pop_key().is_some() {}
421 }
422
423 pub fn shrink_to_fit(&mut self) {
441 self.index.shrink_to_fit();
442 self.dense.shrink_to_fit();
443 }
444
445 pub fn drain(&mut self) -> IntoIter<K> {
448 let mut keys = Vec::with_capacity(self.len());
449 while let Some(key) = self.pop_key() {
450 keys.push(key);
451 }
452 keys.reverse();
453 keys.into_iter()
454 }
455
456 fn pop_key(&mut self) -> Option<K> {
457 let last = self.dense.len().checked_sub(1)?;
458 let key = *self.dense.get(last).expect("last key exists");
459 let slot = self
460 .index
461 .slot(key.index())
462 .expect("present key has a slot");
463 let key = self.dense.pop();
464 slot.store(0, Ordering::Relaxed);
466 key
467 }
468
469 pub fn snapshot(&self) -> PagedSparseSet<K, PAGE, D> {
474 self.iter().copied().collect()
475 }
476
477 pub fn into_inner(self) -> PagedSparseSet<K, PAGE, D> {
479 self.dense.into_inner().into_iter().collect()
480 }
481}
482
483impl<'a, K: Key, const PAGE: usize, D: SharedDirectory> IntoIterator
484 for &'a ConcurrentSparseSet<K, PAGE, D>
485{
486 type Item = &'a K;
487 type IntoIter = DenseIter<'a, K, PAGE>;
488
489 fn into_iter(self) -> Self::IntoIter {
490 self.iter()
491 }
492}
493
494impl<K: Key, const PAGE: usize, D: SharedDirectory> Clone for ConcurrentSparseSet<K, PAGE, D> {
497 fn clone(&self) -> Self {
498 Self::from(self.snapshot())
499 }
500}
501
502impl<K: Key, const PAGE: usize, D: SharedDirectory> Default for ConcurrentSparseSet<K, PAGE, D> {
503 fn default() -> Self {
504 Self::new()
505 }
506}
507
508impl<K: Key + fmt::Debug, const PAGE: usize, D: SharedDirectory> fmt::Debug
509 for ConcurrentSparseSet<K, PAGE, D>
510{
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 f.debug_set().entries(self.iter()).finish()
513 }
514}
515
516impl<K: Key, const PAGE: usize, D: SharedDirectory> FromIterator<K>
517 for ConcurrentSparseSet<K, PAGE, D>
518{
519 fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
520 let mut result = Self::new();
521 result.extend(iter);
522 result
523 }
524}
525
526impl<K: Key, const PAGE: usize, D: SharedDirectory> Extend<K> for ConcurrentSparseSet<K, PAGE, D> {
528 fn extend<I: IntoIterator<Item = K>>(&mut self, iter: I) {
529 for key in iter {
530 self.insert(key);
531 }
532 }
533}
534
535impl<K: Key, const PAGE: usize, D: SharedDirectory> From<PagedSparseSet<K, PAGE, D>>
536 for ConcurrentSparseSet<K, PAGE, D>
537{
538 fn from(inner: PagedSparseSet<K, PAGE, D>) -> Self {
539 inner.into_iter().collect()
540 }
541}
542
543pub struct ConcurrentSparseMap<
571 K: Key,
572 V,
573 const PAGE: usize = DEFAULT_PAGE,
574 D: SharedDirectory = Flat,
575> {
576 index: Index<PAGE, D>,
577 dense: AppendLog<(K, V), PAGE>,
579}
580
581unsafe impl<K: Key + Send, V: Send, const PAGE: usize, D: SharedDirectory> Send
584 for ConcurrentSparseMap<K, V, PAGE, D>
585{
586}
587unsafe impl<K: Key + Send + Sync, V: Send + Sync, const PAGE: usize, D: SharedDirectory> Sync
590 for ConcurrentSparseMap<K, V, PAGE, D>
591{
592}
593
594impl<K: Key, V, const PAGE: usize, D: SharedDirectory> ConcurrentSparseMap<K, V, PAGE, D> {
595 pub const PAGE_SIZE: usize = PAGE;
597
598 pub fn new() -> Self {
604 Self {
605 index: Index::new(),
606 dense: AppendLog::new(),
607 }
608 }
609
610 fn position(&self, key: &K) -> Option<usize> {
611 let pos = self.index.position(key.index())?;
612 self.dense
613 .get(pos)
614 .filter(|(stored, _)| stored == key)
615 .map(|_| pos)
616 }
617
618 fn append(&self, reservation: Reservation<'_>, key: K, value: V) -> &V {
619 let mut entry = Some((key, value));
620 let owner = reservation;
622 let Some(pos) = self.dense.push_from(&mut entry, DENSE_LIMIT) else {
623 panic!("ConcurrentSparseMap cannot hold more than u32::MAX - 1 entries");
624 };
625 owner.publish(pos);
626 &self.dense.get(pos).expect("published entry is ready").1
627 }
628
629 pub fn try_insert(&self, key: K, value: V) -> Result<&V, (K, V)> {
638 match self.index.claim(key.index()) {
639 Ok(owner) => Ok(self.append(owner, key, value)),
640 Err(_) => Err((key, value)),
641 }
642 }
643
644 pub fn try_insert_many(&self, entries: impl IntoIterator<Item = (K, V)>) -> usize {
656 insert_batched(
657 &self.index,
658 &self.dense,
659 entries,
660 |(key, _)| *key,
661 |(key, value)| self.try_insert(key, value).is_ok(),
662 "ConcurrentSparseMap cannot hold more than u32::MAX - 1 entries",
663 )
664 }
665
666 pub fn get(&self, key: &K) -> Option<&V> {
669 self.position(key)
670 .map(|pos| &self.dense.get(pos).expect("published entry is ready").1)
671 }
672
673 pub fn contains_key(&self, key: &K) -> bool {
676 self.position(key).is_some()
677 }
678
679 pub fn get_or_insert_with(&self, key: K, make: impl FnOnce() -> V) -> Option<&V> {
693 match self.index.claim(key.index()) {
694 Ok(owner) => {
695 let value = make();
696 Some(self.append(owner, key, value))
697 }
698 Err(pos) => {
699 let (stored, value) = self.dense.get(pos).expect("published entry is ready");
700 (stored == &key).then_some(value)
701 }
702 }
703 }
704
705 pub fn len(&self) -> usize {
707 self.dense.len()
708 }
709
710 pub fn is_empty(&self) -> bool {
712 self.len() == 0
713 }
714
715 pub fn iter(&self) -> SparseMapIter<'_, K, V, PAGE> {
717 SparseMapIter {
718 inner: self.dense.iter(),
719 }
720 }
721
722 pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
725 let pos = self.position(key)?;
726 self.dense.get_mut(pos).map(|(_, value)| value)
727 }
728
729 pub fn remove(&mut self, key: &K) -> Option<V> {
732 let pos = self.position(key)?;
733 let last = self.dense.len() - 1;
734 let removed = self
735 .index
736 .slot(key.index())
737 .expect("present key has a slot");
738 let moved = if pos == last {
739 None
740 } else {
741 Some(
742 self.index
743 .slot(self.dense.get(last).expect("last entry exists").0.index())
744 .expect("moved key has a slot"),
745 )
746 };
747 let (_, value) = self.dense.swap_remove(pos);
748 removed.store(0, Ordering::Relaxed);
750 if let Some(slot) = moved {
751 slot.store(pos as u32 + 1, Ordering::Relaxed);
753 }
754 Some(value)
755 }
756
757 pub fn iter_mut(&mut self) -> SparseMapIterMut<'_, K, V> {
760 SparseMapIterMut {
761 inner: VecIterMut::new(&mut self.dense),
762 }
763 }
764
765 pub fn clear(&mut self) {
769 while let Some(entry) = self.pop_entry() {
770 drop(entry);
771 }
772 }
773
774 pub fn shrink_to_fit(&mut self) {
778 self.index.shrink_to_fit();
779 self.dense.shrink_to_fit();
780 }
781
782 pub fn drain(&mut self) -> IntoIter<(K, V)> {
785 let mut entries = Vec::with_capacity(self.len());
786 while let Some(entry) = self.pop_entry() {
787 entries.push(entry);
788 }
789 entries.reverse();
790 entries.into_iter()
791 }
792
793 fn pop_entry(&mut self) -> Option<(K, V)> {
794 let last = self.dense.len().checked_sub(1)?;
795 let key = self.dense.get(last).expect("last entry exists").0;
796 let slot = self
797 .index
798 .slot(key.index())
799 .expect("present key has a slot");
800 let entry = self.dense.pop();
801 slot.store(0, Ordering::Relaxed);
803 entry
804 }
805
806 pub fn snapshot(&self) -> PagedSparseMap<K, V, PAGE, D>
811 where
812 V: Clone,
813 {
814 self.iter()
815 .map(|(key, value)| (*key, value.clone()))
816 .collect()
817 }
818
819 pub fn into_inner(self) -> PagedSparseMap<K, V, PAGE, D> {
822 self.dense.into_inner().into_iter().collect()
823 }
824}
825
826impl<'a, K: Key, V, const PAGE: usize, D: SharedDirectory> IntoIterator
827 for &'a ConcurrentSparseMap<K, V, PAGE, D>
828{
829 type Item = (&'a K, &'a V);
830 type IntoIter = SparseMapIter<'a, K, V, PAGE>;
831
832 fn into_iter(self) -> Self::IntoIter {
833 self.iter()
834 }
835}
836
837impl<'a, K: Key, V, const PAGE: usize, D: SharedDirectory> IntoIterator
838 for &'a mut ConcurrentSparseMap<K, V, PAGE, D>
839{
840 type Item = (&'a K, &'a mut V);
841 type IntoIter = SparseMapIterMut<'a, K, V>;
842
843 fn into_iter(self) -> Self::IntoIter {
844 self.iter_mut()
845 }
846}
847
848#[must_use = "iterators are lazy and do nothing unless consumed"]
850pub struct SparseMapIter<'a, K, V, const PAGE: usize = DEFAULT_PAGE> {
851 inner: DenseIter<'a, (K, V), PAGE>,
852}
853
854impl<'a, K, V, const PAGE: usize> Iterator for SparseMapIter<'a, K, V, PAGE> {
855 type Item = (&'a K, &'a V);
856
857 fn next(&mut self) -> Option<Self::Item> {
858 self.nth(0)
859 }
860
861 fn nth(&mut self, n: usize) -> Option<Self::Item> {
862 self.inner.nth(n).map(|(key, value)| (key, value))
863 }
864
865 fn size_hint(&self) -> (usize, Option<usize>) {
866 self.inner.size_hint()
867 }
868}
869
870impl<K, V, const PAGE: usize> DoubleEndedIterator for SparseMapIter<'_, K, V, PAGE> {
871 fn next_back(&mut self) -> Option<Self::Item> {
872 self.nth_back(0)
873 }
874
875 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
876 self.inner.nth_back(n).map(|(key, value)| (key, value))
877 }
878}
879
880impl<K, V, const PAGE: usize> ExactSizeIterator for SparseMapIter<'_, K, V, PAGE> {}
881impl<K, V, const PAGE: usize> FusedIterator for SparseMapIter<'_, K, V, PAGE> {}
882
883impl<K, V, const PAGE: usize> fmt::Debug for SparseMapIter<'_, K, V, PAGE> {
884 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885 f.debug_struct("SparseMapIter")
886 .field("inner", &self.inner)
887 .finish()
888 }
889}
890
891#[must_use = "iterators are lazy and do nothing unless consumed"]
894pub struct SparseMapIterMut<'a, K, V> {
895 inner: VecIterMut<'a, (K, V)>,
896}
897
898impl<'a, K, V> Iterator for SparseMapIterMut<'a, K, V> {
899 type Item = (&'a K, &'a mut V);
900
901 fn next(&mut self) -> Option<Self::Item> {
902 self.inner.next().map(|(key, value)| (&*key, value))
903 }
904
905 fn size_hint(&self) -> (usize, Option<usize>) {
906 self.inner.size_hint()
907 }
908}
909
910impl<K, V> fmt::Debug for SparseMapIterMut<'_, K, V> {
911 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
912 f.debug_struct("SparseMapIterMut").finish_non_exhaustive()
913 }
914}
915
916impl<K: Key, V: Clone, const PAGE: usize, D: SharedDirectory> Clone
919 for ConcurrentSparseMap<K, V, PAGE, D>
920{
921 fn clone(&self) -> Self {
922 Self::from(self.snapshot())
923 }
924}
925
926impl<K: Key, V, const PAGE: usize, D: SharedDirectory> Default
927 for ConcurrentSparseMap<K, V, PAGE, D>
928{
929 fn default() -> Self {
930 Self::new()
931 }
932}
933
934impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: SharedDirectory> fmt::Debug
935 for ConcurrentSparseMap<K, V, PAGE, D>
936{
937 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
938 f.debug_map().entries(self.iter()).finish()
939 }
940}
941
942impl<K: Key, V, const PAGE: usize, D: SharedDirectory> From<PagedSparseMap<K, V, PAGE, D>>
943 for ConcurrentSparseMap<K, V, PAGE, D>
944{
945 fn from(inner: PagedSparseMap<K, V, PAGE, D>) -> Self {
946 inner.into_iter().collect()
947 }
948}
949
950impl<K: Key, V, const PAGE: usize, D: SharedDirectory> FromIterator<(K, V)>
952 for ConcurrentSparseMap<K, V, PAGE, D>
953{
954 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
955 let mut result = Self::new();
956 result.extend(iter);
957 result
958 }
959}
960
961impl<K: Key, V, const PAGE: usize, D: SharedDirectory> Extend<(K, V)>
963 for ConcurrentSparseMap<K, V, PAGE, D>
964{
965 fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
966 for (key, value) in iter {
967 let _ = self.try_insert(key, value);
968 }
969 }
970}
971
972#[cfg(feature = "serde")]
973mod serde_impl {
974 use super::*;
975 use crate::concurrent::serde::deserialize_map;
976 use core::marker::PhantomData;
977 use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Visitor};
978 use serde::ser::{Serialize, Serializer};
979
980 fn check_index<const PAGE: usize, D: SharedDirectory>(
981 index: usize,
982 ) -> Result<(), &'static str> {
983 if D::Pages::<IndexPage>::page_number::<PAGE>(index).is_none() {
984 return Err("ConcurrentSparse: key index exceeds sparse spine range");
985 }
986 Ok(())
987 }
988
989 fn can_append_at<T, const PAGE: usize>(len: usize) -> bool {
990 len < DENSE_LIMIT && AppendLog::<T, PAGE>::can_append_at(len)
991 }
992
993 impl<K: Key + Serialize, const PAGE: usize, D: SharedDirectory> Serialize
997 for ConcurrentSparseSet<K, PAGE, D>
998 {
999 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1000 serializer.collect_seq(self.iter())
1001 }
1002 }
1003
1004 impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: SharedDirectory> Deserialize<'de>
1007 for ConcurrentSparseSet<K, PAGE, D>
1008 {
1009 fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1010 struct SetVisitor<K, const PAGE: usize, D>(PhantomData<(K, D)>);
1011
1012 impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: SharedDirectory> Visitor<'de>
1013 for SetVisitor<K, PAGE, D>
1014 {
1015 type Value = ConcurrentSparseSet<K, PAGE, D>;
1016
1017 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1018 f.write_str("a sequence of keys")
1019 }
1020
1021 fn visit_seq<A: SeqAccess<'de>>(
1022 self,
1023 mut access: A,
1024 ) -> Result<Self::Value, A::Error> {
1025 let set = ConcurrentSparseSet::new();
1026 while let Some(key) = access.next_element::<K>()? {
1027 let index = key.index();
1028 check_index::<PAGE, D>(index).map_err(A::Error::custom)?;
1029 if !can_append_at::<K, PAGE>(set.len())
1030 && set.index.position(index).is_none()
1031 {
1032 return Err(A::Error::custom(
1033 "ConcurrentSparseSet: dense capacity exceeded",
1034 ));
1035 }
1036 set.insert(key);
1037 }
1038 Ok(set)
1039 }
1040 }
1041
1042 if !Index::<PAGE, D>::valid_page_capacity()
1043 || !AppendLog::<K, PAGE>::valid_page_capacity()
1044 {
1045 return Err(De::Error::custom(
1046 "ConcurrentSparseSet: invalid page capacity",
1047 ));
1048 }
1049 deserializer.deserialize_seq(SetVisitor::<K, PAGE, D>(PhantomData))
1050 }
1051 }
1052
1053 impl<K: Key + Serialize, V: Serialize, const PAGE: usize, D: SharedDirectory> Serialize
1057 for ConcurrentSparseMap<K, V, PAGE, D>
1058 {
1059 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1060 serializer.collect_map(self.iter())
1061 }
1062 }
1063
1064 impl<'de, K: Key + Deserialize<'de>, V: Deserialize<'de>, const PAGE: usize, D: SharedDirectory>
1068 Deserialize<'de> for ConcurrentSparseMap<K, V, PAGE, D>
1069 {
1070 fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1071 if !Index::<PAGE, D>::valid_page_capacity()
1072 || !AppendLog::<(K, V), PAGE>::valid_page_capacity()
1073 {
1074 return Err(De::Error::custom(
1075 "ConcurrentSparseMap: invalid page capacity",
1076 ));
1077 }
1078 deserialize_map(deserializer, Self::new(), |map, key: K, value: V| {
1079 let index = key.index();
1080 check_index::<PAGE, D>(index)?;
1081 if let Some(pos) = map.index.position(index) {
1082 let (stored, old) = map.dense.get_mut(pos).expect("published entry is ready");
1083 if *stored != key {
1084 *stored = key;
1085 }
1086 *old = value;
1087 } else {
1088 if !can_append_at::<(K, V), PAGE>(map.len()) {
1089 return Err("ConcurrentSparseMap: dense capacity exceeded");
1090 }
1091 let _ = map.try_insert(key, value);
1092 }
1093 Ok(())
1094 })
1095 }
1096 }
1097}
1098
1099#[cfg(all(test, not(loom), feature = "std"))]
1100mod tests {
1101 use super::*;
1102 use std::panic::{AssertUnwindSafe, catch_unwind};
1103
1104 #[test]
1105 fn bounded_log_failure_rolls_back_sparse_reservation() {
1106 let index = Index::<2>::new();
1107 let dense = AppendLog::<u32, 2>::new();
1108 let owner = index.claim(1).ok().unwrap();
1109 assert_eq!(dense.push(1, 0), Err(1));
1110 drop(owner);
1111 assert_eq!(index.position(1), None);
1112 let owner = index.claim(1).ok().unwrap();
1113 owner.publish(dense.push(1, 1).unwrap());
1114 assert_eq!(index.position(1), Some(0));
1115 }
1116
1117 #[test]
1118 fn unwinding_before_dense_claim_does_not_leave_reserved() {
1119 let index = Index::<2>::new();
1120 let result = catch_unwind(AssertUnwindSafe(|| {
1121 let _owner = index.claim(1).ok().unwrap();
1122 panic!("simulated allocation failure before dense claim");
1123 }));
1124 assert!(result.is_err());
1125 assert!(index.claim(1).is_ok());
1126 }
1127}