use crate::loom::cell::UnsafeCell;
use crate::loom::sync::atomic::{AtomicPtr, AtomicUsize};
use std::alloc::Layout;
use std::mem::MaybeUninit;
use std::ops;
use std::ptr::{self, NonNull};
use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Release};
pub(crate) struct Block<T> {
header: BlockHeader<T>,
values: Values<T>,
}
struct BlockHeader<T> {
start_index: usize,
next: AtomicPtr<Block<T>>,
ready_slots: AtomicUsize,
observed_tail_position: UnsafeCell<usize>,
}
pub(crate) enum Read<T> {
Value(T),
Closed,
}
#[repr(transparent)]
struct Values<T>([UnsafeCell<MaybeUninit<T>>; BLOCK_CAP]);
use super::BLOCK_CAP;
const BLOCK_MASK: usize = !(BLOCK_CAP - 1);
const SLOT_MASK: usize = BLOCK_CAP - 1;
const RELEASED: usize = 1 << BLOCK_CAP;
const TX_CLOSED: usize = RELEASED << 1;
const READY_MASK: usize = RELEASED - 1;
#[inline(always)]
pub(crate) fn start_index(slot_index: usize) -> usize {
BLOCK_MASK & slot_index
}
#[inline(always)]
pub(crate) fn offset(slot_index: usize) -> usize {
SLOT_MASK & slot_index
}
generate_addr_of_methods! {
impl<T> Block<T> {
unsafe fn addr_of_header(self: NonNull<Self>) -> NonNull<BlockHeader<T>> {
&self.header
}
unsafe fn addr_of_values(self: NonNull<Self>) -> NonNull<Values<T>> {
&self.values
}
}
}
impl<T> Block<T> {
pub(crate) fn new(start_index: usize) -> Box<Block<T>> {
unsafe {
let block = std::alloc::alloc(Layout::new::<Block<T>>()) as *mut Block<T>;
let block = match NonNull::new(block) {
Some(block) => block,
None => std::alloc::handle_alloc_error(Layout::new::<Block<T>>()),
};
Block::addr_of_header(block).as_ptr().write(BlockHeader {
start_index,
next: AtomicPtr::new(ptr::null_mut()),
ready_slots: AtomicUsize::new(0),
observed_tail_position: UnsafeCell::new(0),
});
Values::initialize(Block::addr_of_values(block));
Box::from_raw(block.as_ptr())
}
}
pub(crate) fn is_at_index(&self, index: usize) -> bool {
debug_assert!(offset(index) == 0);
self.header.start_index == index
}
pub(crate) fn distance(&self, other_index: usize) -> usize {
debug_assert!(offset(other_index) == 0);
other_index.wrapping_sub(self.header.start_index) / BLOCK_CAP
}
pub(crate) unsafe fn read(&self, slot_index: usize) -> Option<Read<T>> {
let offset = offset(slot_index);
let ready_bits = self.header.ready_slots.load(Acquire);
if !is_ready(ready_bits, offset) {
if is_tx_closed(ready_bits) {
return Some(Read::Closed);
}
return None;
}
let value = self.values[offset].with(|ptr| unsafe { ptr::read(ptr) });
Some(Read::Value(unsafe { value.assume_init() }))
}
pub(crate) fn has_value(&self, slot_index: usize) -> bool {
if slot_index < self.header.start_index {
return false;
}
if slot_index >= self.header.start_index + super::BLOCK_CAP {
return false;
}
let offset = offset(slot_index);
let ready_bits = self.header.ready_slots.load(Acquire);
is_ready(ready_bits, offset)
}
pub(crate) unsafe fn write(&self, slot_index: usize, value: T) {
let slot_offset = offset(slot_index);
self.values[slot_offset].with_mut(|ptr| {
unsafe {
ptr::write(ptr, MaybeUninit::new(value));
}
});
self.set_ready(slot_offset);
}
pub(crate) unsafe fn tx_close(&self) {
self.header.ready_slots.fetch_or(TX_CLOSED, Release);
}
pub(crate) unsafe fn is_closed(&self) -> bool {
let ready_bits = self.header.ready_slots.load(Acquire);
is_tx_closed(ready_bits)
}
pub(crate) unsafe fn reclaim(&mut self) {
self.header.start_index = 0;
self.header.next = AtomicPtr::new(ptr::null_mut());
self.header.ready_slots = AtomicUsize::new(0);
}
pub(crate) unsafe fn tx_release(&self, tail_position: usize) {
self.header
.observed_tail_position
.with_mut(|ptr| unsafe { *ptr = tail_position });
self.header.ready_slots.fetch_or(RELEASED, Release);
}
fn set_ready(&self, slot: usize) {
let mask = 1 << slot;
self.header.ready_slots.fetch_or(mask, Release);
}
pub(crate) fn is_final(&self) -> bool {
self.header.ready_slots.load(Acquire) & READY_MASK == READY_MASK
}
pub(crate) fn observed_tail_position(&self) -> Option<usize> {
if 0 == RELEASED & self.header.ready_slots.load(Acquire) {
None
} else {
Some(
self.header
.observed_tail_position
.with(|ptr| unsafe { *ptr }),
)
}
}
pub(crate) fn load_next(&self, ordering: Ordering) -> Option<NonNull<Block<T>>> {
let ret = NonNull::new(self.header.next.load(ordering));
debug_assert!(unsafe {
ret.map_or(true, |block| {
block.as_ref().header.start_index == self.header.start_index.wrapping_add(BLOCK_CAP)
})
});
ret
}
pub(crate) unsafe fn try_push(
&self,
block: &mut NonNull<Block<T>>,
success: Ordering,
failure: Ordering,
) -> Result<(), NonNull<Block<T>>> {
unsafe { block.as_mut() }.header.start_index =
self.header.start_index.wrapping_add(BLOCK_CAP);
let next_ptr = self
.header
.next
.compare_exchange(ptr::null_mut(), block.as_ptr(), success, failure)
.unwrap_or_else(|x| x);
match NonNull::new(next_ptr) {
Some(next_ptr) => Err(next_ptr),
None => Ok(()),
}
}
pub(crate) fn grow(&self) -> NonNull<Block<T>> {
let new_block = Block::new(self.header.start_index + BLOCK_CAP);
let mut new_block = unsafe { NonNull::new_unchecked(Box::into_raw(new_block)) };
let next = NonNull::new(
self.header
.next
.compare_exchange(ptr::null_mut(), new_block.as_ptr(), AcqRel, Acquire)
.unwrap_or_else(|x| x),
);
let next = match next {
Some(next) => next,
None => {
return new_block;
}
};
let mut curr = next;
loop {
let actual = unsafe { curr.as_ref().try_push(&mut new_block, AcqRel, Acquire) };
curr = match actual {
Ok(()) => {
return next;
}
Err(curr) => curr,
};
crate::loom::thread::yield_now();
}
}
}
fn is_ready(bits: usize, slot: usize) -> bool {
let mask = 1 << slot;
mask == mask & bits
}
fn is_tx_closed(bits: usize) -> bool {
TX_CLOSED == bits & TX_CLOSED
}
impl<T> Values<T> {
unsafe fn initialize(_value: NonNull<Values<T>>) {
if_loom! {
let p = _value.as_ptr() as *mut UnsafeCell<MaybeUninit<T>>;
for i in 0..BLOCK_CAP {
unsafe {
p.add(i).write(UnsafeCell::new(MaybeUninit::uninit()));
}
}
}
}
}
impl<T> ops::Index<usize> for Values<T> {
type Output = UnsafeCell<MaybeUninit<T>>;
fn index(&self, index: usize) -> &Self::Output {
self.0.index(index)
}
}
#[cfg(all(test, not(loom)))]
#[test]
fn assert_no_stack_overflow() {
struct Foo {
_a: [u8; 2_000_000],
}
assert_eq!(
Layout::new::<MaybeUninit<Block<Foo>>>(),
Layout::new::<Block<Foo>>()
);
let _block = Block::<Foo>::new(0);
}