use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt;
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ops::Index;
use core::ptr;
use super::atomic::{AtomicU32, AtomicU64, Ordering, UnsafeCell};
use super::count::StripedLen;
use super::free_stack::{FreeStack, Unissued, block_for};
use super::recycle::PageStack;
use super::spine::Spine;
use crate::hive::{Hive, RawPage, RawSlot};
use crate::id_alloc::{Id, MAX_INDICES, generation_of, live_version};
use crate::page::DEFAULT_PAGE;
#[cfg(not(loom))]
const CHUNKS: usize = 28;
#[cfg(loom)]
const CHUNKS: usize = 32;
const VERSION: u64 = u32::MAX as u64;
const BUSY: u64 = 1 << 32;
struct Slot<T> {
state: AtomicU64,
next: AtomicU32,
value: UnsafeCell<MaybeUninit<T>>,
}
impl<T> Slot<T> {
fn new() -> Self {
Self::with_state(0)
}
fn with_state(version: u32) -> Self {
Self {
state: AtomicU64::new(u64::from(version)),
next: AtomicU32::new(0),
value: UnsafeCell::new(MaybeUninit::uninit()),
}
}
fn exclusive_version(&self) -> u32 {
let word = self.state.load(Ordering::Relaxed);
debug_assert_eq!(word & !VERSION, 0, "exclusive slot is BUSY");
word as u32
}
}
struct Page<T> {
slots: Box<[Slot<T>]>,
}
fn vacant(live: u32) -> u64 {
u64::from(live.checked_add(1).unwrap_or(0))
}
pub struct ConcurrentAppendHive<T, const PAGE: usize = DEFAULT_PAGE> {
pages: Spine<Page<T>, CHUNKS>,
free: FreeStack,
recycled: PageStack,
len: StripedLen,
}
unsafe impl<T: Send, const PAGE: usize> Send for ConcurrentAppendHive<T, PAGE> {}
unsafe impl<T: Send + Sync, const PAGE: usize> Sync for ConcurrentAppendHive<T, PAGE> {}
struct Busy<'a, T, const PAGE: usize> {
hive: &'a ConcurrentAppendHive<T, PAGE>,
slot: &'a Slot<T>,
index: u32,
vacant: u64,
armed: bool,
}
impl<T, const PAGE: usize> Drop for Busy<'_, T, PAGE> {
fn drop(&mut self) {
if self.armed {
self.slot.state.store(self.vacant, Ordering::Release);
if self.vacant != 0 {
self.hive.free.push(self.index, &self.slot.next);
}
}
}
}
impl<T, const PAGE: usize> ConcurrentAppendHive<T, PAGE> {
pub const PAGE: usize = PAGE;
pub fn new() -> Self {
assert!(
PAGE > 0
&& PAGE <= u32::MAX as usize
&& PAGE <= isize::MAX as usize / core::mem::size_of::<Slot<T>>(),
"ConcurrentAppendHive: invalid page capacity"
);
Self {
pages: Spine::new(),
free: FreeStack::new(),
recycled: PageStack::new(),
len: StripedLen::new(),
}
}
fn slot(&self, index: u32) -> Option<&Slot<T>> {
if index == MAX_INDICES {
return None;
}
self.pages
.get(index as usize / PAGE)
.map(|page| &page.slots[index as usize % PAGE])
}
fn snapshot_slot(&self, index: u32, unissued: &Unissued) -> RawSlot<&T> {
let Some(slot) = self.slot(index) else {
return RawSlot::Vacant { version: 0 };
};
let word = slot.state.load(Ordering::Acquire);
let version = word as u32;
if word & BUSY != 0 {
debug_assert_eq!(version & 1, 0);
return RawSlot::Vacant { version };
}
if version & 1 != 0 {
let value = slot.value.with(|cell| {
unsafe { &*cell.cast::<T>() }
});
return RawSlot::Occupied { version, value };
}
let version = if version == 0 && unissued.contains_shared(index) {
2
} else {
version
};
RawSlot::Vacant { version }
}
fn ensure_slot(&self, index: u32) -> &Slot<T> {
let page = self.pages.get_or_insert_with(index as usize / PAGE, || {
Box::new(Page {
slots: (0..PAGE).map(|_| Slot::new()).collect(),
})
});
&page.slots[index as usize % PAGE]
}
fn recycle(&self) -> Option<u32> {
let (page, floor) = self.recycled.pop()?;
let base = page * PAGE;
let limit = PAGE.min(MAX_INDICES as usize - base);
let installed = self.pages.get_or_insert_with(page, || {
Box::new(Page {
slots: (0..PAGE)
.map(|offset| Slot::with_state(if offset < limit { floor } else { 0 }))
.collect(),
})
});
for offset in (1..limit).rev() {
self.free
.push((base + offset) as u32, &installed.slots[offset].next);
}
Some(base as u32)
}
fn claim(&self) -> Option<(Busy<'_, T, PAGE>, u32)> {
loop {
let (index, reused) = self.free.next_index(
|index| &self.slot(index).expect("free index has a page").next,
|| self.recycle(),
MAX_INDICES,
block_for(PAGE),
)?;
let slot = self.ensure_slot(index);
let old = slot.state.load(Ordering::Acquire);
if old & !VERSION != 0 || old & 1 != 0 || (reused && old == 0) {
continue;
}
if slot
.state
.compare_exchange(old, old | BUSY, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
continue;
}
let live = old as u32 + 1;
return Some((
Busy {
hive: self,
slot,
index,
vacant: vacant(live),
armed: true,
},
live,
));
}
}
fn write_value(&self, slot: &Slot<T>, index: u32, live: u32, value: T) {
slot.value.with_mut(|cell| {
unsafe { ptr::write(cell.cast::<T>(), value) };
});
self.len.increment(index as usize / PAGE);
slot.state.store(u64::from(live), Ordering::Release);
}
fn publish(&self, mut owner: Busy<'_, T, PAGE>, live: u32, value: T) -> Id {
self.write_value(owner.slot, owner.index, live, value);
owner.armed = false;
Id::new(owner.index, generation_of(live))
}
pub fn insert(&self, value: T) -> Id {
self.try_insert(value).unwrap_or_else(|_| {
panic!("ConcurrentAppendHive: all {MAX_INDICES} slot indices are occupied or retired")
})
}
pub fn try_insert(&self, value: T) -> Result<Id, T> {
let Some((owner, live)) = self.claim() else {
return Err(value);
};
Ok(self.publish(owner, live, value))
}
pub fn insert_with(&self, f: impl FnOnce(Id) -> T) -> Id {
self.try_insert_with(f).unwrap_or_else(|| {
panic!("ConcurrentAppendHive: all {MAX_INDICES} slot indices are occupied or retired")
})
}
pub fn try_insert_with(&self, f: impl FnOnce(Id) -> T) -> Option<Id> {
let (owner, live) = self.claim()?;
let value = f(Id::new(owner.index, generation_of(live)));
Some(self.publish(owner, live, value))
}
pub fn get(&self, id: Id) -> Option<&T> {
let live = live_version(id.generation())?;
let slot = self.slot(id.index())?;
if slot.state.load(Ordering::Acquire) != u64::from(live) {
return None;
}
Some(slot.value.with(|cell| {
unsafe { &*cell.cast::<T>() }
}))
}
pub fn id_of(&self, value: &T) -> Option<Id> {
let target = ptr::from_ref(value);
let size = core::mem::size_of::<Slot<T>>();
for (number, page) in self.pages.iter() {
let start = page.slots.as_ptr().addr();
let Some(offset) = target.addr().checked_sub(start).map(|bytes| bytes / size) else {
continue;
};
let Some(slot) = page.slots.get(offset) else {
continue;
};
if !slot.value.with(|cell| ptr::eq(cell.cast::<T>(), target)) {
return None;
}
let word = slot.state.load(Ordering::Acquire);
return (word & 1 == 1 && word & !VERSION == 0)
.then(|| Id::new((number * PAGE + offset) as u32, generation_of(word as u32)));
}
None
}
pub fn contains(&self, id: Id) -> bool {
let Some(live) = live_version(id.generation()) else {
return false;
};
self.slot(id.index())
.is_some_and(|slot| slot.state.load(Ordering::Acquire) == u64::from(live))
}
pub fn len(&self) -> usize {
self.len.get()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn index_bound(&self) -> u32 {
self.free.index_bound()
}
pub fn iter(&self) -> AppendIter<'_, T, PAGE> {
AppendIter {
hive: self,
indices: 0..self.index_bound(),
}
}
pub fn get_mut(&mut self, id: Id) -> Option<&mut T> {
let live = live_version(id.generation())?;
let slot = self.slot(id.index())?;
if slot.exclusive_version() != live {
return None;
}
Some(slot.value.with_mut(|cell| {
unsafe { &mut *cell.cast::<T>() }
}))
}
pub fn remove(&mut self, id: Id) -> Option<T> {
let live = live_version(id.generation())?;
let slot = self.slot(id.index())?;
if slot.exclusive_version() != live {
return None;
}
let value = slot.value.with_mut(|cell| {
unsafe { ptr::read(cell.cast::<T>()) }
});
let vacant = vacant(live);
slot.state.store(vacant, Ordering::Release);
if vacant != 0 {
self.free.push(id.index(), &slot.next);
}
self.len.decrement(id.index() as usize / PAGE);
Some(value)
}
pub fn iter_mut(&mut self) -> AppendIterMut<'_, T, PAGE> {
AppendIterMut {
remaining: self.len(),
indices: 0..self.index_bound(),
hive: self,
exclusive: PhantomData,
}
}
pub fn drain(&mut self) -> AppendDrain<'_, T, PAGE> {
let mut values = Vec::with_capacity(self.len());
for index in 0..self.index_bound() {
let Some(slot) = self.slot(index) else {
continue;
};
let version = slot.exclusive_version();
if version & 1 != 0 {
let id = Id::new(index, generation_of(version));
values.push((id, self.remove(id).expect("exclusive live value")));
}
}
AppendDrain {
inner: values.into_iter(),
exclusive: PhantomData,
}
}
pub fn retain(&mut self, mut keep: impl FnMut(Id, &mut T) -> bool) {
for index in 0..self.index_bound() {
let Some(slot) = self.slot(index) else {
continue;
};
let version = slot.exclusive_version();
if version & 1 == 0 {
continue;
}
let id = Id::new(index, generation_of(version));
if !keep(id, self.get_mut(id).expect("exclusive live value")) {
drop(self.remove(id));
}
}
}
pub fn clear(&mut self) {
self.retain(|_, _| false);
}
pub fn shrink_to_fit(&mut self) {
let bound = self.index_bound() as usize;
let mut freed = self.recycled.pending().to_vec();
let installed: Vec<usize> = self.pages.iter().map(|(number, _)| number).collect();
for number in installed {
let base = number * PAGE;
let end = (base + PAGE).min(MAX_INDICES as usize);
if end > bound {
continue;
}
let page = self.pages.get(number).expect("page was just listed");
let mut floor = 0;
let empty = page.slots[..end - base].iter().all(|slot| {
let version = slot.exclusive_version();
floor = floor.max(version);
version & 1 == 0 && version != 0
});
if empty {
drop(self.pages.remove(number));
freed.push((number, floor));
}
}
self.free.reset();
for index in (0..bound as u32).rev() {
if let Some(slot) = self.slot(index) {
let version = slot.exclusive_version();
if version & 1 == 0 && version != 0 {
self.free.push(index, &slot.next);
}
}
}
self.recycled.set(freed);
}
pub fn into_hive(mut self) -> Hive<T, PAGE> {
let bound = self.index_bound() as usize;
let mut unissued = self.free.unissued();
let mut pages = Vec::with_capacity(bound.div_ceil(PAGE));
for base in (0..bound).step_by(PAGE) {
if let Some(floor) = self.recycled.floor_of(base / PAGE) {
pages.push(RawPage {
floor,
slots: Vec::new(),
});
continue;
}
let end = base + PAGE.min(bound - base);
let mut slots = Vec::with_capacity(end - base);
for index in base..end {
let mut version = self.slot(index as u32).map_or(0, Slot::exclusive_version);
if unissued.contains(index as u32) {
debug_assert_eq!(version, 0, "unissued index was used");
version = 2;
}
slots.push(if version & 1 != 0 {
let id = Id::new(index as u32, generation_of(version));
RawSlot::Occupied {
version,
value: self.remove(id).expect("exclusive live value"),
}
} else {
RawSlot::Vacant { version }
});
}
pages.push(RawPage { floor: 0, slots });
}
Hive::try_from_raw_pages(pages).expect("append hive raw pages are valid by construction")
}
pub fn snapshot(&self) -> Hive<T, PAGE>
where
T: Clone,
{
let bound = self.index_bound();
let unissued = self.free.unissued_shared();
let pages = self
.recycled
.snapshot_pages(bound, PAGE)
.map(|(floor, indices)| RawPage {
floor,
slots: indices
.map(|index| match self.snapshot_slot(index, &unissued) {
RawSlot::Occupied { version, value } => RawSlot::Occupied {
version,
value: value.clone(),
},
RawSlot::Vacant { version } => RawSlot::Vacant { version },
})
.collect(),
});
Hive::try_from_raw_pages(pages).expect("append hive snapshot has valid raw pages")
}
#[cfg(all(test, loom))]
pub(super) fn prepare_fresh_page(&self) {
self.ensure_slot(0);
}
#[cfg(all(test, loom))]
pub(super) fn inject_busy_hint(&self, index: u32) {
let slot = self.slot(index).unwrap();
assert_ne!(slot.state.load(Ordering::Acquire) & BUSY, 0);
self.free.push(index, &slot.next);
}
}
impl<T: Clone, const PAGE: usize> Clone for ConcurrentAppendHive<T, PAGE> {
fn clone(&self) -> Self {
Self::from(self.snapshot())
}
}
impl<'a, T, const PAGE: usize> IntoIterator for &'a ConcurrentAppendHive<T, PAGE> {
type Item = (Id, &'a T);
type IntoIter = AppendIter<'a, T, PAGE>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, T, const PAGE: usize> IntoIterator for &'a mut ConcurrentAppendHive<T, PAGE> {
type Item = (Id, &'a mut T);
type IntoIter = AppendIterMut<'a, T, PAGE>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
impl<T, const PAGE: usize> Default for ConcurrentAppendHive<T, PAGE> {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::*;
use crate::hive::serde_impl::raw_pages;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
impl<T: Serialize, const PAGE: usize> Serialize for ConcurrentAppendHive<T, PAGE> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let bound = self.index_bound();
let unissued = self.free.unissued_shared();
raw_pages::serialize(
self.recycled.snapshot_pages(bound, PAGE),
|index| self.snapshot_slot(index, &unissued),
serializer,
)
}
}
impl<'de, T: Deserialize<'de>, const PAGE: usize> Deserialize<'de>
for ConcurrentAppendHive<T, PAGE>
{
fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
Hive::deserialize(deserializer).map(Self::from)
}
}
}
impl<T, const PAGE: usize> From<Hive<T, PAGE>> for ConcurrentAppendHive<T, PAGE> {
fn from(mut hive: Hive<T, PAGE>) -> Self {
let mut out = Self::new();
let metadata: Vec<(u32, Vec<u32>)> = hive
.raw_pages()
.map(|raw| {
let versions = raw
.slots
.into_iter()
.map(|slot| match slot {
RawSlot::Occupied { version, .. } | RawSlot::Vacant { version } => version,
})
.collect();
(raw.floor, versions)
})
.collect();
let mut bound = 0;
for (page, (floor, versions)) in metadata.iter().enumerate() {
let base = page * PAGE;
if *floor != 0 {
bound = base + PAGE.min(MAX_INDICES as usize - base);
} else if !versions.is_empty() {
bound = base + versions.len();
}
}
out.free.set_next_fresh(bound as u32);
for index in 0..bound {
let (floor, versions) = &metadata[index / PAGE];
let version = versions
.get(index % PAGE)
.copied()
.unwrap_or((*floor).max(2));
let slot = out.ensure_slot(index as u32);
if version & 1 == 0 {
slot.state.store(u64::from(version), Ordering::Relaxed);
if version != 0 {
out.free.push(index as u32, &slot.next);
}
}
}
for (id, value) in hive.drain() {
let live = live_version(id.generation()).expect("Hive issues valid generations");
let slot = out.slot(id.index()).expect("copied slot has a page");
out.write_value(slot, id.index(), live, value);
}
out
}
}
impl<T, const PAGE: usize> fmt::Debug for ConcurrentAppendHive<T, PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConcurrentAppendHive")
.field("len", &self.len())
.field("index_bound", &self.index_bound())
.finish_non_exhaustive()
}
}
impl<T, const PAGE: usize> Index<Id> for ConcurrentAppendHive<T, PAGE> {
type Output = T;
fn index(&self, id: Id) -> &T {
self.get(id)
.unwrap_or_else(|| panic!("ConcurrentAppendHive: {id:?} is not live"))
}
}
impl<T, const PAGE: usize> Drop for ConcurrentAppendHive<T, PAGE> {
fn drop(&mut self) {
struct Rest<'a, T, const PAGE: usize>(&'a mut ConcurrentAppendHive<T, PAGE>);
impl<T, const PAGE: usize> Drop for Rest<'_, T, PAGE> {
fn drop(&mut self) {
self.0.clear();
}
}
let rest = Rest(self);
rest.0.clear();
core::mem::forget(rest);
}
}
pub struct AppendIter<'a, T, const PAGE: usize = DEFAULT_PAGE> {
hive: &'a ConcurrentAppendHive<T, PAGE>,
indices: core::ops::Range<u32>,
}
impl<'a, T, const PAGE: usize> Iterator for AppendIter<'a, T, PAGE> {
type Item = (Id, &'a T);
fn next(&mut self) -> Option<Self::Item> {
for index in self.indices.by_ref() {
let Some(slot) = self.hive.slot(index) else {
continue;
};
let word = slot.state.load(Ordering::Acquire);
if word & !VERSION != 0 || word & 1 == 0 {
continue;
}
let value = slot.value.with(|cell| {
unsafe { &*cell.cast::<T>() }
});
return Some((Id::new(index, generation_of(word as u32)), value));
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some((self.indices.end - self.indices.start) as usize))
}
}
impl<T, const PAGE: usize> FusedIterator for AppendIter<'_, T, PAGE> {}
pub struct AppendIterMut<'a, T, const PAGE: usize = DEFAULT_PAGE> {
hive: &'a ConcurrentAppendHive<T, PAGE>,
indices: core::ops::Range<u32>,
remaining: usize,
exclusive: PhantomData<&'a mut ConcurrentAppendHive<T, PAGE>>,
}
impl<'a, T, const PAGE: usize> Iterator for AppendIterMut<'a, T, PAGE> {
type Item = (Id, &'a mut T);
fn next(&mut self) -> Option<Self::Item> {
for index in self.indices.by_ref() {
let Some(slot) = self.hive.slot(index) else {
continue;
};
let version = slot.exclusive_version();
if version & 1 == 0 {
continue;
}
self.remaining -= 1;
let value = slot.value.with_mut(|cell| {
unsafe { &mut *cell.cast::<T>() }
});
return Some((Id::new(index, generation_of(version)), value));
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining, Some(self.remaining))
}
}
impl<T, const PAGE: usize> ExactSizeIterator for AppendIterMut<'_, T, PAGE> {}
impl<T, const PAGE: usize> FusedIterator for AppendIterMut<'_, T, PAGE> {}
pub struct AppendDrain<'a, T, const PAGE: usize = DEFAULT_PAGE> {
inner: alloc::vec::IntoIter<(Id, T)>,
exclusive: PhantomData<&'a mut ConcurrentAppendHive<T, PAGE>>,
}
impl<T, const PAGE: usize> Iterator for AppendDrain<'_, T, PAGE> {
type Item = (Id, T);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<T, const PAGE: usize> DoubleEndedIterator for AppendDrain<'_, T, PAGE> {
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back()
}
}
impl<T, const PAGE: usize> ExactSizeIterator for AppendDrain<'_, T, PAGE> {}
impl<T, const PAGE: usize> FusedIterator for AppendDrain<'_, T, PAGE> {}
#[cfg(all(test, not(loom)))]
mod tests {
use super::*;
use crate::id_alloc::MAX_GENERATION;
use core::num::NonZeroU32;
fn raw_versions<T>(plain: &Hive<T, 4>) -> Vec<u32> {
plain
.raw_pages()
.flat_map(|page| page.slots)
.map(|slot| match slot {
RawSlot::Occupied { version, .. } | RawSlot::Vacant { version } => version,
})
.collect()
}
#[test]
fn unissued_block_tail_becomes_reusable_vacancies() {
let mut hive = ConcurrentAppendHive::<u32, 4>::new();
let a = hive.insert(0);
let b = hive.insert(1);
hive.free.force_blocks();
let c = hive.insert(2);
assert_eq!((a.index(), b.index(), c.index()), (0, 1, 2));
assert_eq!(hive.index_bound(), 64);
assert_eq!(hive.remove(b), Some(1));
hive.shrink_to_fit();
let versions = raw_versions(&hive.snapshot());
assert_eq!(&versions[..4], &[1, 2, 1, 2]);
assert!(versions[4..].iter().all(|&v| v == 0));
#[cfg(feature = "serde")]
{
let json = serde_json::to_string(&hive).unwrap();
let decoded: Hive<u32, 4> = serde_json::from_str(&json).unwrap();
assert_eq!(raw_versions(&decoded), versions);
}
let plain = hive.into_hive();
let versions = raw_versions(&plain);
assert_eq!(versions.len(), 64);
assert_eq!(&versions[..3], &[1, 2, 1]);
assert!(versions[3..].iter().all(|&v| v == 2), "{versions:?}");
assert!(plain.get(b).is_none());
let back = ConcurrentAppendHive::from(plain);
let fresh: Vec<Id> = (0..62).map(|v| back.insert(v)).collect();
assert!(fresh.iter().all(|id| id.index() < 64 && *id != b));
assert!(back.get(b).is_none());
}
#[test]
fn last_live_version_retires_and_even_a_stale_hint_cannot_revive_it() {
let plain = Hive::<u8, 2>::try_from_raw_pages([RawPage {
floor: 0,
slots: alloc::vec![
RawSlot::Occupied {
version: u32::MAX,
value: 7,
},
RawSlot::Vacant { version: 0 },
],
}])
.unwrap();
let mut hive = ConcurrentAppendHive::from(plain);
let last = Id::new(0, NonZeroU32::new(MAX_GENERATION).unwrap());
assert_eq!(hive.get(last), Some(&7));
assert_eq!(hive.iter().next(), Some((last, &7)));
assert_eq!(hive.remove(last), Some(7));
let slot = hive.slot(0).unwrap();
assert_eq!(slot.state.load(Ordering::Acquire), 0);
hive.free.push(0, &slot.next);
let next = hive.insert(8);
assert_eq!(next.index(), 2);
assert!(hive.get(last).is_none());
assert_eq!(hive.len(), 1);
}
#[test]
fn a_live_stack_hint_is_discarded() {
let hive = ConcurrentAppendHive::<u8, 2>::new();
let a = hive.insert(1);
let borrowed = hive.get(a).unwrap();
let slot = hive.slot(a.index()).unwrap();
hive.free.push(a.index(), &slot.next);
let b = hive.insert(2);
assert_ne!(a.index(), b.index());
assert_eq!(*borrowed, 1);
assert_eq!(hive.get(b), Some(&2));
assert_eq!(hive.len(), 2);
}
}