use std::{
fmt,
sync::atomic::{
AtomicUsize,
Ordering::{AcqRel, Acquire, Release},
},
};
const RUNNING: usize = 0b0001;
const COMPLETE: usize = 0b0010;
const LIFECYCLE_MASK: usize = 0b11;
const NOTIFIED: usize = 0b100;
const JOIN_INTEREST: usize = 0b1_000;
const JOIN_WAKER: usize = 0b10_000;
const CANCELLED: usize = 0b100_000;
const STATE_MASK: usize = LIFECYCLE_MASK | NOTIFIED | JOIN_INTEREST | JOIN_WAKER | CANCELLED;
const REF_COUNT_MASK: usize = !STATE_MASK;
const REF_COUNT_SHIFT: usize = REF_COUNT_MASK.count_zeros() as usize;
const REF_ONE: usize = 1 << REF_COUNT_SHIFT;
const INITIAL_STATE: usize = (REF_ONE * 2) | JOIN_INTEREST | NOTIFIED;
#[must_use]
pub(super) enum TransitionToRunning {
Success,
Cancelled,
Failed,
Dealloc,
}
#[must_use]
pub(super) enum TransitionToIdle {
Ok,
OkNotified,
OkDealloc,
Cancelled,
}
#[must_use]
pub(super) enum TransitionToNotified {
DoNothing,
Submit,
Dealloc,
}
#[must_use]
pub(super) enum TransitionToCancelled {
DoNothing,
Submit,
}
#[must_use]
pub(super) struct TransitionToJoinHandleDrop {
pub(super) drop_waker: bool,
pub(super) drop_output: bool,
}
pub(super) struct State(AtomicUsize);
#[derive(Copy, Clone)]
pub(super) struct Snapshot(usize);
impl State {
#[must_use]
pub(super) fn new() -> State {
State(AtomicUsize::new(INITIAL_STATE))
}
pub(super) fn get_snapshot(&self) -> Snapshot {
Snapshot(self.0.load(Acquire))
}
pub(super) fn transition_to_running(&self) -> TransitionToRunning {
self.fetch_update(|mut state| {
assert!(state.is_notified());
let action;
if !state.is_idle() {
state.ref_dec();
if state.ref_count() == 0 {
action = TransitionToRunning::Dealloc;
} else {
action = TransitionToRunning::Failed;
}
} else {
state.set_running();
state.unset_notified();
if state.is_cancelled() {
action = TransitionToRunning::Cancelled;
} else {
action = TransitionToRunning::Success;
}
}
(action, Some(state))
})
}
pub(super) fn transition_to_idle(&self) -> TransitionToIdle {
self.fetch_update(|mut state| {
assert!(state.is_running());
if state.is_cancelled() {
return (TransitionToIdle::Cancelled, None);
}
let action;
state.unset_running();
if !state.is_notified() {
state.ref_dec();
if state.ref_count() == 0 {
action = TransitionToIdle::OkDealloc;
} else {
action = TransitionToIdle::Ok;
}
} else {
state.ref_inc();
action = TransitionToIdle::OkNotified;
}
(action, Some(state))
})
}
pub(super) fn transition_to_complete(&self) -> Snapshot {
const DELTA: usize = RUNNING | COMPLETE;
let prev_state = Snapshot(self.0.fetch_xor(DELTA, AcqRel));
assert!(prev_state.is_running());
assert!(!prev_state.is_complete());
Snapshot(prev_state.0 ^ DELTA)
}
pub(super) fn transition_to_notified_by_val(&self) -> TransitionToNotified {
self.fetch_update(|mut state| {
let action;
if state.is_running() {
state.set_notified();
state.ref_dec();
assert!(state.ref_count() > 0);
action = TransitionToNotified::DoNothing;
} else if state.is_complete() || state.is_notified() {
state.ref_dec();
if state.ref_count() == 0 {
action = TransitionToNotified::Dealloc;
} else {
action = TransitionToNotified::DoNothing;
}
} else {
state.set_notified();
state.ref_inc();
action = TransitionToNotified::Submit;
}
(action, Some(state))
})
}
pub(super) fn transition_to_notified_by_ref(&self) -> TransitionToNotified {
self.fetch_update(|mut state| {
if state.is_complete() {
(TransitionToNotified::DoNothing, None)
} else if state.is_notified() {
(TransitionToNotified::DoNothing, Some(state))
} else if state.is_running() {
state.set_notified();
(TransitionToNotified::DoNothing, Some(state))
} else {
state.set_notified();
state.ref_inc();
(TransitionToNotified::Submit, Some(state))
}
})
}
pub(super) fn transition_to_cancelled(&self) -> TransitionToCancelled {
self.fetch_update(|mut state| {
if state.is_complete() || state.is_cancelled() {
return (TransitionToCancelled::DoNothing, None);
}
state.set_cancelled();
if state.is_idle() && !state.is_notified() {
state.set_notified();
state.ref_inc();
(TransitionToCancelled::Submit, Some(state))
} else {
(TransitionToCancelled::DoNothing, Some(state))
}
})
}
pub(super) fn drop_join_handle_fast(&self) -> Result<(), ()> {
use std::sync::atomic::Ordering::Relaxed;
self.0
.compare_exchange_weak(
INITIAL_STATE,
(INITIAL_STATE - REF_ONE) & !JOIN_INTEREST,
Release,
Relaxed,
)
.map(|_| ())
.map_err(|_| ())
}
pub(super) fn transition_to_join_handle_dropped(&self) -> TransitionToJoinHandleDrop {
self.fetch_update(|mut state| {
assert!(state.is_join_interested());
let mut transition = TransitionToJoinHandleDrop {
drop_waker: false,
drop_output: false,
};
state.unset_join_interested();
if !state.is_complete() {
state.unset_join_waker();
} else {
transition.drop_output = true;
}
if !state.is_join_waker_set() {
transition.drop_waker = true;
}
(transition, Some(state))
})
}
pub(super) fn set_join_waker(&self) -> Result<Snapshot, Snapshot> {
let res = self.0.fetch_update(AcqRel, Acquire, |curr| {
let state = Snapshot(curr);
assert!(state.is_join_interested());
assert!(!state.is_join_waker_set());
if state.is_complete() {
return None;
}
let mut next = state;
next.set_join_waker();
Some(next.0)
});
match res {
Err(val) => Err(Snapshot(val)),
Ok(val) => Ok(Snapshot(val)),
}
}
pub(super) fn unset_waker(&self) -> Result<Snapshot, Snapshot> {
let res = self.0.fetch_update(AcqRel, Acquire, |curr| {
let state = Snapshot(curr);
assert!(state.is_join_interested());
if state.is_complete() {
return None;
}
assert!(state.is_join_waker_set());
let mut next = state;
next.unset_join_waker();
Some(next.0)
});
match res {
Err(val) => Err(Snapshot(val)),
Ok(val) => Ok(Snapshot(val)),
}
}
pub(super) fn unset_waker_after_complete(&self) -> Snapshot {
let prev = Snapshot(self.0.fetch_and(!JOIN_WAKER, AcqRel));
assert!(prev.is_complete());
assert!(prev.is_join_waker_set());
Snapshot(prev.0 & !JOIN_WAKER)
}
fn fetch_update<F, T>(&self, mut f: F) -> T
where
F: FnMut(Snapshot) -> (T, Option<Snapshot>),
{
let mut curr = self.get_snapshot();
loop {
let (output, next) = f(curr);
let next = match next {
Some(next) => next,
None => return output,
};
let res = self.0.compare_exchange(curr.0, next.0, AcqRel, Acquire);
match res {
Ok(_) => return output,
Err(actual) => curr = Snapshot(actual),
}
}
}
pub(super) fn ref_inc(&self) {
use std::{process, sync::atomic::Ordering::Relaxed};
let prev = self.0.fetch_add(REF_ONE, Relaxed);
if prev > isize::MAX as usize {
process::abort();
}
}
pub(super) fn ref_dec(&self) -> bool {
let prev = Snapshot(self.0.fetch_sub(REF_ONE, AcqRel));
assert!(prev.ref_count() >= 1);
prev.ref_count() == 1
}
}
impl Snapshot {
pub(super) fn is_idle(&self) -> bool {
self.0 & (RUNNING | COMPLETE) == 0
}
pub(super) fn is_notified(&self) -> bool {
self.0 & NOTIFIED == NOTIFIED
}
pub(super) fn unset_notified(&mut self) {
self.0 &= !NOTIFIED
}
pub(super) fn set_notified(&mut self) {
self.0 |= NOTIFIED
}
pub(super) fn is_running(&self) -> bool {
self.0 & RUNNING == RUNNING
}
pub(super) fn set_running(&mut self) {
self.0 |= RUNNING;
}
pub(super) fn unset_running(&mut self) {
self.0 &= !RUNNING;
}
pub(super) fn is_cancelled(self) -> bool {
self.0 & CANCELLED == CANCELLED
}
fn set_cancelled(&mut self) {
self.0 |= CANCELLED;
}
pub(super) fn is_complete(&self) -> bool {
self.0 & COMPLETE == COMPLETE
}
pub(super) fn is_join_interested(&self) -> bool {
self.0 & JOIN_INTEREST == JOIN_INTEREST
}
pub(super) fn unset_join_interested(&mut self) {
self.0 &= !JOIN_INTEREST
}
pub(super) fn is_join_waker_set(self) -> bool {
self.0 & JOIN_WAKER == JOIN_WAKER
}
fn set_join_waker(&mut self) {
self.0 |= JOIN_WAKER;
}
fn unset_join_waker(&mut self) {
self.0 &= !JOIN_WAKER;
}
pub(super) fn ref_count(self) -> usize {
(self.0 & REF_COUNT_MASK) >> REF_COUNT_SHIFT
}
fn ref_inc(&mut self) {
assert!(self.0 <= isize::MAX as usize);
self.0 += REF_ONE;
}
pub(super) fn ref_dec(&mut self) {
assert!(self.ref_count() > 0);
self.0 -= REF_ONE;
}
}
impl fmt::Debug for Snapshot {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("Snapshot")
.field("is_running", &self.is_running())
.field("is_complete", &self.is_complete())
.field("is_notified", &self.is_notified())
.field("is_cancelled", &self.is_cancelled())
.field("is_join_interested", &self.is_join_interested())
.field("is_join_waker_set", &self.is_join_waker_set())
.field("ref_count", &self.ref_count())
.finish()
}
}