use core::cell::UnsafeCell;
use core::fmt;
use core::mem;
use core::ptr;
use core::sync::atomic::{self, AtomicBool, AtomicUsize, Ordering};
#[cfg(feature = "std")]
use std::panic::{RefUnwindSafe, UnwindSafe};
use Backoff;
pub struct AtomicCell<T: ?Sized> {
value: UnsafeCell<T>,
}
unsafe impl<T: Send> Send for AtomicCell<T> {}
unsafe impl<T: Send> Sync for AtomicCell<T> {}
#[cfg(feature = "std")]
impl<T> UnwindSafe for AtomicCell<T> {}
#[cfg(feature = "std")]
impl<T> RefUnwindSafe for AtomicCell<T> {}
impl<T> AtomicCell<T> {
pub fn new(val: T) -> AtomicCell<T> {
AtomicCell {
value: UnsafeCell::new(val),
}
}
pub fn into_inner(self) -> T {
self.value.into_inner()
}
pub fn is_lock_free() -> bool {
atomic_is_lock_free::<T>()
}
pub fn store(&self, val: T) {
if mem::needs_drop::<T>() {
drop(self.swap(val));
} else {
unsafe {
atomic_store(self.value.get(), val);
}
}
}
pub fn swap(&self, val: T) -> T {
unsafe { atomic_swap(self.value.get(), val) }
}
}
impl<T: ?Sized> AtomicCell<T> {
#[inline]
pub fn as_ptr(&self) -> *mut T {
self.value.get()
}
#[doc(hidden)]
#[deprecated(note = "this method is unsound and will be removed in the next release")]
pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.value.get() }
}
}
impl<T: Default> AtomicCell<T> {
pub fn take(&self) -> T {
self.swap(Default::default())
}
}
impl<T: Copy> AtomicCell<T> {
pub fn load(&self) -> T {
unsafe { atomic_load(self.value.get()) }
}
}
impl<T: Copy + Eq> AtomicCell<T> {
pub fn compare_and_swap(&self, current: T, new: T) -> T {
match self.compare_exchange(current, new) {
Ok(v) => v,
Err(v) => v,
}
}
pub fn compare_exchange(&self, current: T, new: T) -> Result<T, T> {
unsafe { atomic_compare_exchange_weak(self.value.get(), current, new) }
}
}
macro_rules! impl_arithmetic {
($t:ty, $example:tt) => {
impl AtomicCell<$t> {
#[doc = $example]
#[inline]
pub fn fetch_add(&self, val: $t) -> $t {
if can_transmute::<$t, atomic::AtomicUsize>() {
let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) };
a.fetch_add(val as usize, Ordering::AcqRel) as $t
} else {
let _guard = lock(self.value.get() as usize).write();
let value = unsafe { &mut *(self.value.get()) };
let old = *value;
*value = value.wrapping_add(val);
old
}
}
#[doc = $example]
#[inline]
pub fn fetch_sub(&self, val: $t) -> $t {
if can_transmute::<$t, atomic::AtomicUsize>() {
let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) };
a.fetch_sub(val as usize, Ordering::AcqRel) as $t
} else {
let _guard = lock(self.value.get() as usize).write();
let value = unsafe { &mut *(self.value.get()) };
let old = *value;
*value = value.wrapping_sub(val);
old
}
}
#[doc = $example]
#[inline]
pub fn fetch_and(&self, val: $t) -> $t {
if can_transmute::<$t, atomic::AtomicUsize>() {
let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) };
a.fetch_and(val as usize, Ordering::AcqRel) as $t
} else {
let _guard = lock(self.value.get() as usize).write();
let value = unsafe { &mut *(self.value.get()) };
let old = *value;
*value &= val;
old
}
}
#[doc = $example]
#[inline]
pub fn fetch_or(&self, val: $t) -> $t {
if can_transmute::<$t, atomic::AtomicUsize>() {
let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) };
a.fetch_or(val as usize, Ordering::AcqRel) as $t
} else {
let _guard = lock(self.value.get() as usize).write();
let value = unsafe { &mut *(self.value.get()) };
let old = *value;
*value |= val;
old
}
}
#[doc = $example]
#[inline]
pub fn fetch_xor(&self, val: $t) -> $t {
if can_transmute::<$t, atomic::AtomicUsize>() {
let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) };
a.fetch_xor(val as usize, Ordering::AcqRel) as $t
} else {
let _guard = lock(self.value.get() as usize).write();
let value = unsafe { &mut *(self.value.get()) };
let old = *value;
*value ^= val;
old
}
}
}
};
($t:ty, $atomic:ty, $example:tt) => {
impl AtomicCell<$t> {
#[doc = $example]
#[inline]
pub fn fetch_add(&self, val: $t) -> $t {
let a = unsafe { &*(self.value.get() as *const $atomic) };
a.fetch_add(val, Ordering::AcqRel)
}
#[doc = $example]
#[inline]
pub fn fetch_sub(&self, val: $t) -> $t {
let a = unsafe { &*(self.value.get() as *const $atomic) };
a.fetch_sub(val, Ordering::AcqRel)
}
#[doc = $example]
#[inline]
pub fn fetch_and(&self, val: $t) -> $t {
let a = unsafe { &*(self.value.get() as *const $atomic) };
a.fetch_and(val, Ordering::AcqRel)
}
#[doc = $example]
#[inline]
pub fn fetch_or(&self, val: $t) -> $t {
let a = unsafe { &*(self.value.get() as *const $atomic) };
a.fetch_or(val, Ordering::AcqRel)
}
#[doc = $example]
#[inline]
pub fn fetch_xor(&self, val: $t) -> $t {
let a = unsafe { &*(self.value.get() as *const $atomic) };
a.fetch_xor(val, Ordering::AcqRel)
}
}
};
($t:ty, $size:tt, $atomic:ty, $example:tt) => {
#[cfg(target_has_atomic = $size)]
impl_arithmetic!($t, $atomic, $example);
};
}
cfg_if! {
if #[cfg(feature = "nightly")] {
impl_arithmetic!(u8, "8", atomic::AtomicU8, "let a = AtomicCell::new(7u8);");
impl_arithmetic!(i8, "8", atomic::AtomicI8, "let a = AtomicCell::new(7i8);");
impl_arithmetic!(u16, "16", atomic::AtomicU16, "let a = AtomicCell::new(7u16);");
impl_arithmetic!(i16, "16", atomic::AtomicI16, "let a = AtomicCell::new(7i16);");
impl_arithmetic!(u32, "32", atomic::AtomicU32, "let a = AtomicCell::new(7u32);");
impl_arithmetic!(i32, "32", atomic::AtomicI32, "let a = AtomicCell::new(7i32);");
impl_arithmetic!(u64, "64", atomic::AtomicU64, "let a = AtomicCell::new(7u64);");
impl_arithmetic!(i64, "64", atomic::AtomicI64, "let a = AtomicCell::new(7i64);");
impl_arithmetic!(u128, "let a = AtomicCell::new(7u128);");
impl_arithmetic!(i128, "let a = AtomicCell::new(7i128);");
} else {
impl_arithmetic!(u8, "let a = AtomicCell::new(7u8);");
impl_arithmetic!(i8, "let a = AtomicCell::new(7i8);");
impl_arithmetic!(u16, "let a = AtomicCell::new(7u16);");
impl_arithmetic!(i16, "let a = AtomicCell::new(7i16);");
impl_arithmetic!(u32, "let a = AtomicCell::new(7u32);");
impl_arithmetic!(i32, "let a = AtomicCell::new(7i32);");
impl_arithmetic!(u64, "let a = AtomicCell::new(7u64);");
impl_arithmetic!(i64, "let a = AtomicCell::new(7i64);");
impl_arithmetic!(u128, "let a = AtomicCell::new(7u128);");
impl_arithmetic!(i128, "let a = AtomicCell::new(7i128);");
}
}
impl_arithmetic!(
usize,
atomic::AtomicUsize,
"let a = AtomicCell::new(7usize);"
);
impl_arithmetic!(
isize,
atomic::AtomicIsize,
"let a = AtomicCell::new(7isize);"
);
impl AtomicCell<bool> {
#[inline]
pub fn fetch_and(&self, val: bool) -> bool {
let a = unsafe { &*(self.value.get() as *const AtomicBool) };
a.fetch_and(val, Ordering::AcqRel)
}
#[inline]
pub fn fetch_or(&self, val: bool) -> bool {
let a = unsafe { &*(self.value.get() as *const AtomicBool) };
a.fetch_or(val, Ordering::AcqRel)
}
#[inline]
pub fn fetch_xor(&self, val: bool) -> bool {
let a = unsafe { &*(self.value.get() as *const AtomicBool) };
a.fetch_xor(val, Ordering::AcqRel)
}
}
impl<T: Default> Default for AtomicCell<T> {
fn default() -> AtomicCell<T> {
AtomicCell::new(T::default())
}
}
impl<T: Copy + fmt::Debug> fmt::Debug for AtomicCell<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("AtomicCell")
.field("value", &self.load())
.finish()
}
}
fn can_transmute<A, B>() -> bool {
mem::size_of::<A>() == mem::size_of::<B>() && mem::align_of::<A>() >= mem::align_of::<B>()
}
struct Lock {
state: AtomicUsize,
}
impl Lock {
#[inline]
fn optimistic_read(&self) -> Option<usize> {
let state = self.state.load(Ordering::Acquire);
if state == 1 {
None
} else {
Some(state)
}
}
#[inline]
fn validate_read(&self, stamp: usize) -> bool {
atomic::fence(Ordering::Acquire);
self.state.load(Ordering::Relaxed) == stamp
}
#[inline]
fn write(&'static self) -> WriteGuard {
let backoff = Backoff::new();
loop {
let previous = self.state.swap(1, Ordering::Acquire);
if previous != 1 {
atomic::fence(Ordering::Release);
return WriteGuard {
lock: self,
state: previous,
};
}
backoff.snooze();
}
}
}
struct WriteGuard {
lock: &'static Lock,
state: usize,
}
impl WriteGuard {
#[inline]
fn abort(self) {
self.lock.state.store(self.state, Ordering::Release);
}
}
impl Drop for WriteGuard {
#[inline]
fn drop(&mut self) {
self.lock
.state
.store(self.state.wrapping_add(2), Ordering::Release);
}
}
#[inline]
#[must_use]
fn lock(addr: usize) -> &'static Lock {
const LEN: usize = 97;
const L: Lock = Lock {
state: AtomicUsize::new(0),
};
static LOCKS: [Lock; LEN] = [
L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L,
];
&LOCKS[addr % LEN]
}
struct AtomicUnit;
impl AtomicUnit {
#[inline]
fn load(&self, _order: Ordering) {}
#[inline]
fn store(&self, _val: (), _order: Ordering) {}
#[inline]
fn swap(&self, _val: (), _order: Ordering) {}
#[inline]
fn compare_exchange_weak(
&self,
_current: (),
_new: (),
_success: Ordering,
_failure: Ordering,
) -> Result<(), ()> {
Ok(())
}
}
macro_rules! atomic {
(@check, $t:ty, $atomic:ty, $a:ident, $atomic_op:expr) => {
if can_transmute::<$t, $atomic>() {
let $a: &$atomic;
break $atomic_op;
}
};
($t:ty, $a:ident, $atomic_op:expr, $fallback_op:expr) => {
loop {
atomic!(@check, $t, AtomicUnit, $a, $atomic_op);
atomic!(@check, $t, atomic::AtomicUsize, $a, $atomic_op);
#[cfg(feature = "nightly")]
{
#[cfg(target_has_atomic = "8")]
atomic!(@check, $t, atomic::AtomicU8, $a, $atomic_op);
#[cfg(target_has_atomic = "16")]
atomic!(@check, $t, atomic::AtomicU16, $a, $atomic_op);
#[cfg(target_has_atomic = "32")]
atomic!(@check, $t, atomic::AtomicU32, $a, $atomic_op);
#[cfg(target_has_atomic = "64")]
atomic!(@check, $t, atomic::AtomicU64, $a, $atomic_op);
}
break $fallback_op;
}
};
}
fn atomic_is_lock_free<T>() -> bool {
atomic! { T, _a, true, false }
}
unsafe fn atomic_load<T>(src: *mut T) -> T
where
T: Copy,
{
atomic! {
T, a,
{
a = &*(src as *const _ as *const _);
mem::transmute_copy(&a.load(Ordering::Acquire))
},
{
let lock = lock(src as usize);
if let Some(stamp) = lock.optimistic_read() {
let val = ptr::read_volatile(src);
if lock.validate_read(stamp) {
return val;
}
}
let guard = lock.write();
let val = ptr::read(src);
guard.abort();
val
}
}
}
unsafe fn atomic_store<T>(dst: *mut T, val: T) {
atomic! {
T, a,
{
a = &*(dst as *const _ as *const _);
a.store(mem::transmute_copy(&val), Ordering::Release);
mem::forget(val);
},
{
let _guard = lock(dst as usize).write();
ptr::write(dst, val);
}
}
}
unsafe fn atomic_swap<T>(dst: *mut T, val: T) -> T {
atomic! {
T, a,
{
a = &*(dst as *const _ as *const _);
let res = mem::transmute_copy(&a.swap(mem::transmute_copy(&val), Ordering::AcqRel));
mem::forget(val);
res
},
{
let _guard = lock(dst as usize).write();
ptr::replace(dst, val)
}
}
}
unsafe fn atomic_compare_exchange_weak<T>(dst: *mut T, mut current: T, new: T) -> Result<T, T>
where
T: Copy + Eq,
{
atomic! {
T, a,
{
a = &*(dst as *const _ as *const _);
let mut current_raw = mem::transmute_copy(¤t);
let new_raw = mem::transmute_copy(&new);
loop {
match a.compare_exchange_weak(
current_raw,
new_raw,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => break Ok(current),
Err(previous_raw) => {
let previous = mem::transmute_copy(&previous_raw);
if !T::eq(&previous, ¤t) {
break Err(previous);
}
current = previous;
current_raw = previous_raw;
}
}
}
},
{
let guard = lock(dst as usize).write();
if T::eq(&*dst, ¤t) {
Ok(ptr::replace(dst, new))
} else {
let val = ptr::read(dst);
guard.abort();
Err(val)
}
}
}
}