use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt;
use core::iter::FusedIterator;
use super::append::AppendLog;
use super::atomic::{AtomicU32, Ordering};
use super::directory::{SharedDirectory, SharedPages};
use super::index::retry;
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 new() -> Self {
assert!(
PAGE > 0 && PAGE <= isize::MAX as usize / core::mem::size_of::<AtomicU32>(),
"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 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) -> impl DoubleEndedIterator<Item = &K> + ExactSizeIterator + FusedIterator {
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 let Some(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 _ = self.dense.pop();
slot.store(0, Ordering::Relaxed);
}
}
pub fn into_inner(self) -> PagedSparseSet<K, PAGE, D> {
self.dense.into_inner().into_iter().collect()
}
}
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 result = Self::new();
for key in iter {
result.insert(key);
}
result
}
}
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,
) -> impl DoubleEndedIterator<Item = (&K, &V)> + ExactSizeIterator + FusedIterator {
self.dense.iter().map(|(key, value)| (key, value))
}
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) -> impl Iterator<Item = (&K, &mut V)> {
self.dense.iter_mut().map(|(key, value)| (&*key, value))
}
pub fn clear(&mut self) {
while let Some(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);
drop(entry);
}
}
pub fn into_inner(self) -> PagedSparseMap<K, V, PAGE, D> {
self.dense.into_inner().into_iter().collect()
}
}
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 {
let result = Self::new();
for (key, value) in inner {
let _ = result.try_insert(key, value);
}
result
}
}
#[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());
}
}