use alloc::boxed::Box;
use alloc::vec::{IntoIter, Vec};
use core::fmt;
use core::iter::FusedIterator;
use super::append::{AppendLog, DenseIter};
use super::atomic::{AtomicU32, Ordering};
use super::directory::{SharedDirectory, SharedPages};
use super::index::retry;
use super::vec::VecIterMut;
use crate::key::Key;
use crate::page::{DEFAULT_PAGE, Flat};
use crate::sparse_map::PagedSparseMap;
use crate::sparse_set::PagedSparseSet;
const RESERVED: u32 = u32::MAX;
const DENSE_LIMIT: usize = (u32::MAX - 1) as usize;
struct IndexPage {
slots: Box<[AtomicU32]>,
}
struct Index<const PAGE: usize, D: SharedDirectory = Flat> {
pages: D::Pages<IndexPage>,
}
struct Reservation<'a> {
slot: &'a AtomicU32,
armed: bool,
}
impl Reservation<'_> {
fn publish(mut self, pos: usize) {
self.slot.store(pos as u32 + 1, Ordering::Release);
self.armed = false;
}
}
impl Drop for Reservation<'_> {
fn drop(&mut self) {
if self.armed {
self.slot.store(0, Ordering::Release);
}
}
}
impl<const PAGE: usize, D: SharedDirectory> Index<PAGE, D> {
fn valid_page_capacity() -> bool {
PAGE > 0 && PAGE <= isize::MAX as usize / core::mem::size_of::<AtomicU32>()
}
fn new() -> Self {
assert!(
Self::valid_page_capacity(),
"ConcurrentSparse: invalid page capacity"
);
Self {
pages: D::Pages::<IndexPage>::new(),
}
}
fn page_number(index: usize) -> usize {
D::Pages::<IndexPage>::page_number::<PAGE>(index)
.expect("ConcurrentSparse: key index exceeds sparse spine range")
}
fn slot(&self, index: usize) -> Option<&AtomicU32> {
self.pages
.get(Self::page_number(index))
.map(|page| &page.slots[index % PAGE])
}
fn ensure_slot(&self, index: usize) -> &AtomicU32 {
let page = self.pages.get_or_insert_with(Self::page_number(index), || {
Box::new(IndexPage {
slots: (0..PAGE).map(|_| AtomicU32::new(0)).collect(),
})
});
&page.slots[index % PAGE]
}
fn shrink_to_fit(&mut self) {
self.pages.retain(|_, page| {
page.slots
.iter()
.any(|slot| slot.load(Ordering::Relaxed) != 0)
});
}
fn position(&self, index: usize) -> Option<usize> {
match self.slot(index)?.load(Ordering::Acquire) {
0 | RESERVED => None,
word => Some(word as usize - 1),
}
}
fn try_claim(slot: &AtomicU32) -> Claim<'_> {
match slot.load(Ordering::Acquire) {
0 => {
match slot.compare_exchange(0, RESERVED, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => Claim::Owned(Reservation { slot, armed: true }),
Err(RESERVED) => Claim::Busy,
Err(word) => Claim::Present(word as usize - 1),
}
}
RESERVED => Claim::Busy,
word => Claim::Present(word as usize - 1),
}
}
fn claim(&self, index: usize) -> Result<Reservation<'_>, usize> {
let slot = self.ensure_slot(index);
let mut spins = 0;
loop {
match Self::try_claim(slot) {
Claim::Owned(owner) => return Ok(owner),
Claim::Present(pos) => return Err(pos),
Claim::Busy => retry(&mut spins),
}
}
}
}
enum Claim<'a> {
Owned(Reservation<'a>),
Present(usize),
Busy,
}
const BATCH: usize = 256;
#[cfg(all(test, loom))]
pub(super) static BATCH_BUSY: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
fn insert_batched<'a, K: Key, T, const PAGE: usize, D: SharedDirectory>(
index: &'a Index<PAGE, D>,
dense: &AppendLog<T, PAGE>,
items: impl IntoIterator<Item = T>,
key_of: impl Fn(&T) -> K,
insert_one: impl Fn(T) -> bool,
full: &str,
) -> usize {
let mut items = items.into_iter();
let mut inserted = 0;
let mut pending = Vec::with_capacity(BATCH);
let mut deferred = Vec::new();
let mut entries: Vec<T> = Vec::with_capacity(BATCH);
let mut owners: Vec<Reservation<'a>> = Vec::with_capacity(BATCH);
loop {
for item in items.by_ref().take(BATCH) {
let key_index = key_of(&item).index();
let slot = index.ensure_slot(key_index);
pending.push((key_index, slot, Some(item)));
}
let taken = pending.len();
deferred.reserve(taken);
for &mut (key_index, slot, ref mut item) in &mut pending {
if deferred.iter().any(|(key, _)| *key == key_index) {
deferred.push((key_index, item.take().expect("prepared item")));
} else {
match Index::<PAGE, D>::try_claim(slot) {
Claim::Owned(owner) => {
owners.push(owner);
entries.push(item.take().expect("prepared item"));
}
Claim::Present(_) => {}
Claim::Busy => {
#[cfg(all(test, loom))]
BATCH_BUSY.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
deferred.push((key_index, item.take().expect("prepared item")));
}
}
}
}
if !owners.is_empty() {
let Some(start) = dense.push_many_from(&mut entries, DENSE_LIMIT) else {
panic!("{full}");
};
inserted += owners.len();
for (i, owner) in owners.drain(..).enumerate() {
owner.publish(start + i);
}
}
pending.clear();
for (_, item) in deferred.drain(..) {
inserted += usize::from(insert_one(item));
}
if taken < BATCH {
return inserted;
}
}
}
pub struct ConcurrentSparseSet<K: Key, const PAGE: usize = DEFAULT_PAGE, D: SharedDirectory = Flat>
{
index: Index<PAGE, D>,
dense: AppendLog<K, PAGE>,
}
unsafe impl<K: Key + Send, const PAGE: usize, D: SharedDirectory> Send
for ConcurrentSparseSet<K, PAGE, D>
{
}
unsafe impl<K: Key + Send + Sync, const PAGE: usize, D: SharedDirectory> Sync
for ConcurrentSparseSet<K, PAGE, D>
{
}
impl<K: Key, const PAGE: usize, D: SharedDirectory> ConcurrentSparseSet<K, PAGE, D> {
pub const PAGE_SIZE: usize = PAGE;
pub fn new() -> Self {
Self {
index: Index::new(),
dense: AppendLog::new(),
}
}
pub fn insert(&self, key: K) -> bool {
let Ok(owner) = self.index.claim(key.index()) else {
return false;
};
match self.dense.push(key, DENSE_LIMIT) {
Ok(pos) => owner.publish(pos),
Err(_) => {
drop(owner);
panic!("ConcurrentSparseSet cannot hold more than u32::MAX - 1 keys");
}
}
true
}
pub fn insert_many(&self, keys: impl IntoIterator<Item = K>) -> usize {
insert_batched(
&self.index,
&self.dense,
keys,
|&key| key,
|key| self.insert(key),
"ConcurrentSparseSet cannot hold more than u32::MAX - 1 keys",
)
}
pub fn position(&self, key: K) -> Option<usize> {
let pos = self.index.position(key.index())?;
self.dense
.get(pos)
.filter(|&&stored| stored == key)
.map(|_| pos)
}
pub fn contains(&self, key: K) -> bool {
self.position(key).is_some()
}
pub fn len(&self) -> usize {
self.dense.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn iter(&self) -> DenseIter<'_, K, PAGE> {
self.dense.iter()
}
pub fn pages(
&self,
) -> impl DoubleEndedIterator<Item = &[K]> + ExactSizeIterator + FusedIterator {
self.dense.pages()
}
pub fn remove(&mut self, key: K) -> bool {
let Some(pos) = self.position(key) else {
return false;
};
let last = self.dense.len() - 1;
let removed = self
.index
.slot(key.index())
.expect("present key has a slot");
let moved = if pos == last {
None
} else {
Some(
self.index
.slot(self.dense.get(last).expect("last key exists").index())
.expect("moved key has a slot"),
)
};
self.dense.swap_remove(pos);
removed.store(0, Ordering::Relaxed);
if let Some(slot) = moved {
slot.store(pos as u32 + 1, Ordering::Relaxed);
}
true
}
pub fn clear(&mut self) {
while self.pop_key().is_some() {}
}
pub fn shrink_to_fit(&mut self) {
self.index.shrink_to_fit();
self.dense.shrink_to_fit();
}
pub fn drain(&mut self) -> IntoIter<K> {
let mut keys = Vec::with_capacity(self.len());
while let Some(key) = self.pop_key() {
keys.push(key);
}
keys.reverse();
keys.into_iter()
}
fn pop_key(&mut self) -> Option<K> {
let last = self.dense.len().checked_sub(1)?;
let key = *self.dense.get(last).expect("last key exists");
let slot = self
.index
.slot(key.index())
.expect("present key has a slot");
let key = self.dense.pop();
slot.store(0, Ordering::Relaxed);
key
}
pub fn snapshot(&self) -> PagedSparseSet<K, PAGE, D> {
self.iter().copied().collect()
}
pub fn into_inner(self) -> PagedSparseSet<K, PAGE, D> {
self.dense.into_inner().into_iter().collect()
}
}
impl<'a, K: Key, const PAGE: usize, D: SharedDirectory> IntoIterator
for &'a ConcurrentSparseSet<K, PAGE, D>
{
type Item = &'a K;
type IntoIter = DenseIter<'a, K, PAGE>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<K: Key, const PAGE: usize, D: SharedDirectory> Clone for ConcurrentSparseSet<K, PAGE, D> {
fn clone(&self) -> Self {
Self::from(self.snapshot())
}
}
impl<K: Key, const PAGE: usize, D: SharedDirectory> Default for ConcurrentSparseSet<K, PAGE, D> {
fn default() -> Self {
Self::new()
}
}
impl<K: Key + fmt::Debug, const PAGE: usize, D: SharedDirectory> fmt::Debug
for ConcurrentSparseSet<K, PAGE, D>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
impl<K: Key, const PAGE: usize, D: SharedDirectory> FromIterator<K>
for ConcurrentSparseSet<K, PAGE, D>
{
fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
let mut result = Self::new();
result.extend(iter);
result
}
}
impl<K: Key, const PAGE: usize, D: SharedDirectory> Extend<K> for ConcurrentSparseSet<K, PAGE, D> {
fn extend<I: IntoIterator<Item = K>>(&mut self, iter: I) {
for key in iter {
self.insert(key);
}
}
}
impl<K: Key, const PAGE: usize, D: SharedDirectory> From<PagedSparseSet<K, PAGE, D>>
for ConcurrentSparseSet<K, PAGE, D>
{
fn from(inner: PagedSparseSet<K, PAGE, D>) -> Self {
inner.into_iter().collect()
}
}
pub struct ConcurrentSparseMap<
K: Key,
V,
const PAGE: usize = DEFAULT_PAGE,
D: SharedDirectory = Flat,
> {
index: Index<PAGE, D>,
dense: AppendLog<(K, V), PAGE>,
}
unsafe impl<K: Key + Send, V: Send, const PAGE: usize, D: SharedDirectory> Send
for ConcurrentSparseMap<K, V, PAGE, D>
{
}
unsafe impl<K: Key + Send + Sync, V: Send + Sync, const PAGE: usize, D: SharedDirectory> Sync
for ConcurrentSparseMap<K, V, PAGE, D>
{
}
impl<K: Key, V, const PAGE: usize, D: SharedDirectory> ConcurrentSparseMap<K, V, PAGE, D> {
pub const PAGE_SIZE: usize = PAGE;
pub fn new() -> Self {
Self {
index: Index::new(),
dense: AppendLog::new(),
}
}
fn position(&self, key: &K) -> Option<usize> {
let pos = self.index.position(key.index())?;
self.dense
.get(pos)
.filter(|(stored, _)| stored == key)
.map(|_| pos)
}
fn append(&self, reservation: Reservation<'_>, key: K, value: V) -> &V {
let mut entry = Some((key, value));
let owner = reservation;
let Some(pos) = self.dense.push_from(&mut entry, DENSE_LIMIT) else {
panic!("ConcurrentSparseMap cannot hold more than u32::MAX - 1 entries");
};
owner.publish(pos);
&self.dense.get(pos).expect("published entry is ready").1
}
pub fn try_insert(&self, key: K, value: V) -> Result<&V, (K, V)> {
match self.index.claim(key.index()) {
Ok(owner) => Ok(self.append(owner, key, value)),
Err(_) => Err((key, value)),
}
}
pub fn try_insert_many(&self, entries: impl IntoIterator<Item = (K, V)>) -> usize {
insert_batched(
&self.index,
&self.dense,
entries,
|(key, _)| *key,
|(key, value)| self.try_insert(key, value).is_ok(),
"ConcurrentSparseMap cannot hold more than u32::MAX - 1 entries",
)
}
pub fn get(&self, key: &K) -> Option<&V> {
self.position(key)
.map(|pos| &self.dense.get(pos).expect("published entry is ready").1)
}
pub fn contains_key(&self, key: &K) -> bool {
self.position(key).is_some()
}
pub fn get_or_insert_with(&self, key: K, make: impl FnOnce() -> V) -> Option<&V> {
match self.index.claim(key.index()) {
Ok(owner) => {
let value = make();
Some(self.append(owner, key, value))
}
Err(pos) => {
let (stored, value) = self.dense.get(pos).expect("published entry is ready");
(stored == &key).then_some(value)
}
}
}
pub fn len(&self) -> usize {
self.dense.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn iter(&self) -> SparseMapIter<'_, K, V, PAGE> {
SparseMapIter {
inner: self.dense.iter(),
}
}
pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
let pos = self.position(key)?;
self.dense.get_mut(pos).map(|(_, value)| value)
}
pub fn remove(&mut self, key: &K) -> Option<V> {
let pos = self.position(key)?;
let last = self.dense.len() - 1;
let removed = self
.index
.slot(key.index())
.expect("present key has a slot");
let moved = if pos == last {
None
} else {
Some(
self.index
.slot(self.dense.get(last).expect("last entry exists").0.index())
.expect("moved key has a slot"),
)
};
let (_, value) = self.dense.swap_remove(pos);
removed.store(0, Ordering::Relaxed);
if let Some(slot) = moved {
slot.store(pos as u32 + 1, Ordering::Relaxed);
}
Some(value)
}
pub fn iter_mut(&mut self) -> SparseMapIterMut<'_, K, V> {
SparseMapIterMut {
inner: VecIterMut::new(&mut self.dense),
}
}
pub fn clear(&mut self) {
while let Some(entry) = self.pop_entry() {
drop(entry);
}
}
pub fn shrink_to_fit(&mut self) {
self.index.shrink_to_fit();
self.dense.shrink_to_fit();
}
pub fn drain(&mut self) -> IntoIter<(K, V)> {
let mut entries = Vec::with_capacity(self.len());
while let Some(entry) = self.pop_entry() {
entries.push(entry);
}
entries.reverse();
entries.into_iter()
}
fn pop_entry(&mut self) -> Option<(K, V)> {
let last = self.dense.len().checked_sub(1)?;
let key = self.dense.get(last).expect("last entry exists").0;
let slot = self
.index
.slot(key.index())
.expect("present key has a slot");
let entry = self.dense.pop();
slot.store(0, Ordering::Relaxed);
entry
}
pub fn snapshot(&self) -> PagedSparseMap<K, V, PAGE, D>
where
V: Clone,
{
self.iter()
.map(|(key, value)| (*key, value.clone()))
.collect()
}
pub fn into_inner(self) -> PagedSparseMap<K, V, PAGE, D> {
self.dense.into_inner().into_iter().collect()
}
}
impl<'a, K: Key, V, const PAGE: usize, D: SharedDirectory> IntoIterator
for &'a ConcurrentSparseMap<K, V, PAGE, D>
{
type Item = (&'a K, &'a V);
type IntoIter = SparseMapIter<'a, K, V, PAGE>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, K: Key, V, const PAGE: usize, D: SharedDirectory> IntoIterator
for &'a mut ConcurrentSparseMap<K, V, PAGE, D>
{
type Item = (&'a K, &'a mut V);
type IntoIter = SparseMapIterMut<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct SparseMapIter<'a, K, V, const PAGE: usize = DEFAULT_PAGE> {
inner: DenseIter<'a, (K, V), PAGE>,
}
impl<'a, K, V, const PAGE: usize> Iterator for SparseMapIter<'a, K, V, PAGE> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.nth(0)
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.inner.nth(n).map(|(key, value)| (key, value))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V, const PAGE: usize> DoubleEndedIterator for SparseMapIter<'_, K, V, PAGE> {
fn next_back(&mut self) -> Option<Self::Item> {
self.nth_back(0)
}
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
self.inner.nth_back(n).map(|(key, value)| (key, value))
}
}
impl<K, V, const PAGE: usize> ExactSizeIterator for SparseMapIter<'_, K, V, PAGE> {}
impl<K, V, const PAGE: usize> FusedIterator for SparseMapIter<'_, K, V, PAGE> {}
impl<K, V, const PAGE: usize> fmt::Debug for SparseMapIter<'_, K, V, PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SparseMapIter")
.field("inner", &self.inner)
.finish()
}
}
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct SparseMapIterMut<'a, K, V> {
inner: VecIterMut<'a, (K, V)>,
}
impl<'a, K, V> Iterator for SparseMapIterMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(key, value)| (&*key, value))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<K, V> fmt::Debug for SparseMapIterMut<'_, K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SparseMapIterMut").finish_non_exhaustive()
}
}
impl<K: Key, V: Clone, const PAGE: usize, D: SharedDirectory> Clone
for ConcurrentSparseMap<K, V, PAGE, D>
{
fn clone(&self) -> Self {
Self::from(self.snapshot())
}
}
impl<K: Key, V, const PAGE: usize, D: SharedDirectory> Default
for ConcurrentSparseMap<K, V, PAGE, D>
{
fn default() -> Self {
Self::new()
}
}
impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: SharedDirectory> fmt::Debug
for ConcurrentSparseMap<K, V, PAGE, D>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl<K: Key, V, const PAGE: usize, D: SharedDirectory> From<PagedSparseMap<K, V, PAGE, D>>
for ConcurrentSparseMap<K, V, PAGE, D>
{
fn from(inner: PagedSparseMap<K, V, PAGE, D>) -> Self {
inner.into_iter().collect()
}
}
impl<K: Key, V, const PAGE: usize, D: SharedDirectory> FromIterator<(K, V)>
for ConcurrentSparseMap<K, V, PAGE, D>
{
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
let mut result = Self::new();
result.extend(iter);
result
}
}
impl<K: Key, V, const PAGE: usize, D: SharedDirectory> Extend<(K, V)>
for ConcurrentSparseMap<K, V, PAGE, D>
{
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
for (key, value) in iter {
let _ = self.try_insert(key, value);
}
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::*;
use crate::concurrent::serde::deserialize_map;
use core::marker::PhantomData;
use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Visitor};
use serde::ser::{Serialize, Serializer};
fn check_index<const PAGE: usize, D: SharedDirectory>(
index: usize,
) -> Result<(), &'static str> {
if D::Pages::<IndexPage>::page_number::<PAGE>(index).is_none() {
return Err("ConcurrentSparse: key index exceeds sparse spine range");
}
Ok(())
}
fn can_append_at<T, const PAGE: usize>(len: usize) -> bool {
len < DENSE_LIMIT && AppendLog::<T, PAGE>::can_append_at(len)
}
impl<K: Key + Serialize, const PAGE: usize, D: SharedDirectory> Serialize
for ConcurrentSparseSet<K, PAGE, D>
{
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.iter())
}
}
impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: SharedDirectory> Deserialize<'de>
for ConcurrentSparseSet<K, PAGE, D>
{
fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
struct SetVisitor<K, const PAGE: usize, D>(PhantomData<(K, D)>);
impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: SharedDirectory> Visitor<'de>
for SetVisitor<K, PAGE, D>
{
type Value = ConcurrentSparseSet<K, PAGE, D>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a sequence of keys")
}
fn visit_seq<A: SeqAccess<'de>>(
self,
mut access: A,
) -> Result<Self::Value, A::Error> {
let set = ConcurrentSparseSet::new();
while let Some(key) = access.next_element::<K>()? {
let index = key.index();
check_index::<PAGE, D>(index).map_err(A::Error::custom)?;
if !can_append_at::<K, PAGE>(set.len())
&& set.index.position(index).is_none()
{
return Err(A::Error::custom(
"ConcurrentSparseSet: dense capacity exceeded",
));
}
set.insert(key);
}
Ok(set)
}
}
if !Index::<PAGE, D>::valid_page_capacity()
|| !AppendLog::<K, PAGE>::valid_page_capacity()
{
return Err(De::Error::custom(
"ConcurrentSparseSet: invalid page capacity",
));
}
deserializer.deserialize_seq(SetVisitor::<K, PAGE, D>(PhantomData))
}
}
impl<K: Key + Serialize, V: Serialize, const PAGE: usize, D: SharedDirectory> Serialize
for ConcurrentSparseMap<K, V, PAGE, D>
{
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_map(self.iter())
}
}
impl<'de, K: Key + Deserialize<'de>, V: Deserialize<'de>, const PAGE: usize, D: SharedDirectory>
Deserialize<'de> for ConcurrentSparseMap<K, V, PAGE, D>
{
fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
if !Index::<PAGE, D>::valid_page_capacity()
|| !AppendLog::<(K, V), PAGE>::valid_page_capacity()
{
return Err(De::Error::custom(
"ConcurrentSparseMap: invalid page capacity",
));
}
deserialize_map(deserializer, Self::new(), |map, key: K, value: V| {
let index = key.index();
check_index::<PAGE, D>(index)?;
if let Some(pos) = map.index.position(index) {
let (stored, old) = map.dense.get_mut(pos).expect("published entry is ready");
if *stored != key {
*stored = key;
}
*old = value;
} else {
if !can_append_at::<(K, V), PAGE>(map.len()) {
return Err("ConcurrentSparseMap: dense capacity exceeded");
}
let _ = map.try_insert(key, value);
}
Ok(())
})
}
}
}
#[cfg(all(test, not(loom), feature = "std"))]
mod tests {
use super::*;
use std::panic::{AssertUnwindSafe, catch_unwind};
#[test]
fn bounded_log_failure_rolls_back_sparse_reservation() {
let index = Index::<2>::new();
let dense = AppendLog::<u32, 2>::new();
let owner = index.claim(1).ok().unwrap();
assert_eq!(dense.push(1, 0), Err(1));
drop(owner);
assert_eq!(index.position(1), None);
let owner = index.claim(1).ok().unwrap();
owner.publish(dense.push(1, 1).unwrap());
assert_eq!(index.position(1), Some(0));
}
#[test]
fn unwinding_before_dense_claim_does_not_leave_reserved() {
let index = Index::<2>::new();
let result = catch_unwind(AssertUnwindSafe(|| {
let _owner = index.claim(1).ok().unwrap();
panic!("simulated allocation failure before dense claim");
}));
assert!(result.is_err());
assert!(index.claim(1).is_ok());
}
}