#![no_std]
#![allow(unsafe_code)]
#![deny(missing_docs)]
use core::cell::UnsafeCell;
use core::cmp;
use core::fmt;
use core::fmt::{Debug, Display};
use core::ops::{Deref, DerefMut};
use core::sync::atomic;
use core::sync::atomic::AtomicUsize;
pub struct AtomicRefCell<T: ?Sized> {
borrow: AtomicUsize,
value: UnsafeCell<T>,
}
pub struct BorrowError {
_private: (),
}
impl Debug for BorrowError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BorrowError").finish()
}
}
impl Display for BorrowError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt("already mutably borrowed", f)
}
}
pub struct BorrowMutError {
_private: (),
}
impl Debug for BorrowMutError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BorrowMutError").finish()
}
}
impl Display for BorrowMutError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt("already borrowed", f)
}
}
impl<T> AtomicRefCell<T> {
#[inline]
pub const fn new(value: T) -> AtomicRefCell<T> {
AtomicRefCell {
borrow: AtomicUsize::new(0),
value: UnsafeCell::new(value),
}
}
#[inline]
pub fn into_inner(self) -> T {
debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0);
self.value.into_inner()
}
}
impl<T: ?Sized> AtomicRefCell<T> {
#[inline]
pub fn borrow(&self) -> AtomicRef<T> {
match self.try_borrow() {
Ok(borrowed) => borrowed,
Err(_) => panic!("already mutably borrowed"),
}
}
#[inline]
pub fn try_borrow(&self) -> Result<AtomicRef<T>, BorrowError> {
match AtomicBorrowRef::try_new(&self.borrow) {
Some(borrow) => Ok(AtomicRef {
value: unsafe { &*self.value.get() },
borrow,
}),
None => Err(BorrowError { _private: () }),
}
}
#[inline]
pub fn borrow_mut(&self) -> AtomicRefMut<T> {
let borrow = AtomicBorrowRefMut::new(&self.borrow);
AtomicRefMut {
value: unsafe { &mut *self.value.get() },
borrow,
}
}
#[inline]
pub fn try_borrow_mut(&self) -> Result<AtomicRefMut<T>, BorrowMutError> {
match AtomicBorrowRefMut::try_new(&self.borrow) {
Some(borrow) => Ok(AtomicRefMut {
value: unsafe { &mut *self.value.get() },
borrow,
}),
None => Err(BorrowMutError { _private: () }),
}
}
#[inline]
pub fn as_ptr(&self) -> *mut T {
self.value.get()
}
#[inline]
pub fn get_mut(&mut self) -> &mut T {
debug_assert!(self.borrow.load(atomic::Ordering::Acquire) == 0);
unsafe { &mut *self.value.get() }
}
}
const HIGH_BIT: usize = !(::core::usize::MAX >> 1);
const MAX_FAILED_BORROWS: usize = HIGH_BIT + (HIGH_BIT >> 1);
struct AtomicBorrowRef<'b> {
borrow: &'b AtomicUsize,
}
impl<'b> AtomicBorrowRef<'b> {
#[inline]
fn try_new(borrow: &'b AtomicUsize) -> Option<Self> {
let new = borrow.fetch_add(1, atomic::Ordering::Acquire) + 1;
if new & HIGH_BIT != 0 {
Self::do_sanity_check(borrow, new);
None
} else {
Some(AtomicBorrowRef { borrow: borrow })
}
}
#[cold]
#[inline(never)]
fn do_sanity_check(borrow: &'b AtomicUsize, new: usize) {
if new == HIGH_BIT {
borrow.fetch_sub(1, atomic::Ordering::Release);
panic!("too many immutable borrows");
} else if new >= MAX_FAILED_BORROWS {
struct ForceAbort;
impl Drop for ForceAbort {
fn drop(&mut self) {
panic!("Aborting to avoid unsound state of AtomicRefCell");
}
}
let _abort = ForceAbort;
panic!("Too many failed borrows");
}
}
}
impl<'b> Drop for AtomicBorrowRef<'b> {
#[inline]
fn drop(&mut self) {
let old = self.borrow.fetch_sub(1, atomic::Ordering::Release);
debug_assert!(old & HIGH_BIT == 0);
}
}
struct AtomicBorrowRefMut<'b> {
borrow: &'b AtomicUsize,
}
impl<'b> Drop for AtomicBorrowRefMut<'b> {
#[inline]
fn drop(&mut self) {
self.borrow.store(0, atomic::Ordering::Release);
}
}
impl<'b> AtomicBorrowRefMut<'b> {
#[inline]
fn try_new(borrow: &'b AtomicUsize) -> Option<AtomicBorrowRefMut<'b>> {
match borrow.compare_exchange(
0,
HIGH_BIT,
atomic::Ordering::Acquire,
atomic::Ordering::Relaxed,
) {
Ok(_) => Some(AtomicBorrowRefMut { borrow }),
Err(_) => None,
}
}
#[inline]
fn new(borrow: &'b AtomicUsize) -> AtomicBorrowRefMut<'b> {
let old = match borrow.compare_exchange(
0,
HIGH_BIT,
atomic::Ordering::Acquire,
atomic::Ordering::Relaxed,
) {
Ok(x) => x,
Err(x) => x,
};
assert!(
old == 0,
"already {} borrowed",
if old & HIGH_BIT == 0 {
"immutably"
} else {
"mutably"
}
);
AtomicBorrowRefMut { borrow: borrow }
}
}
unsafe impl<T: ?Sized + Send + Sync> Send for AtomicRefCell<T> {}
unsafe impl<T: ?Sized + Send + Sync> Sync for AtomicRefCell<T> {}
impl<T: Clone> Clone for AtomicRefCell<T> {
#[inline]
fn clone(&self) -> AtomicRefCell<T> {
AtomicRefCell::new(self.borrow().clone())
}
}
impl<T: Default> Default for AtomicRefCell<T> {
#[inline]
fn default() -> AtomicRefCell<T> {
AtomicRefCell::new(Default::default())
}
}
impl<T: ?Sized + PartialEq> PartialEq for AtomicRefCell<T> {
#[inline]
fn eq(&self, other: &AtomicRefCell<T>) -> bool {
*self.borrow() == *other.borrow()
}
}
impl<T: ?Sized + Eq> Eq for AtomicRefCell<T> {}
impl<T: ?Sized + PartialOrd> PartialOrd for AtomicRefCell<T> {
#[inline]
fn partial_cmp(&self, other: &AtomicRefCell<T>) -> Option<cmp::Ordering> {
self.borrow().partial_cmp(&*other.borrow())
}
}
impl<T: ?Sized + Ord> Ord for AtomicRefCell<T> {
#[inline]
fn cmp(&self, other: &AtomicRefCell<T>) -> cmp::Ordering {
self.borrow().cmp(&*other.borrow())
}
}
impl<T> From<T> for AtomicRefCell<T> {
fn from(t: T) -> AtomicRefCell<T> {
AtomicRefCell::new(t)
}
}
impl<'b> Clone for AtomicBorrowRef<'b> {
#[inline]
fn clone(&self) -> AtomicBorrowRef<'b> {
AtomicBorrowRef::try_new(self.borrow).unwrap()
}
}
pub struct AtomicRef<'b, T: ?Sized + 'b> {
value: &'b T,
borrow: AtomicBorrowRef<'b>,
}
impl<'b, T: ?Sized> Deref for AtomicRef<'b, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
self.value
}
}
impl<'b, T: ?Sized> AtomicRef<'b, T> {
#[inline]
pub fn clone(orig: &AtomicRef<'b, T>) -> AtomicRef<'b, T> {
AtomicRef {
value: orig.value,
borrow: orig.borrow.clone(),
}
}
#[inline]
pub fn map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> AtomicRef<'b, U>
where
F: FnOnce(&T) -> &U,
{
AtomicRef {
value: f(orig.value),
borrow: orig.borrow,
}
}
#[inline]
pub fn filter_map<U: ?Sized, F>(orig: AtomicRef<'b, T>, f: F) -> Option<AtomicRef<'b, U>>
where
F: FnOnce(&T) -> Option<&U>,
{
Some(AtomicRef {
value: f(orig.value)?,
borrow: orig.borrow,
})
}
}
impl<'b, T: ?Sized> AtomicRefMut<'b, T> {
#[inline]
pub fn map<U: ?Sized, F>(orig: AtomicRefMut<'b, T>, f: F) -> AtomicRefMut<'b, U>
where
F: FnOnce(&mut T) -> &mut U,
{
AtomicRefMut {
value: f(orig.value),
borrow: orig.borrow,
}
}
#[inline]
pub fn filter_map<U: ?Sized, F>(orig: AtomicRefMut<'b, T>, f: F) -> Option<AtomicRefMut<'b, U>>
where
F: FnOnce(&mut T) -> Option<&mut U>,
{
Some(AtomicRefMut {
value: f(orig.value)?,
borrow: orig.borrow,
})
}
}
pub struct AtomicRefMut<'b, T: ?Sized + 'b> {
value: &'b mut T,
borrow: AtomicBorrowRefMut<'b>,
}
impl<'b, T: ?Sized> Deref for AtomicRefMut<'b, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
self.value
}
}
impl<'b, T: ?Sized> DerefMut for AtomicRefMut<'b, T> {
#[inline]
fn deref_mut(&mut self) -> &mut T {
self.value
}
}
impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRef<'b, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.value.fmt(f)
}
}
impl<'b, T: ?Sized + Debug + 'b> Debug for AtomicRefMut<'b, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.value.fmt(f)
}
}
impl<T: ?Sized + Debug> Debug for AtomicRefCell<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "AtomicRefCell {{ ... }}")
}
}