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::Deref;
use core::ptr;
use super::atomic::{AtomicU32, AtomicU64, Ordering, UnsafeCell, spin_loop};
use super::count::StripedLen;
use super::free_stack::{FreeStack, 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;
const MARKED: u64 = 1 << 33;
const TAKE: u64 = 1 << 34;
const REF: u64 = 1 << 35;
const REFS: u64 = !(REF - 1);
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()),
}
}
}
struct Page<T> {
slots: Box<[Slot<T>]>,
}
fn vacant(live: u32) -> u64 {
u64::from(live.checked_add(1).unwrap_or(0))
}
fn matches(word: u64, version: u32) -> bool {
word & VERSION == u64::from(version) && word & (BUSY | MARKED) == 0
}
fn retry(spins: &mut u32) {
*spins = spins.saturating_add(1);
#[cfg(all(feature = "std", not(loom)))]
if *spins >= 64 {
std::thread::yield_now();
return;
}
spin_loop();
}
pub struct ConcurrentHive<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 ConcurrentHive<T, PAGE> {}
unsafe impl<T: Send + Sync, const PAGE: usize> Sync for ConcurrentHive<T, PAGE> {}
struct Busy<'a, T, const PAGE: usize> {
hive: &'a ConcurrentHive<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> ConcurrentHive<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>>(),
"ConcurrentHive: 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 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 busy<'a>(&'a self, slot: &'a Slot<T>, index: u32, vacant: u64) -> Busy<'a, T, PAGE> {
Busy {
hive: self,
slot,
index,
vacant,
armed: true,
}
}
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((self.busy(slot, index, vacant(live)), 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!("ConcurrentHive: 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!("ConcurrentHive: 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))
}
fn acquire(&self, index: u32, expected: Option<u32>) -> Option<Ref<'_, T, PAGE>> {
let slot = self.slot(index)?;
let mut word = slot.state.load(Ordering::Acquire);
loop {
let live = word as u32;
if live & 1 == 0
|| word & (BUSY | MARKED) != 0
|| expected.is_some_and(|version| version != live)
{
return None;
}
assert!(word & REFS != REFS, "ConcurrentHive: guard count overflow");
match slot.state.compare_exchange_weak(
word,
word + REF,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => {
return Some(Ref {
hive: self,
slot,
index,
version: live,
#[cfg(loom)]
access: Some(slot.value.read()),
});
}
Err(actual) => word = actual,
}
}
}
pub fn get(&self, id: Id) -> Option<Ref<'_, T, PAGE>> {
self.acquire(id.index(), Some(live_version(id.generation())?))
}
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| matches(slot.state.load(Ordering::Acquire), live))
}
pub fn remove(&self, id: Id) -> bool {
let Some(live) = live_version(id.generation()) else {
return false;
};
let Some(slot) = self.slot(id.index()) else {
return false;
};
let mut word = slot.state.load(Ordering::Acquire);
loop {
if !matches(word, live) {
return false;
}
let direct = word & REFS == 0;
let new = if direct {
vacant(live) | BUSY
} else {
word | MARKED
};
match slot
.state
.compare_exchange_weak(word, new, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => {
self.len.decrement(id.index() as usize / PAGE);
if direct {
let owner = self.busy(slot, id.index(), vacant(live));
self.drop_owned(&owner);
}
return true;
}
Err(actual) => word = actual,
}
}
}
fn drop_owned(&self, owner: &Busy<'_, T, PAGE>) {
owner.slot.value.with_mut(|cell| {
unsafe { ptr::drop_in_place(cell.cast::<T>()) };
});
}
pub fn take(&self, id: Id) -> Option<T> {
let live = live_version(id.generation())?;
let slot = self.slot(id.index())?;
let mut word = slot.state.load(Ordering::Acquire);
loop {
if !matches(word, live) {
return None;
}
match slot.state.compare_exchange_weak(
word,
word | MARKED | TAKE,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => break,
Err(actual) => word = actual,
}
}
self.len.decrement(id.index() as usize / PAGE);
let mut spins = 0;
loop {
let word = slot.state.load(Ordering::Acquire);
if word & REFS == 0
&& slot
.state
.compare_exchange(
u64::from(live) | MARKED | TAKE,
vacant(live) | BUSY,
Ordering::AcqRel,
Ordering::Acquire,
)
.is_ok()
{
let owner = self.busy(slot, id.index(), vacant(live));
let value = slot.value.with_mut(|cell| {
unsafe { ptr::read(cell.cast::<T>()) }
});
drop(owner);
return Some(value);
}
retry(&mut spins);
}
}
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) -> Iter<'_, T, PAGE> {
Iter {
hive: self,
indices: 0..self.index_bound(),
}
}
fn normalize_slot(&mut self, index: u32) {
let Some(slot) = self.slot(index) else {
return;
};
let word = slot.state.load(Ordering::Acquire);
if word & 1 == 0 {
return;
}
if word & MARKED != 0 {
let vacant = vacant(word as u32);
slot.state.store(vacant | BUSY, Ordering::Release);
let owner = self.busy(slot, index, vacant);
self.drop_owned(&owner);
} else if word & REFS != 0 {
slot.state.store(word & !REFS, Ordering::Release);
}
}
fn normalize(&mut self) {
for index in 0..self.index_bound() {
self.normalize_slot(index);
}
}
pub fn get_mut(&mut self, id: Id) -> Option<&mut T> {
self.normalize_slot(id.index());
let live = live_version(id.generation())?;
let slot = self.slot(id.index())?;
if !matches(slot.state.load(Ordering::Acquire), live) {
return None;
}
Some(slot.value.with_mut(|cell| {
unsafe { &mut *cell.cast::<T>() }
}))
}
pub fn take_mut(&mut self, id: Id) -> Option<T> {
self.normalize_slot(id.index());
self.take(id)
}
pub fn iter_mut(&mut self) -> IterMut<'_, T, PAGE> {
self.normalize();
IterMut {
remaining: self.len(),
indices: 0..self.index_bound(),
hive: self,
exclusive: PhantomData,
}
}
pub fn clear(&mut self) {
self.retain(|_, _| false);
}
pub fn drain(&mut self) -> Drain<'_, T, PAGE> {
self.normalize();
let mut values = Vec::with_capacity(self.len());
for index in 0..self.index_bound() {
let Some(slot) = self.slot(index) else {
continue;
};
let word = slot.state.load(Ordering::Acquire);
if word & 1 != 0 {
let id = Id::new(index, generation_of(word as u32));
values.push((id, self.take(id).expect("normalized live value")));
}
}
Drain {
inner: values.into_iter(),
exclusive: PhantomData,
}
}
pub fn retain(&mut self, mut keep: impl FnMut(Id, &mut T) -> bool) {
self.normalize();
for index in 0..self.index_bound() {
let Some(slot) = self.slot(index) else {
continue;
};
let word = slot.state.load(Ordering::Acquire);
if word & 1 == 0 {
continue;
}
let id = Id::new(index, generation_of(word as u32));
let keep_value = keep(id, self.get_mut(id).expect("normalized live value"));
if !keep_value {
drop(self.take(id));
}
}
}
pub fn shrink_to_fit(&mut self) {
self.normalize();
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 word = slot.state.load(Ordering::Relaxed);
debug_assert_eq!(word & !VERSION, 0, "normalized slot has flags");
let version = word as u32;
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.state.load(Ordering::Relaxed) as u32;
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> {
self.normalize();
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| {
let word = slot.state.load(Ordering::Acquire);
debug_assert!(word & !VERSION == 0);
word as u32
});
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.take(id).expect("normalized live value"),
}
} else {
RawSlot::Vacant { version }
});
}
pages.push(RawPage { floor: 0, slots });
}
Hive::try_from_raw_pages(pages)
.expect("concurrent hive raw pages are valid by construction")
}
#[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, const PAGE: usize> Default for ConcurrentHive<T, PAGE> {
fn default() -> Self {
Self::new()
}
}
impl<T, const PAGE: usize> From<Hive<T, PAGE>> for ConcurrentHive<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 ConcurrentHive<T, PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConcurrentHive")
.field("len", &self.len())
.field("index_bound", &self.index_bound())
.finish_non_exhaustive()
}
}
impl<T, const PAGE: usize> Drop for ConcurrentHive<T, PAGE> {
fn drop(&mut self) {
struct Rest<'a, T, const PAGE: usize>(&'a mut ConcurrentHive<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 Ref<'a, T, const PAGE: usize = DEFAULT_PAGE> {
hive: &'a ConcurrentHive<T, PAGE>,
slot: &'a Slot<T>,
index: u32,
version: u32,
#[cfg(loom)]
access: Option<loom::cell::ConstPtr<MaybeUninit<T>>>,
}
unsafe impl<T: Send + Sync, const PAGE: usize> Send for Ref<'_, T, PAGE> {}
unsafe impl<T: Send + Sync, const PAGE: usize> Sync for Ref<'_, T, PAGE> {}
impl<T, const PAGE: usize> Ref<'_, T, PAGE> {
pub fn id(&self) -> Id {
Id::new(self.index, generation_of(self.version))
}
}
impl<T, const PAGE: usize> Deref for Ref<'_, T, PAGE> {
type Target = T;
fn deref(&self) -> &T {
self.slot.value.with(|cell| {
unsafe { &*cell.cast::<T>() }
})
}
}
impl<T: fmt::Debug, const PAGE: usize> fmt::Debug for Ref<'_, T, PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ref")
.field("id", &self.id())
.field("value", &**self)
.finish()
}
}
impl<T, const PAGE: usize> Drop for Ref<'_, T, PAGE> {
fn drop(&mut self) {
#[cfg(loom)]
drop(self.access.take());
let mut word = self.slot.state.load(Ordering::Acquire);
loop {
debug_assert!(word & REFS != 0);
let finalize = word & REFS == REF && word & MARKED != 0 && word & TAKE == 0;
let new = if finalize {
vacant(self.version) | BUSY
} else {
word - REF
};
match self.slot.state.compare_exchange_weak(
word,
new,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => {
if finalize {
let owner = self.hive.busy(self.slot, self.index, vacant(self.version));
self.hive.drop_owned(&owner);
}
return;
}
Err(actual) => word = actual,
}
}
}
}
pub struct Iter<'a, T, const PAGE: usize = DEFAULT_PAGE> {
hive: &'a ConcurrentHive<T, PAGE>,
indices: core::ops::Range<u32>,
}
impl<'a, T, const PAGE: usize> Iterator for Iter<'a, T, PAGE> {
type Item = (Id, Ref<'a, T, PAGE>);
fn next(&mut self) -> Option<Self::Item> {
for index in self.indices.by_ref() {
if let Some(value) = self.hive.acquire(index, None) {
return Some((value.id(), 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 Iter<'_, T, PAGE> {}
pub struct IterMut<'a, T, const PAGE: usize = DEFAULT_PAGE> {
hive: &'a ConcurrentHive<T, PAGE>,
indices: core::ops::Range<u32>,
remaining: usize,
exclusive: PhantomData<&'a mut ConcurrentHive<T, PAGE>>,
}
impl<'a, T, const PAGE: usize> Iterator for IterMut<'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 word = slot.state.load(Ordering::Acquire);
if word & 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(word as u32)), value));
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining, Some(self.remaining))
}
}
impl<T, const PAGE: usize> ExactSizeIterator for IterMut<'_, T, PAGE> {}
impl<T, const PAGE: usize> FusedIterator for IterMut<'_, T, PAGE> {}
pub struct Drain<'a, T, const PAGE: usize = DEFAULT_PAGE> {
inner: alloc::vec::IntoIter<(Id, T)>,
exclusive: PhantomData<&'a mut ConcurrentHive<T, PAGE>>,
}
impl<T, const PAGE: usize> Iterator for Drain<'_, 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 Drain<'_, T, PAGE> {
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back()
}
}
impl<T, const PAGE: usize> ExactSizeIterator for Drain<'_, T, PAGE> {}
impl<T, const PAGE: usize> FusedIterator for Drain<'_, T, PAGE> {}
#[cfg(all(test, not(loom), feature = "std"))]
mod tests {
use super::*;
use crate::id_alloc::MAX_GENERATION;
use core::num::NonZeroU32;
use std::panic::{AssertUnwindSafe, catch_unwind};
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 = ConcurrentHive::<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!(hive.remove(b));
hive.shrink_to_fit();
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());
assert_eq!((plain.get(a), plain.get(c)), (Some(&0), Some(&2)));
let back = ConcurrentHive::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());
assert_eq!(back.index_bound(), 64);
}
#[test]
fn last_generation_retires_to_plain_zero() {
let hive = ConcurrentHive::<u8, 2>::new();
let old = hive.insert(7);
let slot = hive.slot(old.index()).unwrap();
slot.state.store(u64::from(u32::MAX), Ordering::Release);
let last = Id::new(old.index(), NonZeroU32::new(MAX_GENERATION).unwrap());
assert!(hive.remove(last));
assert_eq!(slot.state.load(Ordering::Acquire), 0);
hive.free.push(old.index(), &slot.next);
let new = hive.insert(8);
assert_ne!(old.index(), new.index());
assert!(!hive.contains(last));
assert_eq!(hive.len(), 1);
}
#[test]
fn overflow_panics_without_wrapping_the_count() {
let mut hive = ConcurrentHive::<u8, 2>::new();
let id = hive.insert(7);
let slot = hive.slot(id.index()).unwrap();
slot.state.store(1 | REFS, Ordering::Release);
assert!(catch_unwind(AssertUnwindSafe(|| hive.get(id))).is_err());
assert_eq!(slot.state.load(Ordering::Acquire), 1 | REFS);
assert_eq!(hive.take_mut(id), Some(7));
assert!(hive.is_empty());
}
#[cfg_attr(miri, ignore)]
#[test]
fn the_last_slots_below_u32_max_hold_values_and_exhaust_exactly() {
let mut hive = ConcurrentHive::<u64, 4096>::new();
hive.free.set_next_fresh(MAX_INDICES - 2);
let a = hive.insert(1);
let b = hive.insert(2);
assert_eq!((a.index(), b.index()), (MAX_INDICES - 2, MAX_INDICES - 1));
assert_eq!(hive.try_insert(3), Err(3));
assert_eq!(hive.index_bound(), MAX_INDICES);
assert_eq!((*hive.get(a).unwrap(), *hive.get(b).unwrap()), (1, 2));
let top = Id::new(MAX_INDICES, b.generation());
assert!(hive.get(top).is_none() && !hive.remove(top));
assert_eq!(hive.take(top), None);
assert_eq!(hive.take(b), Some(2));
let c = hive.insert(4);
assert_eq!(c.index(), MAX_INDICES - 1);
assert!(c != b && hive.get(b).is_none());
assert_eq!(*hive.get(c).unwrap(), 4);
assert_eq!(hive.try_insert(5), Err(5));
assert_eq!(hive.len(), 2);
core::mem::forget(hive);
}
#[test]
fn a_live_stack_hint_is_discarded() {
let hive = ConcurrentHive::<u8, 2>::new();
let a = hive.insert(1);
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!(*hive.get(a).unwrap(), 1);
assert_eq!(*hive.get(b).unwrap(), 2);
assert_eq!(hive.len(), 2);
}
}