#[cfg(not(loom))]
use alloc::alloc::{Layout, alloc_zeroed, handle_alloc_error};
use alloc::boxed::Box;
use alloc::vec::{self, Vec};
use core::fmt;
use core::iter::FusedIterator;
use core::mem::{MaybeUninit, needs_drop};
use core::ptr;
use super::atomic::{AtomicPtr, AtomicU32, AtomicU64, CachePadded, Ordering, UnsafeCell, fence};
use super::free_stack::{FreeStack, NONE};
use super::index::{INDEX_CHUNKS, retry};
use super::spine::Spine;
use crate::page::DEFAULT_PAGE;
use crate::paged_deque::PagedDeque;
const WRITE: u32 = 1;
const READ: u32 = 2;
const DESTROY: u32 = 4;
const POOLED: u32 = 1;
const SHIFT: u32 = 1;
const HAS_NEXT: u64 = 1;
const STEP: u64 = 1 << SHIFT;
struct Slot<T> {
value: UnsafeCell<MaybeUninit<T>>,
state: AtomicU32,
}
impl<T> Slot<T> {
fn wait_write(&self) {
let mut spins = 0;
while self.state.load(Ordering::Acquire) & WRITE == 0 {
retry(&mut spins);
}
}
unsafe fn take(&self) -> T {
self.value.with(|cell| {
unsafe { cell.cast::<T>().read() }
})
}
}
struct Block<T, const PAGE: usize> {
next: AtomicPtr<Self>,
pool_next: AtomicU32,
pool_state: AtomicU32,
number: u32,
slots: [Slot<T>; PAGE],
}
impl<T, const PAGE: usize> Block<T, PAGE> {
#[cfg(not(loom))]
fn new(number: u32) -> Box<Self> {
let layout = Layout::new::<Self>();
let raw = unsafe { alloc_zeroed(layout) };
if raw.is_null() {
handle_alloc_error(layout);
}
let mut block: Box<Self> = unsafe { Box::from_raw(raw.cast()) };
block.number = number;
block
}
#[cfg(loom)]
fn new(number: u32) -> Box<Self> {
Box::new(Self {
next: AtomicPtr::new(ptr::null_mut()),
pool_next: AtomicU32::new(0),
pool_state: AtomicU32::new(0),
number,
slots: core::array::from_fn(|_| Slot {
value: UnsafeCell::new(MaybeUninit::uninit()),
state: AtomicU32::new(0),
}),
})
}
fn wait_next(&self) -> *mut Self {
let mut spins = 0;
loop {
let next = self.next.load(Ordering::Acquire);
if !next.is_null() {
return next;
}
retry(&mut spins);
}
}
}
struct Position<T, const PAGE: usize> {
index: AtomicU64,
block: AtomicPtr<Block<T, PAGE>>,
}
pub struct ConcurrentQueue<T, const PAGE: usize = DEFAULT_PAGE> {
head: CachePadded<Position<T, PAGE>>,
tail: CachePadded<Position<T, PAGE>>,
blocks: Spine<Block<T, PAGE>, INDEX_CHUNKS>,
pool: FreeStack,
allocated: AtomicU32,
}
unsafe impl<T: Send, const PAGE: usize> Send for ConcurrentQueue<T, PAGE> {}
unsafe impl<T: Send, const PAGE: usize> Sync for ConcurrentQueue<T, PAGE> {}
impl<T, const PAGE: usize> ConcurrentQueue<T, PAGE> {
const BLOCK_CAP: u64 = PAGE as u64;
const LAP: u64 = Self::BLOCK_CAP + 1;
#[cfg(not(loom))]
pub const fn new() -> Self {
const { assert!(PAGE > 0, "page size must be non-zero") };
Self {
head: CachePadded(Position {
index: AtomicU64::new(0),
block: AtomicPtr::new(ptr::null_mut()),
}),
tail: CachePadded(Position {
index: AtomicU64::new(0),
block: AtomicPtr::new(ptr::null_mut()),
}),
blocks: Spine::new(),
pool: FreeStack::new(),
allocated: AtomicU32::new(0),
}
}
#[cfg(loom)]
pub fn new() -> Self {
const { assert!(PAGE > 0, "page size must be non-zero") };
Self {
head: CachePadded(Position {
index: AtomicU64::new(0),
block: AtomicPtr::new(ptr::null_mut()),
}),
tail: CachePadded(Position {
index: AtomicU64::new(0),
block: AtomicPtr::new(ptr::null_mut()),
}),
blocks: Spine::new(),
pool: FreeStack::new(),
allocated: AtomicU32::new(0),
}
}
pub fn with_capacity(capacity: usize) -> Self {
let queue = Self::new();
let pages = capacity.div_ceil(PAGE);
if pages > 0 {
assert!(
pages <= NONE as usize
&& Spine::<Block<T, PAGE>, INDEX_CHUNKS>::can_allocate_page(pages - 1),
"ConcurrentQueue page capacity overflow"
);
}
for _ in 0..pages {
let number = queue.pool.fresh(NONE, 1).expect("checked page capacity");
queue.pool_block(queue.allocate_block(number));
}
queue
}
fn block(&self, number: u32) -> &Block<T, PAGE> {
self.blocks
.get(number as usize)
.expect("pooled queue block")
}
fn allocate_block(&self, number: u32) -> &Block<T, PAGE> {
let page = number as usize;
assert!(
Spine::<Block<T, PAGE>, INDEX_CHUNKS>::can_allocate_page(page),
"ConcurrentQueue page capacity overflow"
);
let block = self.blocks.get_or_insert_with(page, || Block::new(number));
self.allocated.fetch_add(1, Ordering::Relaxed);
block
}
fn claim_pooled(&self, number: u32) -> Option<&Block<T, PAGE>> {
let block = self.block(number);
block
.pool_state
.compare_exchange(POOLED, 0, Ordering::AcqRel, Ordering::Acquire)
.ok()
.map(|_| block)
}
fn take_block(&self) -> &Block<T, PAGE> {
loop {
let (number, pooled) = self
.pool
.next_index(|n| &self.block(n).pool_next, || None, NONE, 1)
.expect("ConcurrentQueue block numbers exhausted");
if !pooled {
return self.allocate_block(number);
}
if let Some(block) = self.claim_pooled(number) {
#[cfg(all(test, loom))]
REUSED_BLOCK.store(true, core::sync::atomic::Ordering::Relaxed);
return block;
}
}
}
fn pool_block(&self, block: &Block<T, PAGE>) {
block.pool_state.store(POOLED, Ordering::Release);
self.pool.push(block.number, &block.pool_next);
}
fn recycle_block(&self, block: &Block<T, PAGE>) {
for slot in &block.slots {
slot.state.store(0, Ordering::Relaxed);
}
block.next.store(ptr::null_mut(), Ordering::Relaxed);
self.pool_block(block);
}
fn destroy(&self, block: &Block<T, PAGE>, start: usize) {
for slot in &block.slots[start..PAGE - 1] {
if slot.state.load(Ordering::Acquire) & READ == 0
&& slot.state.fetch_or(DESTROY, Ordering::AcqRel) & READ == 0
{
return;
}
}
self.recycle_block(block);
}
pub fn push(&self, value: T) {
let mut spins = 0;
let mut tail = self.tail.0.index.load(Ordering::Acquire);
let mut block = self.tail.0.block.load(Ordering::Acquire);
let mut spare = SpareBlock {
queue: self,
block: None,
};
loop {
let offset = (tail >> SHIFT) % Self::LAP;
if offset == Self::BLOCK_CAP {
#[cfg(all(test, loom))]
BOUNDARY_WAITED.store(true, core::sync::atomic::Ordering::Relaxed);
retry(&mut spins);
tail = self.tail.0.index.load(Ordering::Acquire);
block = self.tail.0.block.load(Ordering::Acquire);
continue;
}
let last = offset + 1 == Self::BLOCK_CAP;
let advance = if last { 2 * STEP } else { STEP };
assert!(
tail <= u64::MAX - advance,
"ConcurrentQueue position overflow"
);
if last && spare.block.is_none() {
spare.block = Some(self.take_block());
}
if block.is_null() {
let first = self.take_block();
let new = ptr::from_ref(first).cast_mut();
if self
.tail
.0
.block
.compare_exchange(block, new, Ordering::Release, Ordering::Relaxed)
.is_ok()
{
self.head.0.block.store(new, Ordering::Release);
block = new;
} else {
#[cfg(all(test, loom))]
INSTALL_LOST.store(true, core::sync::atomic::Ordering::Relaxed);
self.pool_block(first);
tail = self.tail.0.index.load(Ordering::Acquire);
block = self.tail.0.block.load(Ordering::Acquire);
continue;
}
}
let new_tail = tail + STEP;
match self.tail.0.index.compare_exchange_weak(
tail,
new_tail,
Ordering::SeqCst,
Ordering::Acquire,
) {
Ok(_) => {
let block = unsafe { &*block };
if last {
let next = ptr::from_ref(spare.block.take().unwrap()).cast_mut();
self.tail.0.block.store(next, Ordering::Release);
self.tail.0.index.store(new_tail + STEP, Ordering::Release);
block.next.store(next, Ordering::Release);
}
let slot = &block.slots[offset as usize];
slot.value.with_mut(|cell| {
unsafe { cell.write(MaybeUninit::new(value)) };
});
slot.state.fetch_or(WRITE, Ordering::Release);
return;
}
Err(actual) => {
tail = actual;
block = self.tail.0.block.load(Ordering::Acquire);
retry(&mut spins);
}
}
}
}
pub fn pop(&self) -> Option<T> {
self.pop_inner(
#[cfg(all(test, loom))]
|_| {},
)
}
fn pop_inner(
&self,
#[cfg(all(test, loom))] mut checkpoint: impl FnMut(PopStep<T, PAGE>),
) -> Option<T> {
let mut spins = 0;
let mut head = self.head.0.index.load(Ordering::Acquire);
let mut block = self.head.0.block.load(Ordering::Acquire);
loop {
let offset = (head >> SHIFT) % Self::LAP;
if offset == Self::BLOCK_CAP {
retry(&mut spins);
head = self.head.0.index.load(Ordering::Acquire);
block = self.head.0.block.load(Ordering::Acquire);
continue;
}
let mut new_head = head;
if head & HAS_NEXT == 0 {
fence(Ordering::SeqCst);
let tail = self.tail.0.index.load(Ordering::Relaxed);
if head >> SHIFT == tail >> SHIFT {
return None;
}
if (head >> SHIFT) / Self::LAP != (tail >> SHIFT) / Self::LAP {
new_head |= HAS_NEXT;
}
}
if block.is_null() {
retry(&mut spins);
head = self.head.0.index.load(Ordering::Acquire);
block = self.head.0.block.load(Ordering::Acquire);
continue;
}
new_head += STEP;
#[cfg(all(test, loom))]
checkpoint(PopStep::BeforeClaim { head, block });
match self.head.0.index.compare_exchange_weak(
head,
new_head,
Ordering::SeqCst,
Ordering::Acquire,
) {
Ok(_) => {
let block = unsafe { &*block };
let last = offset + 1 == Self::BLOCK_CAP;
if last {
let next = block.wait_next();
let mut next_index = (new_head & !HAS_NEXT) + STEP;
if !unsafe { &*next }.next.load(Ordering::Relaxed).is_null() {
next_index |= HAS_NEXT;
}
self.head.0.block.store(next, Ordering::Release);
self.head.0.index.store(next_index, Ordering::Release);
}
let slot = &block.slots[offset as usize];
slot.wait_write();
let value = unsafe { slot.take() };
if last {
self.destroy(block, 0);
} else if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 {
#[cfg(all(test, loom))]
checkpoint(PopStep::DestroyHandOff);
self.destroy(block, offset as usize + 1);
}
return Some(value);
}
Err(actual) => {
head = actual;
block = self.head.0.block.load(Ordering::Acquire);
retry(&mut spins);
}
}
}
}
pub fn is_empty(&self) -> bool {
let head = self.head.0.index.load(Ordering::SeqCst);
let tail = self.tail.0.index.load(Ordering::SeqCst);
head >> SHIFT == tail >> SHIFT
}
pub fn len(&self) -> usize {
loop {
let tail = self.tail.0.index.load(Ordering::SeqCst);
let head = self.head.0.index.load(Ordering::SeqCst);
if self.tail.0.index.load(Ordering::SeqCst) == tail {
let logical = |position: u64| {
let position = position >> SHIFT;
position - position / Self::LAP
};
return logical(tail).saturating_sub(logical(head)) as usize;
}
}
}
pub fn allocated_pages(&self) -> usize {
self.allocated.load(Ordering::Relaxed) as usize
}
fn pop_exclusive(&mut self, recycle: bool) -> Option<T> {
let head = self.head.0.index.load(Ordering::Relaxed);
let tail = self.tail.0.index.load(Ordering::Relaxed);
if head >> SHIFT == tail >> SHIFT {
return None;
}
let offset = (head >> SHIFT) % Self::LAP;
let raw = self.head.0.block.load(Ordering::Relaxed);
let block = unsafe { &*raw };
let value = unsafe { block.slots[offset as usize].take() };
if offset + 1 == Self::BLOCK_CAP {
let next = block.next.load(Ordering::Relaxed);
self.head.0.block.store(next, Ordering::Relaxed);
self.head
.0
.index
.store((head & !HAS_NEXT) + 2 * STEP, Ordering::Relaxed);
if recycle {
self.recycle_block(block);
}
} else {
self.head.0.index.store(head + STEP, Ordering::Relaxed);
}
Some(value)
}
fn detach_empty_block(&mut self) -> *mut Block<T, PAGE> {
self.tail.0.index.store(0, Ordering::Relaxed);
self.head.0.index.store(0, Ordering::Relaxed);
self.tail.0.block.store(ptr::null_mut(), Ordering::Relaxed);
self.head.0.block.swap(ptr::null_mut(), Ordering::Relaxed)
}
fn pool_empty_block(&mut self) {
let empty = self.detach_empty_block();
if let Some(block) = unsafe { empty.as_ref() } {
self.recycle_block(block);
}
}
pub fn clear(&mut self) {
while let Some(value) = self.pop_exclusive(true) {
drop(value);
}
self.pool_empty_block();
}
pub fn shrink_to_fit(&mut self) {
let values: Vec<T> = core::iter::from_fn(|| self.pop_exclusive(false)).collect();
self.detach_empty_block();
self.pool = FreeStack::new();
self.blocks.clear();
self.allocated.store(0, Ordering::Relaxed);
self.extend(values);
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
let mut head = self.head.0.index.load(Ordering::Relaxed) >> SHIFT;
let tail = self.tail.0.index.load(Ordering::Relaxed) >> SHIFT;
let mut block = self.head.0.block.load(Ordering::Relaxed);
core::iter::from_fn(move || {
if head == tail {
return None;
}
let offset = head % Self::LAP;
let slots = unsafe { &raw const (*block).slots };
let slot = unsafe { &*slots.cast::<Slot<T>>().wrapping_add(offset as usize) };
head += 1;
if offset + 1 == Self::BLOCK_CAP {
let next = unsafe { &(*block).next };
block = next.load(Ordering::Relaxed);
head += 1;
}
Some(slot.value.with_mut(|cell| {
unsafe { &mut *cell.cast::<T>() }
}))
})
}
pub fn drain(&mut self) -> vec::IntoIter<T> {
let mut values = Vec::with_capacity(self.len());
while let Some(value) = self.pop_exclusive(true) {
values.push(value);
}
self.pool_empty_block();
values.into_iter()
}
}
struct SpareBlock<'a, T, const PAGE: usize> {
queue: &'a ConcurrentQueue<T, PAGE>,
block: Option<&'a Block<T, PAGE>>,
}
impl<T, const PAGE: usize> Drop for SpareBlock<'_, T, PAGE> {
fn drop(&mut self) {
if let Some(block) = self.block.take() {
self.queue.pool_block(block);
}
}
}
impl<T, const PAGE: usize> Drop for ConcurrentQueue<T, PAGE> {
fn drop(&mut self) {
struct DropRest<'a, T, const PAGE: usize>(&'a mut ConcurrentQueue<T, PAGE>);
impl<T, const PAGE: usize> Drop for DropRest<'_, T, PAGE> {
fn drop(&mut self) {
while let Some(value) = self.0.pop_exclusive(false) {
drop(value);
}
}
}
if needs_drop::<T>() {
let rest = DropRest(self);
while let Some(value) = rest.0.pop_exclusive(false) {
drop(value);
}
core::mem::forget(rest);
}
}
}
impl<T, const PAGE: usize> Default for ConcurrentQueue<T, PAGE> {
fn default() -> Self {
Self::new()
}
}
impl<T, const PAGE: usize> fmt::Debug for ConcurrentQueue<T, PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConcurrentQueue")
.field("len", &self.len())
.finish()
}
}
impl<T, const PAGE: usize> Extend<T> for ConcurrentQueue<T, PAGE> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for value in iter {
self.push(value);
}
}
}
impl<T, const PAGE: usize> FromIterator<T> for ConcurrentQueue<T, PAGE> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut queue = Self::new();
queue.extend(iter);
queue
}
}
pub struct IntoIter<T, const PAGE: usize> {
queue: ConcurrentQueue<T, PAGE>,
}
impl<T, const PAGE: usize> Iterator for IntoIter<T, PAGE> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.queue.pop_exclusive(false)
}
}
impl<T, const PAGE: usize> FusedIterator for IntoIter<T, PAGE> {}
impl<T, const PAGE: usize> IntoIterator for ConcurrentQueue<T, PAGE> {
type Item = T;
type IntoIter = IntoIter<T, PAGE>;
fn into_iter(self) -> Self::IntoIter {
IntoIter { queue: self }
}
}
impl<T, const PAGE: usize> From<PagedDeque<T, PAGE>> for ConcurrentQueue<T, PAGE> {
fn from(deque: PagedDeque<T, PAGE>) -> Self {
deque.into_iter().collect()
}
}
impl<T, const PAGE: usize> From<ConcurrentQueue<T, PAGE>> for PagedDeque<T, PAGE> {
fn from(queue: ConcurrentQueue<T, PAGE>) -> Self {
queue.into_iter().collect()
}
}
#[cfg(feature = "serde")]
impl<'de, T: serde::Deserialize<'de>, const PAGE: usize> serde::Deserialize<'de>
for ConcurrentQueue<T, PAGE>
{
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
<PagedDeque<T, PAGE> as serde::Deserialize>::deserialize(deserializer).map(Self::from)
}
}
#[cfg(all(test, loom))]
static BOUNDARY_WAITED: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
#[cfg(all(test, loom))]
static REUSED_BLOCK: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
#[cfg(all(test, loom))]
static INSTALL_LOST: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
#[cfg(all(test, loom))]
enum PopStep<T, const PAGE: usize> {
BeforeClaim {
head: u64,
block: *mut Block<T, PAGE>,
},
DestroyHandOff,
}
#[cfg(all(test, loom))]
#[path = "loom_queue.rs"]
mod loom_queue;